Skip to main content

core_crypto/transaction_context/conversation/
mod.rs

1//! This module contains all [super::TransactionContext] methods related to a conversation.
2
3pub mod external_commit;
4mod persistence;
5pub mod welcome;
6
7use openmls::group::MlsGroup;
8
9use super::{Error, Result, TransactionContext};
10use crate::{
11    ConversationConfiguration, CredentialRef, OpenMlsError, PendingStatus, RecursiveError,
12    mls::conversation::{ConversationIdRef, ConversationMut},
13};
14
15impl TransactionContext {
16    /// Checks if a given conversation id exists locally.
17    ///
18    /// Somewhat cheaper than `self.conversation(id).is_ok()`.
19    ///
20    /// If `filter_pending` is set, only returns `true` if a conversation exists whose pending status
21    /// matches the filter.
22    pub async fn conversation_exists(
23        &self,
24        id: &ConversationIdRef,
25        filter_pending: Option<PendingStatus>,
26    ) -> Result<bool> {
27        let database = self.database()?.into();
28        self.mls_groups()
29            .await?
30            .exists(id, &database, filter_pending)
31            .await
32            .map_err(RecursiveError::context("checking for conversation existence"))
33            .map_err(Into::into)
34    }
35
36    /// Acquire a conversation guard.
37    ///
38    /// Most of the time it's better to use [`Self::conversation`].
39    /// However, in certain limited circumstances, it might be necessary to get a [`ConversationMut`]
40    /// whether or not the conversation in question is in fact pending.
41    pub(crate) async fn conversation_regardless_of_pending_status(
42        &self,
43        id: &ConversationIdRef,
44    ) -> Result<ConversationMut> {
45        let inner = self.inner()?;
46        let session = self.session().await?;
47        let conversation = self
48            .mls_groups()
49            .await?
50            .get_or_fetch(id, &inner.transaction, &session)
51            .await
52            .map_err(RecursiveError::context("fetching conversation from mls groups by id"))?
53            .ok_or_else(|| Error::ConversationNotFound(id.to_owned()))?;
54        Ok(ConversationMut::new(conversation, self.clone()))
55    }
56
57    /// Acquire a conversation guard.
58    ///
59    /// This helper struct permits mutations on a conversation.
60    pub async fn conversation(&self, id: &ConversationIdRef) -> Result<ConversationMut> {
61        let conversation = self.conversation_regardless_of_pending_status(id).await?;
62        if conversation.group().await.pending_status.is_pending() {
63            return Err(Error::PendingConversation(id.to_owned()));
64        }
65        Ok(conversation)
66    }
67
68    /// Create a new empty conversation
69    ///
70    /// # Arguments
71    /// * `id` - identifier of the group/conversation (must be unique otherwise the existing group will be overridden)
72    /// * `creator_credential_type` - kind of credential the creator wants to create the group with
73    /// * `config` - configuration of the group/conversation
74    ///
75    /// # Errors
76    /// Errors can happen from the KeyStore or from OpenMls for ex if no [openmls::key_packages::KeyPackage] can
77    /// be found in the KeyStore
78    #[cfg_attr(test, crate::dispotent)]
79    pub async fn new_conversation(
80        &self,
81        id: &ConversationIdRef,
82        credential_ref: &CredentialRef,
83        configuration: ConversationConfiguration,
84    ) -> Result<()> {
85        let database = self.database()?;
86        let provider = self.crypto_provider().await?;
87        if self.conversation_exists(id, None).await? {
88            return Err(Error::ConversationAlreadyExists(id.to_owned()));
89        }
90
91        let credential = credential_ref.load(&*database).await.map_err(RecursiveError::context(
92            "loading credential from database to create new conversation",
93        ))?;
94
95        let config = configuration
96            .as_openmls_default_configuration()
97            .map_err(RecursiveError::context("converting config to openmls default"))?;
98
99        // there's a deferred constraint on epoch encryption keypairs.
100        // openmls creates the keypairs before it hands us the `group` which we can use to
101        // persist the conversation, so the constraint _can't_ be fulfilled immediately;
102        // it gets checked at the outermost commit.
103        // wrapping these two operations in an explicit savepoint means that these two operations
104        // are bundled together; failing to persist the group un-persists the keypairs.
105        self.inner()?
106            .with_savepoint(
107                "new_conversation",
108                async || {
109                    let group = MlsGroup::new_with_group_id(
110                        &provider,
111                        &credential.signature_key_pair,
112                        &config,
113                        openmls::prelude::GroupId::from_slice(id.as_ref()),
114                        credential.to_mls_credential_with_key(),
115                    )
116                    .await
117                    .map_err(OpenMlsError::wrap("creating group with id"))?;
118
119                    self.persist_conversation_from_mls_group(group, configuration, PendingStatus::Operational)
120                        .await?;
121
122                    Ok(())
123                },
124                Error::savepoint,
125            )
126            .await
127    }
128}