Skip to main content

core_crypto/mls/conversation/mutable/
wipe.rs

1use core_crypto_keystore::entities::PersistedMlsGroup;
2
3use super::Result;
4use crate::{KeystoreError, OpenMlsError, RecursiveError, mls::conversation::ConversationMut};
5
6impl ConversationMut {
7    /// Destroys a group locally
8    ///
9    /// # Errors
10    /// KeyStore errors, such as IO
11    pub async fn wipe(&mut self) -> Result<()> {
12        // to the degree that it's easy, fallibly get things before doing any mutation
13        let provider = self.crypto_provider().await?;
14        let mut conversation_cache = self
15            .tx_context
16            .mls_groups()
17            .await
18            .map_err(RecursiveError::context("getting mls conversation cache"))?;
19
20        self.mutate_group(async |transaction, group, _| {
21            // the own client may or may not have generated an epoch keypair in the previous epoch
22            // Since it is a terminal operation, ignoring the error is fine here.
23            let _ = group.delete_previous_epoch_keypairs(&provider).await;
24
25            // collect all the relevant proposal refs without holding onto the group;
26            // we'll need to mutate the group in shortly
27            let proposals = group
28                .pending_proposals()
29                .map(|proposal| proposal.proposal_reference().to_owned())
30                .collect::<Vec<_>>();
31            for proposal in proposals {
32                // Update proposals rekey the own leaf node. Hence the associated encryption keypair has to be cleared
33                group
34                    .remove_pending_proposal(transaction, &proposal)
35                    .await
36                    .map_err(OpenMlsError::wrap("removing pending proposal"))?;
37            }
38
39            Ok(())
40        })
41        .await?;
42
43        let id = self.id();
44        let context = self
45            .tx_context
46            .inner()
47            .await
48            .map_err(RecursiveError::context("getting inner context"))?;
49        let tx = context.transaction();
50        tx.remove_borrowed::<PersistedMlsGroup>(id.as_ref())
51            .await
52            .map_err(KeystoreError::wrap("deleting mls group"))?;
53        let _ = conversation_cache.remove(id);
54
55        // Release the cache guard before clearing the buffers: that path reaches back into the
56        // transaction context, and holding this guard across it would deadlock.
57        drop(conversation_cache);
58
59        // Any message or commit this conversation had buffered is unreachable now that the
60        // conversation is gone, so it has to go with it.
61        self.tx_context
62            .clear_orphaned_conversation_buffers(id)
63            .await
64            .map_err(RecursiveError::context(
65                "clearing buffered messages and commits of a wiped conversation",
66            ))?;
67
68        Ok(())
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use crate::{mls::conversation::Error, test_utils::*};
75
76    /// Wiping a conversation abandons the messages it had buffered.
77    ///
78    /// [`ConversationMut::wipe`] deletes the group and nothing else, so a message buffered for a future
79    /// epoch outlives the conversation it was buffered for. That row is then unreachable: every route to
80    /// a buffered message runs through a conversation, and this conversation no longer exists. It can
81    /// never be restored, and nothing will ever delete it, so the keystore carries it forever.
82    ///
83    /// Nothing in the schema prevents this. `mls_pending_messages.conversation_id` has no foreign key —
84    /// V31 dropped the one it used to have, because a buffered message's conversation may live in either
85    /// `mls_groups` or `mls_pending_groups` — so keeping the two in step is this layer's job.
86    #[apply(all_cred_cipher)]
87    async fn wipe_abandons_buffered_messages(case: TestContext) {
88        Box::pin(async move {
89            let [mut alice, bob] = case.sessions().await;
90            let conversation = case.create_conversation([&alice, &bob]).await;
91
92            // Bob advances the epoch without Alice hearing about it, then speaks in the new epoch.
93            let conversation = conversation
94                .acting_as(&bob)
95                .await
96                .update()
97                .await
98                .process_member_changes()
99                .await
100                .finish();
101            let app_msg = conversation
102                .guard_of(&bob)
103                .await
104                .encrypt_message(b"Hello Alice !")
105                .await
106                .unwrap();
107
108            // Alice cannot decrypt a message from an epoch she has not reached yet, so she buffers it
109            // until the commit which advances her own epoch arrives.
110            let decrypt = conversation.guard_of(&alice).await.decrypt_message(app_msg).await;
111            assert!(matches!(decrypt.unwrap_err(), Error::BufferedFutureMessage { .. }));
112            assert_eq!(
113                alice.transaction.count_entities().await.pending_messages,
114                1,
115                "the message Alice could not decrypt must have been buffered"
116            );
117
118            // That commit never arrives; Alice wipes the conversation instead.
119            conversation.guard_of(&alice).await.wipe().await.unwrap();
120
121            drop(conversation);
122            alice.commit_transaction().await;
123
124            let counts = alice.transaction.count_entities().await;
125            assert_eq!(counts.group, 0, "the wipe must have removed the conversation");
126            assert_eq!(
127                counts.pending_messages, 0,
128                "the buffered message belongs to a conversation which no longer exists, so wiping that \
129                 conversation must have taken the message with it"
130            );
131        })
132        .await
133    }
134
135    /// Wiping a conversation abandons the commit it had buffered.
136    ///
137    /// The same defect as [`wipe_abandons_buffered_messages`], one table over: `mls_buffered_commits` is
138    /// keyed by conversation id and is not cleaned up when the conversation is deleted. It gets its own
139    /// test because the two tables are written and cleared by entirely separate code paths, so covering
140    /// one says nothing about the other.
141    #[apply(all_cred_cipher)]
142    async fn wipe_abandons_buffered_commits(case: TestContext) {
143        Box::pin(async move {
144            let [mut alice, bob, charlie] = case.sessions().await;
145            let conversation = case.create_conversation([&alice, &bob, &charlie]).await;
146
147            // Bob proposes removing Charlie, but nobody else is told about the proposal.
148            let conversation = conversation
149                .acting_as(&bob)
150                .await
151                .remove_proposal(&charlie)
152                .await
153                .finish();
154
155            // Bob then commits it. The commit refers to the proposal by reference, so Alice — who never
156            // received that proposal — cannot apply the commit, and buffers it to retry once she does.
157            let commit_guard = conversation.acting_as(&bob).await.commit_pending_proposals().await;
158            let (commit_guard, result) = commit_guard.notify_member_fallible(&alice).await;
159            assert!(matches!(result.unwrap_err(), Error::BufferedCommit));
160            let conversation = commit_guard.finish();
161
162            assert_eq!(
163                alice.transaction.count_entities().await.buffered_commits,
164                1,
165                "the commit Alice could not apply must have been buffered"
166            );
167
168            // The proposal never arrives; Alice wipes the conversation instead.
169            conversation.guard_of(&alice).await.wipe().await.unwrap();
170
171            drop(conversation);
172            alice.commit_transaction().await;
173
174            let counts = alice.transaction.count_entities().await;
175            assert_eq!(counts.group, 0, "the wipe must have removed the conversation");
176            assert_eq!(
177                counts.buffered_commits, 0,
178                "the buffered commit belongs to a conversation which no longer exists, so wiping that \
179                 conversation must have taken the commit with it"
180            );
181        })
182        .await
183    }
184}