Skip to main content

core_crypto/mls/conversation/mutable/
wipe.rs

1use openmls_traits::OpenMlsCryptoProvider as _;
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::transaction("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
45        provider
46            .key_store()
47            .mls_group_delete(id)
48            .await
49            .map_err(KeystoreError::wrap("deleting mls group"))?;
50        let _ = conversation_cache.remove(id);
51
52        // Release the cache guard before clearing the buffers: that path reaches back into the
53        // transaction context, and holding this guard across it would deadlock.
54        drop(conversation_cache);
55
56        // Any message or commit this conversation had buffered is unreachable now that the
57        // conversation is gone, so it has to go with it.
58        self.tx_context
59            .clear_orphaned_conversation_buffers(id)
60            .await
61            .map_err(RecursiveError::transaction(
62                "clearing buffered messages and commits of a wiped conversation",
63            ))?;
64
65        Ok(())
66    }
67}
68
69#[cfg(test)]
70mod tests {
71    use crate::{mls::conversation::Error, test_utils::*};
72
73    /// Wiping a conversation abandons the messages it had buffered.
74    ///
75    /// [`ConversationMut::wipe`] deletes the group and nothing else, so a message buffered for a future
76    /// epoch outlives the conversation it was buffered for. That row is then unreachable: every route to
77    /// a buffered message runs through a conversation, and this conversation no longer exists. It can
78    /// never be restored, and nothing will ever delete it, so the keystore carries it forever.
79    ///
80    /// Nothing in the schema prevents this. `mls_pending_messages.conversation_id` has no foreign key —
81    /// V31 dropped the one it used to have, because a buffered message's conversation may live in either
82    /// `mls_groups` or `mls_pending_groups` — so keeping the two in step is this layer's job.
83    #[apply(all_cred_cipher)]
84    async fn wipe_abandons_buffered_messages(case: TestContext) {
85        Box::pin(async move {
86            let [mut alice, bob] = case.sessions().await;
87            let conversation = case.create_conversation([&alice, &bob]).await;
88
89            // Bob advances the epoch without Alice hearing about it, then speaks in the new epoch.
90            let conversation = conversation
91                .acting_as(&bob)
92                .await
93                .update()
94                .await
95                .process_member_changes()
96                .await
97                .finish();
98            let app_msg = conversation
99                .guard_of(&bob)
100                .await
101                .encrypt_message(b"Hello Alice !")
102                .await
103                .unwrap();
104
105            // Alice cannot decrypt a message from an epoch she has not reached yet, so she buffers it
106            // until the commit which advances her own epoch arrives.
107            let decrypt = conversation.guard_of(&alice).await.decrypt_message(app_msg).await;
108            assert!(matches!(decrypt.unwrap_err(), Error::BufferedFutureMessage { .. }));
109            assert_eq!(
110                alice.transaction.count_entities().await.pending_messages,
111                1,
112                "the message Alice could not decrypt must have been buffered"
113            );
114
115            // That commit never arrives; Alice wipes the conversation instead.
116            conversation.guard_of(&alice).await.wipe().await.unwrap();
117
118            drop(conversation);
119            alice.commit_transaction().await;
120
121            let counts = alice.transaction.count_entities().await;
122            assert_eq!(counts.group, 0, "the wipe must have removed the conversation");
123            assert_eq!(
124                counts.pending_messages, 0,
125                "the buffered message belongs to a conversation which no longer exists, so wiping that \
126                 conversation must have taken the message with it"
127            );
128        })
129        .await
130    }
131
132    /// Wiping a conversation abandons the commit it had buffered.
133    ///
134    /// The same defect as [`wipe_abandons_buffered_messages`], one table over: `mls_buffered_commits` is
135    /// keyed by conversation id and is not cleaned up when the conversation is deleted. It gets its own
136    /// test because the two tables are written and cleared by entirely separate code paths, so covering
137    /// one says nothing about the other.
138    #[apply(all_cred_cipher)]
139    async fn wipe_abandons_buffered_commits(case: TestContext) {
140        Box::pin(async move {
141            let [mut alice, bob, charlie] = case.sessions().await;
142            let conversation = case.create_conversation([&alice, &bob, &charlie]).await;
143
144            // Bob proposes removing Charlie, but nobody else is told about the proposal.
145            let conversation = conversation
146                .acting_as(&bob)
147                .await
148                .remove_proposal(&charlie)
149                .await
150                .finish();
151
152            // Bob then commits it. The commit refers to the proposal by reference, so Alice — who never
153            // received that proposal — cannot apply the commit, and buffers it to retry once she does.
154            let commit_guard = conversation.acting_as(&bob).await.commit_pending_proposals().await;
155            let (commit_guard, result) = commit_guard.notify_member_fallible(&alice).await;
156            assert!(matches!(result.unwrap_err(), Error::BufferedCommit));
157            let conversation = commit_guard.finish();
158
159            assert_eq!(
160                alice.transaction.count_entities().await.buffered_commits,
161                1,
162                "the commit Alice could not apply must have been buffered"
163            );
164
165            // The proposal never arrives; Alice wipes the conversation instead.
166            conversation.guard_of(&alice).await.wipe().await.unwrap();
167
168            drop(conversation);
169            alice.commit_transaction().await;
170
171            let counts = alice.transaction.count_entities().await;
172            assert_eq!(counts.group, 0, "the wipe must have removed the conversation");
173            assert_eq!(
174                counts.buffered_commits, 0,
175                "the buffered commit belongs to a conversation which no longer exists, so wiping that \
176                 conversation must have taken the commit with it"
177            );
178        })
179        .await
180    }
181}