Skip to main content

core_crypto/mls/conversation/mutable/
commit.rs

1//! The methods in this module all produce or handle commits.
2
3use std::{borrow::Borrow, collections::HashMap};
4
5use openmls::prelude::{CredentialWithKey, KeyPackageIn};
6use openmls_traits::OpenMlsCryptoProvider as _;
7
8use super::history_sharing::HistoryClientUpdateOutcome;
9use crate::{
10    ClientId, ClientIdRef, Commit, CredentialRef, DecryptedMessage, GroupInfoBundle, OpenMlsError, RecursiveError,
11    mls::{
12        conversation::{ConversationMut, Error, Result, commit::CommitBundle},
13        credential::{Credential, ext::CredentialExt as _},
14    },
15};
16
17impl ConversationMut {
18    pub(super) async fn send_and_merge_commit(&mut self, commit: CommitBundle) -> Result<()> {
19        let history_client_update_result = self.update_history_client().await?;
20        if history_client_update_result == HistoryClientUpdateOutcome::CommitSentAndMerged {
21            return Ok(());
22        }
23
24        if let Err(send_err) = self.send_commit(commit).await {
25            // on error, cleanup, but don't let that cleanup result override the outer result
26            if let Err(cleanup_error) = self.clear_pending_commit().await {
27                log::warn!(
28                    cleanup_error:err;
29                    "failed to clear the pending commit after the delivery service rejected it"
30                );
31            }
32            return Err(send_err);
33        }
34        self.merge_commit().await.map(|_| ())
35    }
36
37    /// Merge the pending commit, returning the [`Commit`] produced.
38    ///
39    /// This adapts [Self::commit_accepted] to return a type compatible with
40    /// [crate::mls::conversation::ConversationMut::decrypt_message], and also
41    /// ensures that the epoch change is propagated.
42    pub(crate) async fn merge_commit(&mut self) -> Result<DecryptedMessage> {
43        self.commit_accepted().await?;
44
45        self.tx_context
46            .queue_epoch_changed(self.id.clone(), self.epoch().await)
47            .await
48            .map_err(RecursiveError::context("queueing epoch changed notification"))?;
49
50        let group = self.group().await;
51
52        let own_leaf = group
53            .own_leaf()
54            .ok_or(Error::MlsGroupInvalidState("own_leaf is None"))?;
55
56        // We return self identity here, probably not necessary to check revocation
57        let own_leaf_credential_with_key = CredentialWithKey {
58            credential: own_leaf.credential().clone(),
59            signature_key: own_leaf.signature_key().clone(),
60        };
61        let pki_env = self.crypto_provider().await?.authentication_service().pki_env().await;
62        let identity = own_leaf_credential_with_key
63            .extract_identity(self.cipher_suite().await.signature_algorithm(), pki_env.as_deref())
64            .await
65            .map_err(RecursiveError::context("extracting identity"))?;
66
67        let decrypted_message = DecryptedMessage::Commit(Commit {
68            is_active: self.group().await.is_active(),
69            identity,
70        });
71
72        Ok(decrypted_message)
73    }
74
75    /// Send the commit via [crate::MlsTransport] and handle the response.
76    pub(super) async fn send_commit(&mut self, commit: CommitBundle) -> Result<()> {
77        let transport = self.transport().await?;
78
79        transport
80            .send_commit_bundle(commit)
81            .await
82            .map_err(RecursiveError::context("sending commit bundle"))
83            .map_err(Into::into)
84    }
85
86    /// Adds new members to the group/conversation
87    pub async fn add_members(&mut self, key_packages: Vec<KeyPackageIn>) -> Result<()> {
88        let commit = self.add_members_inner(key_packages).await?;
89
90        self.send_and_merge_commit(commit).await?;
91
92        Ok(())
93    }
94
95    pub(super) async fn add_members_inner(&mut self, key_packages: Vec<KeyPackageIn>) -> Result<CommitBundle> {
96        self.ensure_no_pending_commit().await?;
97        let backend = self.crypto_provider().await?;
98        let credential = self.credential().await?;
99
100        self.mutate_group(async |_, group, _| {
101            let signer = credential.signature_key();
102            let (commit, welcome, group_info) = group
103                .add_members(&backend, signer, key_packages.clone())
104                .await
105                .map_err(|err| {
106                    if Self::err_is_duplicate_signature_key(&err) {
107                        Self::clients_with_duplicate_signature_keys(key_packages.as_ref())
108                            .map(|affected_clients| Error::DuplicateSignature { affected_clients })
109                            .unwrap_or_else(|e| e)
110                    } else {
111                        OpenMlsError::wrap("group add members")(err).into()
112                    }
113                })?;
114
115            Ok(CommitBundle {
116                commit,
117                welcome: Some(welcome),
118                group_info: Self::group_info(group_info)?,
119                encrypted_message: None,
120            })
121        })
122        .await
123    }
124
125    fn err_is_duplicate_signature_key(
126        err: &openmls::prelude::AddMembersError<core_crypto_keystore::CryptoKeystoreError>,
127    ) -> bool {
128        matches!(
129            err,
130            openmls::prelude::AddMembersError::CreateCommitError(
131                openmls::prelude::CreateCommitError::ProposalValidationError(
132                    openmls::prelude::ProposalValidationError::DuplicateSignatureKey
133                )
134            )
135        )
136    }
137
138    fn clients_with_duplicate_signature_keys(key_packages: &[KeyPackageIn]) -> Result<Vec<(ClientId, ClientId)>> {
139        let mut seen_signature_keys = HashMap::new();
140        let mut duplicate_pairs = Vec::new();
141
142        for key_package in key_packages {
143            let signature_key = key_package.unverified_credential().signature_key.as_slice().to_vec();
144
145            let client_id: ClientId = key_package
146                .credential()
147                .identity()
148                .try_into()
149                .map_err(RecursiveError::context("client id from bytes"))?;
150
151            if let Some(previous_client_id) = seen_signature_keys.insert(signature_key, client_id.clone()) {
152                duplicate_pairs.push((previous_client_id, client_id));
153            }
154        }
155
156        Ok(duplicate_pairs)
157    }
158
159    /// Removes clients from the group/conversation.
160    ///
161    /// # Arguments
162    /// * `id` - group/conversation id
163    /// * `clients` - list of client ids to be removed from the group
164    pub async fn remove_members(&mut self, clients: &[impl Borrow<ClientIdRef>]) -> Result<()> {
165        self.remove_members_or_history_clients(clients.iter().map(|e| e.borrow().as_ref()))
166            .await
167    }
168
169    pub(crate) async fn remove_members_or_history_clients(
170        &mut self,
171        clients: impl Iterator<Item = &[u8]> + Clone,
172    ) -> Result<()> {
173        self.ensure_no_pending_commit().await?;
174        let backend = self.crypto_provider().await?;
175        let credential = self.credential().await?;
176        let signer = credential.signature_key();
177        let (commit, welcome, group_info) = self
178            .mutate_group(async |_, group, _| {
179                let members = group
180                    .members()
181                    .filter_map(|member| {
182                        clients
183                            .clone()
184                            .any(move |client_id| client_id == member.credential.identity())
185                            .then_some(member.index)
186                    })
187                    .collect::<Vec<_>>();
188                group
189                    .remove_members(&backend, signer, &members)
190                    .await
191                    .map_err(OpenMlsError::wrap("group remove members"))
192                    .map_err(Into::into)
193            })
194            .await?;
195
196        let group_info = Self::group_info(group_info)?;
197
198        self.send_and_merge_commit(CommitBundle {
199            commit,
200            welcome,
201            group_info,
202            encrypted_message: None,
203        })
204        .await
205    }
206
207    /// Self updates the own leaf node and automatically commits. Pending proposals will be committed.
208    pub async fn update_key_material(&mut self) -> Result<()> {
209        let credential = self.credential().await?;
210        let commit = self.set_credential_inner(&credential).await?;
211        self.send_and_merge_commit(commit).await
212    }
213
214    /// Set the referenced credential for this conversation.
215    pub async fn set_credential_by_ref(&mut self, credential_ref: &CredentialRef) -> Result<()> {
216        let database = self.database()?;
217        let credential = credential_ref
218            .load(&*database)
219            .await
220            .map_err(RecursiveError::context("loading credential from ref"))?;
221        let commit = self.set_credential_inner(&credential).await?;
222
223        self.send_and_merge_commit(commit).await
224    }
225
226    /// Self updates the own leaf node with the given credential and automatically commits. Pending proposals will be
227    /// committed.
228    pub(crate) async fn set_credential_inner(&mut self, credential: &Credential) -> Result<CommitBundle> {
229        self.ensure_no_pending_commit().await?;
230        let backend = self.crypto_provider().await?;
231        let credential = credential.clone();
232
233        self.mutate_group(async |_, group, _| {
234            // If the credential remains the same and we still want to update, we explicitly need to pass `None` to
235            // openmls, if we just passed an unchanged leaf node, no update commit would be created.
236            // Also, we can avoid cloning in the case we don't need to create a new leaf node.
237            let updated_leaf_node = {
238                let leaf_node = group
239                    .own_leaf()
240                    .ok_or(Error::MlsGroupInvalidState("own leaf node not found"))?;
241                if leaf_node.credential() == &credential.mls_credential {
242                    None
243                } else {
244                    let mut leaf_node = leaf_node.clone();
245                    leaf_node.set_credential_with_key(credential.to_mls_credential_with_key());
246                    Some(leaf_node)
247                }
248            };
249
250            let (commit, welcome, group_info) = group
251                .explicit_self_update(&backend, &credential.signature_key_pair, updated_leaf_node)
252                .await
253                .map_err(OpenMlsError::wrap("group self update"))?;
254
255            // We should always have ratchet tree extension turned on hence GroupInfo should always be present
256            let group_info = group_info.ok_or(Error::MissingGroupInfo)?;
257            let group_info = GroupInfoBundle::try_new_full_plaintext(group_info)?;
258
259            Ok(CommitBundle {
260                welcome,
261                commit,
262                group_info,
263                encrypted_message: None,
264            })
265        })
266        .await
267    }
268
269    /// Commits all pending proposals of the group
270    pub async fn commit_pending_proposals(&mut self) -> Result<()> {
271        self.ensure_no_pending_commit().await?;
272        let commit = self.commit_pending_proposals_inner().await?;
273        let Some(commit) = commit else {
274            return Ok(());
275        };
276        self.send_and_merge_commit(commit).await
277    }
278
279    pub(crate) async fn commit_pending_proposals_inner(&mut self) -> Result<Option<CommitBundle>> {
280        if self.group().await.pending_proposals().next().is_none() {
281            return Ok(None);
282        }
283
284        let crypto_provider = self.crypto_provider().await?;
285        let credential = self.credential().await?;
286
287        let (commit, welcome, openmls_group_info) = self
288            .mutate_group(async |_, group, _| {
289                let signer = &credential.signature_key_pair;
290                group
291                    .commit_to_pending_proposals(&crypto_provider, signer)
292                    .await
293                    .map_err(OpenMlsError::wrap("group commit to pending proposals"))
294                    .map_err(Into::into)
295            })
296            .await?;
297        let group_info = GroupInfoBundle::try_new_full_plaintext(
298            openmls_group_info.expect("creating a commit always produces a group info"),
299        )?;
300
301        Ok(Some(CommitBundle {
302            welcome,
303            commit,
304            group_info,
305            encrypted_message: None,
306        }))
307    }
308
309    pub(crate) async fn commit_inline_proposals(
310        &mut self,
311        proposals: Vec<openmls::prelude::Proposal>,
312    ) -> Result<Option<CommitBundle>> {
313        if proposals.is_empty() {
314            return Ok(None);
315        }
316
317        let provider = &self.crypto_provider().await?;
318        let credential = self.credential().await?;
319
320        let (commit, welcome, openmls_group_info) = self
321            .mutate_group(async |_, group, _| {
322                let signer = &credential.signature_key_pair;
323                group
324                    .commit_to_inline_proposals(provider, signer, proposals)
325                    .await
326                    .map_err(OpenMlsError::wrap("group commit to pending proposals"))
327                    .map_err(Into::into)
328            })
329            .await?;
330        let group_info = GroupInfoBundle::try_new_full_plaintext(
331            openmls_group_info.expect("creating a commit always produces a group info"),
332        )?;
333
334        Ok(Some(CommitBundle {
335            welcome,
336            commit,
337            group_info,
338            encrypted_message: None,
339        }))
340    }
341}