Skip to main content

core_crypto/mls/conversation/
commit.rs

1//! This table summarizes when an MLS group can create a commit or proposal:
2//!
3//! | can create handshake ? | 0 pend. Commit | 1 pend. Commit |
4//! |------------------------|----------------|----------------|
5//! | 0 pend. Proposal       | ✅              | ❌              |
6//! | 1+ pend. Proposal      | ✅              | ❌              |
7
8use openmls::prelude::MlsMessageOut;
9
10use super::Result;
11use crate::{GroupInfoBundle, TlsCodecError, mls::conversation::WelcomeMessage};
12
13/// Returned when a commit is created
14#[derive(Debug, Clone)]
15pub struct CommitBundle {
16    /// A welcome message if there are pending Add proposals
17    pub welcome: Option<MlsMessageOut>,
18    /// The commit message
19    pub commit: MlsMessageOut,
20    /// `GroupInfo` if the commit is merged
21    pub group_info: GroupInfoBundle,
22    /// An encrypted message to fan out to all other conversation members in the new epoch
23    pub encrypted_message: Option<Vec<u8>>,
24}
25
26impl CommitBundle {
27    /// Unpacks this struct and serializes the commit
28    ///
29    /// 0 -> welcome
30    /// 1 -> message
31    /// 2 -> public group state
32    pub fn to_bytes_triple(self) -> Result<(Option<WelcomeMessage>, Vec<u8>, GroupInfoBundle)> {
33        use openmls::prelude::TlsSerializeTrait as _;
34        let welcome = self.welcome.map(Into::into);
35        let commit = self
36            .commit
37            .tls_serialize_detached()
38            .map_err(TlsCodecError::serialize("serialize commit"))?;
39        Ok((welcome, commit, self.group_info))
40    }
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46    use crate::{
47        DeferralReason, RejectionReason, mls::conversation::Error, test_utils::*,
48        transaction_context::Error as TransactionError,
49    };
50
51    mod add_members {
52        use std::sync::Arc;
53
54        use super::*;
55        use crate::Credential;
56
57        #[apply(all_cred_cipher)]
58        async fn can_add_members_to_conversation(case: TestContext) {
59            let [alice, bob] = case.sessions().await;
60            Box::pin(async move {
61                let conversation = case.create_conversation([&alice]).await;
62                let id = conversation.id.clone();
63                let bob_keypackage = bob.new_keypackage(&case).await;
64                // First, abort commit transport
65                alice
66                    .replace_transport(Arc::<CoreCryptoTransportAbortProvider>::default())
67                    .await;
68                alice
69                    .transaction
70                    .conversation(&id)
71                    .await
72                    .unwrap()
73                    .add_members(vec![bob_keypackage.clone().into()])
74                    .await
75                    .unwrap_err();
76
77                // commit is not applied
78                assert_eq!(conversation.member_count().await, 1);
79
80                alice
81                    .replace_transport(Arc::<CoreCryptoTransportSuccessProvider>::default())
82                    .await;
83
84                let conversation = conversation.invite_notify([&bob]).await;
85
86                assert_eq!(*conversation.id(), id);
87                assert_eq!(
88                    conversation.guard().await.group().await.group_id().as_slice(),
89                    id.as_ref().as_ref()
90                );
91                assert_eq!(conversation.member_count().await, 2);
92                assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
93            })
94            .await
95        }
96
97        #[apply(all_cred_cipher)]
98        async fn should_fail_on_duplicate_signatures(case: TestContext) {
99            let [alice, bob, carol] = case.sessions().await;
100            Box::pin(async move {
101                let conversation = case.create_conversation([&alice]).await;
102                let id = conversation.id.clone();
103                let bob_keypackage = bob.new_keypackage(&case).await;
104                let signature_key_pair = bob
105                    .find_any_credential(case.cipher_suite(), case.credential_type)
106                    .await
107                    .signature_key_pair
108                    .clone();
109                let credential = Credential {
110                    cipher_suite: case.cipher_suite(),
111                    credential_type: CredentialType::Basic,
112                    mls_credential: openmls::credentials::Credential::new_basic(
113                        carol.get_client_id().await.into_inner(),
114                    ),
115                    signature_key_pair,
116                    earliest_validity: 0,
117                };
118                let cred_ref = carol.add_credential(credential).await.unwrap();
119                let carol_key_package = carol.new_keypackage_from_ref(cred_ref, None).await;
120                let _affected_clients = [(carol.get_client_id().await, bob.get_client_id().await)];
121
122                let error = alice
123                    .transaction
124                    .conversation(&id)
125                    .await
126                    .unwrap()
127                    .add_members(vec![bob_keypackage.clone().into(), carol_key_package.clone().into()])
128                    .await
129                    .unwrap_err();
130
131                assert!(matches!(
132                    error,
133                    Error::DuplicateSignature {
134                        affected_clients: _affected_clients
135                    }
136                ));
137            })
138            .await
139        }
140
141        #[apply(all_cred_cipher)]
142        async fn should_return_valid_welcome(case: TestContext) {
143            let [alice, bob] = case.sessions().await;
144            Box::pin(async move {
145                let conversation = case.create_conversation([&alice, &bob]).await;
146                assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
147            })
148            .await
149        }
150
151        #[apply(all_cred_cipher)]
152        async fn should_return_valid_group_info(case: TestContext) {
153            let [alice, bob, guest] = case.sessions().await;
154            Box::pin(async move {
155                let conversation = case.create_conversation([&alice, &bob]).await;
156                let commit_bundle = alice.mls_transport().await.latest_commit_bundle().await;
157                let group_info = commit_bundle.group_info.get_group_info();
158                let conversation = conversation
159                    .external_join_via_group_info_notify(&guest, group_info)
160                    .await;
161                assert!(conversation.is_functional_and_contains([&alice, &bob, &guest]).await);
162            })
163            .await
164        }
165    }
166
167    mod remove_members {
168        use super::*;
169
170        #[apply(all_cred_cipher)]
171        async fn alice_can_remove_bob_from_conversation(case: TestContext) {
172            let [alice, bob] = case.sessions().await;
173            Box::pin(async move {
174                let conversation = case.create_conversation([&alice, &bob]).await.remove_notify(&bob).await;
175                let id = conversation.id().clone();
176
177                let CommitBundle { welcome, .. } = alice.mls_transport().await.latest_commit_bundle().await;
178                assert!(welcome.is_none());
179
180                assert_eq!(conversation.member_count().await, 1);
181
182                // But has been removed from the conversation
183                assert!(matches!(
184                bob.transaction.conversation(&id).await.unwrap_err(),
185                TransactionError::ConversationNotFound(ref i)
186                    if i == &id
187                ));
188                assert!(!conversation.can_talk(&alice, &bob).await);
189            })
190            .await;
191        }
192
193        #[apply(all_cred_cipher)]
194        async fn should_return_valid_group_info(case: TestContext) {
195            let [alice, bob, guest] = case.sessions().await;
196            Box::pin(async move {
197                let conversation = case.create_conversation([&alice, &bob]).await.remove_notify(&bob).await;
198                let commit_bundle = alice.mls_transport().await.latest_commit_bundle().await;
199                let group_info = commit_bundle.group_info.get_group_info();
200                let conversation = conversation
201                    .external_join_via_group_info_notify(&guest, group_info)
202                    .await;
203
204                assert!(conversation.is_functional_and_contains([&alice, &guest]).await);
205                // because Bob has been removed from the group
206                assert!(!conversation.can_talk(&alice, &bob).await);
207            })
208            .await;
209        }
210    }
211
212    mod update_keying_material {
213        use super::*;
214
215        #[apply(all_cred_cipher)]
216        async fn should_succeed(case: TestContext) {
217            let [alice, bob] = case.sessions().await;
218            Box::pin(async move {
219                let conversation = case.create_conversation([&alice, &bob]).await;
220                let init_count = alice.transaction.count_entities().await;
221
222                let bob_keys = conversation.guard_of(&bob).await.encryption_keys().await;
223                let alice_keys = conversation.guard().await.encryption_keys().await;
224                assert!(alice_keys.iter().all(|a_key| bob_keys.contains(a_key)));
225
226                let alice_key = conversation.encryption_public_key().await;
227
228                // proposing the key update for alice
229                let conversation = conversation.update_notify().await;
230                let CommitBundle { welcome, .. } = alice.mls_transport().await.latest_commit_bundle().await;
231                assert!(welcome.is_none());
232
233                let alice_new_keys = conversation.guard().await.encryption_keys().await;
234                assert!(!alice_new_keys.contains(&alice_key));
235
236                let bob_new_keys = conversation.guard_of(&bob).await.encryption_keys().await;
237                assert!(alice_new_keys.iter().all(|a_key| bob_new_keys.contains(a_key)));
238
239                // ensuring both can encrypt messages
240                assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
241
242                // make sure inline update commit + merge does not leak anything
243                // that's obvious since no new encryption keypair is created in this case
244                let final_count = alice.transaction.count_entities().await;
245                assert_eq!(init_count, final_count);
246            })
247            .await;
248        }
249
250        #[apply(all_cred_cipher)]
251        async fn should_return_valid_group_info(case: TestContext) {
252            let [alice, bob, guest] = case.sessions().await;
253            Box::pin(async move {
254                let conversation = case.create_conversation([&alice, &bob]).await.update_notify().await;
255
256                let group_info = alice.mls_transport().await.latest_group_info().await;
257                let group_info = group_info.get_group_info();
258
259                let conversation = conversation
260                    .external_join_via_group_info_notify(&guest, group_info)
261                    .await;
262                assert!(conversation.is_functional_and_contains([&alice, &bob, &guest]).await);
263            })
264            .await;
265        }
266    }
267
268    mod commit_pending_proposals {
269        use super::*;
270
271        #[apply(all_cred_cipher)]
272        async fn should_create_a_commit_out_of_pending_proposals_by_ref(case: TestContext) {
273            let [alice, bob, charlie] = case.sessions().await;
274            Box::pin(async move {
275                // Bob removes charlie
276                let conversation = case
277                    .create_conversation([&alice, &bob, &charlie])
278                    .await
279                    .acting_as(&bob)
280                    .await
281                    .remove_proposal_notify(&charlie)
282                    .await
283                    .acting_as(&bob)
284                    .await;
285
286                assert!(conversation.has_pending_proposals().await);
287                assert_eq!(conversation.member_count().await, 3);
288
289                // Alice commits the proposal
290                let conversation = conversation.commit_pending_proposals_notify().await;
291                assert_eq!(conversation.member_count().await, 2);
292
293                assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
294            })
295            .await;
296        }
297    }
298
299    mod delivery_semantics {
300        use super::*;
301
302        #[apply(all_cred_cipher)]
303        async fn should_prevent_out_of_order_commits(case: TestContext) {
304            let [alice, bob] = case.sessions().await;
305            Box::pin(async move {
306                let conversation = case.create_conversation([&alice, &bob]).await;
307                let id = conversation.id().clone();
308
309                let commit_guard = conversation.update().await;
310                let commit1 = commit_guard.message();
311                let commit1 = commit1.to_bytes().unwrap();
312
313                let commit_guard = commit_guard.finish().update().await;
314                let commit2 = commit_guard.message();
315                let commit2 = commit2.to_bytes().unwrap();
316
317                // fails when a commit is skipped
318                let out_of_order = bob
319                    .transaction
320                    .conversation(&id)
321                    .await
322                    .unwrap()
323                    .decrypt_message(&commit2)
324                    .await;
325                assert!(
326                    matches!(
327                        out_of_order.unwrap().into_single_deferred(),
328                        DeferralReason::FutureEpoch { .. }
329                    ),
330                    "the message must have been deferred"
331                );
332
333                // works in the right order though
334                // NB: here 'commit2' has been buffered so it is also applied when we decrypt commit1
335                bob.transaction
336                    .conversation(&id)
337                    .await
338                    .unwrap()
339                    .decrypt_message(&commit1)
340                    .await
341                    .unwrap();
342
343                // and then fails again when trying to decrypt a commit with an epoch in the past
344                let past_commit = bob
345                    .transaction
346                    .conversation(&id)
347                    .await
348                    .unwrap()
349                    .decrypt_message(&commit1)
350                    .await;
351                assert!(matches!(
352                    past_commit.unwrap().into_single_rejected(),
353                    RejectionReason::StaleCommit
354                ));
355            })
356            .await;
357        }
358    }
359}