Skip to main content

core_crypto/transaction_context/conversation/
welcome.rs

1//! This module contains transactional conversation operations that are related to processing welcome messages.
2
3use openmls::prelude::{MlsMessageIn, MlsMessageInBody};
4
5use super::{Error, Result, TransactionContext};
6use crate::{ConversationConfiguration, ConversationId, KeystoreError};
7
8impl TransactionContext {
9    /// Create a conversation from a received MLS Welcome message
10    ///
11    /// # Arguments
12    /// * `welcome` - a `Welcome` message received as a result of a commit adding new members to a group
13    ///
14    /// # Return type
15    /// This function will return the conversation/group id
16    ///
17    /// # Errors
18    /// Errors can be originating from the KeyStore of from OpenMls:
19    /// * if no [openmls::key_packages::KeyPackage] can be read from the KeyStore
20    /// * if the message can't be decrypted
21    #[cfg_attr(test, crate::dispotent)]
22    pub async fn process_welcome_message(&self, welcome: impl Into<MlsMessageIn>) -> Result<ConversationId> {
23        let MlsMessageInBody::Welcome(welcome) = welcome.into().extract() else {
24            return Err(Error::CallerError(
25                "the message provided to process_welcome_message was not a welcome message",
26            ));
27        };
28
29        let configuration = ConversationConfiguration {
30            cipher_suite: welcome.ciphersuite().into(),
31            ..Default::default()
32        };
33
34        let inner = self.inner().await?;
35        let conversation = inner
36            .transaction()
37            .with_savepoint(
38                "process_welcome_message_savepoint",
39                async || {
40                    self.persist_conversation_from_welcome_message(welcome, configuration)
41                        .await
42                },
43                |context| Box::new(move |err| KeystoreError::wrap(context)(err).into()),
44            )
45            .await?;
46
47        let id = conversation.id().to_owned();
48
49        Ok(id)
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use crate::test_utils::*;
56
57    #[apply(all_cred_cipher)]
58    async fn joining_from_welcome_should_prune_local_key_material(case: TestContext) {
59        let [alice, bob] = case.sessions().await;
60        Box::pin(async move {
61            // has to be before the original key_package count because it creates one
62            // Create a conversation from alice, where she invites bob
63            let commit_guard = case.create_conversation([&alice]).await.invite([&bob]).await;
64
65            // Keep track of the whatever amount was initially generated
66            let prev_count = bob.transaction.count_entities().await;
67            // Bob accepts the welcome message, and as such, it should prune the used keypackage from the store
68            commit_guard.notify_members().await;
69
70            // Ensure we're left with 1 less keypackage bundle in the store, because it was consumed with the OpenMLS
71            // Welcome message
72            let next_count = bob.transaction.count_entities().await;
73            assert_eq!(next_count.key_package, prev_count.key_package - 1);
74            assert_eq!(next_count.hpke_private_key, prev_count.hpke_private_key - 1);
75            assert_eq!(next_count.encryption_keypair, prev_count.encryption_keypair - 1);
76        })
77        .await;
78    }
79
80    #[apply(all_cred_cipher)]
81    async fn process_welcome_should_fail_when_already_exists(case: TestContext) {
82        let [alice, mut bob] = case.sessions().await;
83        Box::pin(async move {
84            let credential_ref = &bob.initial_credential;
85            let commit = case.create_conversation([&alice]).await.invite([&bob]).await;
86            let conversation = commit.conversation();
87            let id = conversation.id().clone();
88                // Meanwhile Bob creates a conversation with the exact same id as the one he's trying to join
89                bob
90                    .transaction
91                    .new_conversation(&id, credential_ref, case.cfg.clone())
92                    .await
93                    .unwrap();
94
95                // Bob's key packages before processing the welcome
96                let key_package_refs_before = bob.transaction.get_key_package_refs().await.unwrap();
97
98                let welcome = conversation.transport().await.latest_welcome_message().await;
99
100                // We need Bob's created key package to be persisted, so we can restore it on error.
101                // Assuming that key package creation happens in its own transaction matches a sufficiently large
102                // portion of real-world usage.
103                bob.commit_transaction().await;
104
105                let join_welcome = bob
106                    .transaction
107                    .process_welcome_message(welcome)
108                    .await;
109
110                // Bob's key packages after processing the welcome
111                let key_package_refs_after = bob.transaction.get_key_package_refs().await.unwrap();
112
113                assert!(!key_package_refs_before.is_empty());
114                assert_eq!(key_package_refs_before, key_package_refs_after);
115                assert!(innermost_source_matches!(join_welcome.unwrap_err(), super::Error::ConversationAlreadyExists(i) if i == &id));
116            })
117        .await;
118    }
119
120    /// Processing a welcome message makes openmls consume the key package it was addressed to; when
121    /// persisting the conversation then fails, the savepoint in `process_welcome_message` must put
122    /// that key material back.
123    ///
124    /// Unlike [`process_welcome_should_fail_when_already_exists`], this does not commit before
125    /// processing the welcome: a savepoint rolls back within the transaction which created the key
126    /// package, so restoration must work even then.
127    #[apply(all_cred_cipher)]
128    async fn failed_welcome_should_restore_key_material_in_same_transaction(case: TestContext) {
129        let [alice, bob] = case.sessions().await;
130        let credential_ref = &bob.initial_credential;
131        let commit = case.create_conversation([&alice]).await.invite([&bob]).await;
132        let conversation = commit.conversation();
133        let id = conversation.id().clone();
134
135        // Bob creates a conversation with the exact same id as the one he's trying to join, so
136        // persisting the conversation from the welcome message is bound to fail
137        bob.transaction
138            .new_conversation(&id, credential_ref, case.cfg.clone())
139            .await
140            .unwrap();
141
142        let welcome = conversation.transport().await.latest_welcome_message().await;
143
144        let count_before = bob.transaction.count_entities().await;
145        let key_package_refs_before = bob.transaction.get_key_package_refs().await.unwrap();
146        assert!(!key_package_refs_before.is_empty());
147
148        let join_welcome = bob.transaction.process_welcome_message(welcome).await;
149        assert!(innermost_source_matches!(
150            join_welcome.unwrap_err(),
151            super::Error::ConversationAlreadyExists(i) if i == &id
152        ));
153
154        // Every entity the welcome touched must be back where it was: the key package itself,
155        // its hpke init private key, and its leaf node encryption keypair.
156        let count_after = bob.transaction.count_entities().await;
157        assert_eq!(count_before, count_after);
158        let key_package_refs_after = bob.transaction.get_key_package_refs().await.unwrap();
159        assert_eq!(key_package_refs_before, key_package_refs_after);
160    }
161
162    /// Restoring the key material is only worth anything if it is complete: a key package whose
163    /// private keys were not restored is unusable. So once the reason the welcome failed is gone,
164    /// processing that same welcome message again has to succeed.
165    #[apply(all_cred_cipher)]
166    async fn restored_key_material_should_still_be_able_to_join_from_welcome(case: TestContext) {
167        let [alice, bob] = case.sessions().await;
168        let credential_ref = &bob.initial_credential;
169        let commit = case.create_conversation([&alice]).await.invite([&bob]).await;
170        let conversation = commit.conversation();
171        let id = conversation.id().clone();
172
173        // The conflicting conversation which makes the first attempt fail
174        bob.transaction
175            .new_conversation(&id, credential_ref, case.cfg.clone())
176            .await
177            .unwrap();
178
179        let welcome = conversation.transport().await.latest_welcome_message().await;
180
181        let join_welcome = bob.transaction.process_welcome_message(welcome.clone()).await;
182        assert!(innermost_source_matches!(
183            join_welcome.unwrap_err(),
184            super::Error::ConversationAlreadyExists(i) if i == &id
185        ));
186
187        // Bob gets rid of the conversation which was in the way
188        bob.transaction.conversation(&id).await.unwrap().wipe().await.unwrap();
189
190        // The restored key material is complete, so the second attempt goes through
191        let joined_id = bob.transaction.process_welcome_message(welcome).await.unwrap();
192        assert_eq!(joined_id, id);
193
194        // And the conversation Bob joined is the real thing: he can talk in it
195        let message = bob
196            .transaction
197            .conversation(&id)
198            .await
199            .unwrap()
200            .encrypt_message(b"hello")
201            .await
202            .unwrap();
203        let decrypted = conversation
204            .guard_of(&alice)
205            .await
206            .decrypt_message(&message)
207            .await
208            .unwrap();
209        assert_eq!(decrypted.as_application_message().unwrap().plaintext, b"hello");
210    }
211}