Skip to main content

core_crypto/transaction_context/
mod.rs

1//! This module contains the primitives to enable transactional support on a higher level within the
2//! [Session]. All mutating operations need to be done through a [TransactionContext].
3
4use std::sync::Arc;
5
6use async_lock::{Mutex, MutexGuardArc, RwLock};
7use core_crypto_keystore::{
8    CryptoKeystoreError, Database, UniqueArc,
9    entities::ConsumerData,
10    traits::{EntityDatabaseMutation as _, FetchFromDatabase as _},
11};
12pub use error::{Error, Result};
13use log::info;
14use openmls_traits::OpenMlsCryptoProvider as _;
15use wire_e2e_identity::pki_env::PkiEnvironment;
16
17use crate::{
18    ClientId, ConversationId, CoreCrypto, KeystoreError, MlsTransport, OpenMlsError, RecursiveError, Session,
19    mls::{self, conversation_cache::ConversationCache},
20    mls_provider::CryptoProvider,
21};
22pub mod conversation;
23mod credential;
24mod decrypt;
25pub mod e2e_identity;
26mod error;
27mod inner_guard;
28pub mod key_package;
29#[cfg(feature = "proteus")]
30pub mod proteus;
31mod savepoint;
32#[cfg(test)]
33pub mod test_utils;
34
35/// This struct provides transactional support for Core Crypto.
36///
37/// This struct provides mutable access to the internals of Core Crypto. Every operation that
38/// causes data to be persisted needs to be done through this struct. This struct will buffer all
39/// operations in memory and when [TransactionContext::finish] is called, it will persist the data into
40/// the keystore.
41///
42/// Due to uniffi's design, we can't force the context to be dropped after the transaction is
43/// committed. To work around that keep everything important in `TransactionContextInner`;
44/// see `inner` and `take_inner`.
45#[derive(Debug, Clone)]
46pub struct TransactionContext {
47    inner: Arc<RwLock<Option<TransactionContextInner>>>,
48}
49
50#[derive(derive_more::Debug)]
51pub(crate) struct TransactionContextInner {
52    core_crypto: Arc<CoreCrypto>,
53    pending_epoch_changes: Arc<Mutex<Vec<(ConversationId, u64)>>>,
54    /// Conversations whose in-memory state may have changed in this transaction, in order, with
55    /// repeats. A savepoint rollback restores the ones added after the savepoint started.
56    touched_conversations: Mutex<Vec<ConversationId>>,
57    #[debug(skip)]
58    transaction: UniqueArc<core_crypto_keystore::Transaction>,
59}
60
61impl CoreCrypto {
62    /// Creates a new transaction. All operations that persist data will be
63    /// buffered in memory and when [TransactionContext::finish] is called, the data will be persisted
64    /// in a single database transaction.
65    pub async fn new_transaction(self: &Arc<Self>) -> Result<TransactionContext> {
66        TransactionContext::new(self.clone()).await
67    }
68}
69
70impl TransactionContext {
71    /// Clear the MLS and Proteus caches so accesses are forced to read from DB state.
72    async fn clear_caches(core_crypto: &CoreCrypto) {
73        if let Some(session) = core_crypto.mls.read().await.as_ref() {
74            session.conversation_cache.lock().await.clear();
75        }
76        #[cfg(feature = "proteus")]
77        if let Some(proteus) = core_crypto.proteus.lock().await.as_mut() {
78            proteus.clear_session_cache();
79        }
80    }
81
82    async fn new(core_crypto: Arc<CoreCrypto>) -> Result<Self> {
83        let transaction = core_crypto
84            .database
85            .new_transaction()
86            .await
87            .map_err(KeystoreError::wrap("creating new transaction"))?;
88        if transaction.externally_modified() {
89            info!("on initializing a new transaction, DB connection detected external modification; clearing caches");
90            Self::clear_caches(&core_crypto).await;
91        }
92        Ok(Self {
93            inner: Arc::new(RwLock::new(Some(TransactionContextInner {
94                core_crypto,
95                pending_epoch_changes: Default::default(),
96                touched_conversations: Default::default(),
97                transaction,
98            }))),
99        })
100    }
101
102    pub(crate) async fn session(&self) -> Result<Arc<Session>> {
103        let inner = self.inner()?;
104        inner.core_crypto.mls.read().await.as_ref().cloned().ok_or(
105            RecursiveError::context("Getting mls session from transaction context")(
106                mls::session::Error::MlsNotInitialized,
107            )
108            .into(),
109        )
110    }
111
112    #[cfg(test)]
113    pub(crate) async fn set_session_if_exists(&self, new_session: &Arc<Session>) {
114        let Ok(inner) = self.inner() else {
115            return;
116        };
117        let mut guard = inner.core_crypto.mls.write().await;
118        if guard.as_ref().is_some() {
119            *guard = Some(new_session.clone())
120        }
121    }
122
123    pub(crate) async fn mls_transport(&self) -> Result<Arc<dyn MlsTransport + 'static>> {
124        let inner = self.inner()?;
125        inner
126            .core_crypto
127            .mls
128            .read()
129            .await
130            .as_ref()
131            .map(|s| s.transport.clone())
132            .ok_or(
133                RecursiveError::context("Getting mls session from transaction context")(
134                    mls::session::Error::MlsNotInitialized,
135                )
136                .into(),
137            )
138    }
139
140    /// Clones the [CryptoProvider].
141    pub async fn crypto_provider(&self) -> Result<CryptoProvider> {
142        let inner = self.inner()?;
143        inner
144            .core_crypto
145            .mls
146            .read()
147            .await
148            .as_ref()
149            .map(|s| s.crypto_provider.clone())
150            .ok_or(
151                RecursiveError::context("Getting mls session from transaction context")(
152                    mls::session::Error::MlsNotInitialized,
153                )
154                .into(),
155            )
156    }
157
158    pub(crate) fn database(&self) -> Result<Arc<Database>> {
159        let inner = self.inner()?;
160        Ok(inner.core_crypto.database.clone())
161    }
162
163    pub(crate) async fn pki_environment(&self) -> Result<Arc<PkiEnvironment>> {
164        let inner = self.inner()?;
165        inner
166            .core_crypto
167            .pki_environment
168            .read()
169            .await
170            .as_ref()
171            .map(Clone::clone)
172            .ok_or(Error::PkiEnvironmentUnset)
173    }
174
175    pub(crate) async fn mls_groups(&self) -> Result<MutexGuardArc<ConversationCache>> {
176        let inner = self.inner()?;
177        let cache = inner
178            .core_crypto
179            .mls
180            .read()
181            .await
182            .as_ref()
183            .map(|session| session.conversation_cache.clone())
184            .ok_or_else(|| {
185                RecursiveError::context("getting mls session from transaction context")(
186                    mls::session::Error::MlsNotInitialized,
187                )
188            })?;
189
190        Ok(cache.lock_arc().await)
191    }
192
193    pub(crate) async fn queue_epoch_changed(&self, conversation_id: ConversationId, epoch: u64) -> Result<()> {
194        let inner = self.inner()?;
195        inner.pending_epoch_changes.lock().await.push((conversation_id, epoch));
196        Ok(())
197    }
198
199    /// Commits the transaction, meaning it takes all the enqueued operations and persist them into
200    /// the keystore. After that the internal state is switched to invalid, causing errors if
201    /// something is called from this object.
202    pub async fn finish(&self) -> Result<()> {
203        let TransactionContextInner {
204            core_crypto,
205            pending_epoch_changes,
206            transaction: tx,
207            ..
208        } = self.take_inner().await?;
209
210        let commit_result = tx
211            .commit()
212            .await
213            .map_err(KeystoreError::wrap("commiting transaction"))
214            .map_err(Into::into);
215
216        if commit_result.is_ok() {
217            if let Some(session) = core_crypto.mls.read().await.as_ref() {
218                // We need owned values, so we could just clone the conversation ids, but we don't need the events
219                // anymore, so draining the vector works, too.
220                let mut epoch_changes = pending_epoch_changes.lock().await;
221                for (conversation_id, epoch) in epoch_changes.drain(..) {
222                    session.notify_epoch_changed(conversation_id, epoch).await;
223                }
224            }
225            // if not, we still drop the pending changes at the end of this function
226        } else {
227            // Commit failed: the keystore is back to its pre-transaction state, but the in-memory
228            // caches may have absorbed mutations that never made it to disk. Clear them
229            // so subsequent reads load fresh state from the keystore.
230            Self::clear_caches(&core_crypto).await;
231        }
232
233        commit_result
234    }
235
236    /// Aborts the transaction, meaning it discards all the enqueued operations.
237    /// After that the internal state is switched to invalid, causing errors if
238    /// something is called from this object.
239    pub async fn abort(&self) -> Result<()> {
240        let inner = self.take_inner().await?;
241
242        // Drop any in-memory state mutated during this transaction; it never reached
243        // the keystore and would otherwise diverge from disk after rollback.
244        Self::clear_caches(&inner.core_crypto).await;
245
246        Ok(())
247    }
248
249    /// Initializes the MLS client of [super::CoreCrypto].
250    pub async fn mls_init(&self, session_id: ClientId, transport: Arc<dyn MlsTransport>) -> Result<()> {
251        let database = self.database()?;
252        let pki_env = self.pki_environment().await.ok();
253        let crypto_provider = CryptoProvider::new_with_pki_env(database.clone(), pki_env);
254        let session = Session::new(session_id.clone(), crypto_provider, database.into(), transport);
255        self.set_mls_session(session).await?;
256
257        Ok(())
258    }
259
260    /// Set the `mls_session` Arc (also sets it on the transaction's CoreCrypto instance)
261    pub(crate) async fn set_mls_session(&self, session: Arc<Session>) -> Result<()> {
262        let inner = self.inner()?;
263        let mut guard = inner.core_crypto.mls.write().await;
264        *guard = Some(session);
265        Ok(())
266    }
267
268    /// see [Session::id]
269    pub async fn client_id(&self) -> Result<ClientId> {
270        let session = self.session().await?;
271        Ok(session.id())
272    }
273
274    /// Generates a random byte array of the specified size
275    pub async fn random_bytes(&self, len: usize) -> Result<Vec<u8>> {
276        use openmls_traits::random::OpenMlsRand as _;
277        self.crypto_provider()
278            .await?
279            .rand()
280            .random_vec(len)
281            .map_err(OpenMlsError::wrap("generating random vector"))
282            .map_err(Into::into)
283    }
284
285    /// Set arbitrary data to be retrieved by [TransactionContext::get_data].
286    /// This is meant to be used as a check point at the end of a transaction.
287    /// The data should be limited to a reasonable size.
288    pub fn set_data(&self, data: Vec<u8>) -> Result<()> {
289        let inner = self.inner()?;
290        ConsumerData::from(data)
291            .save(inner.transaction())
292            .map_err(KeystoreError::wrap("saving consumer data"))?;
293        Ok(())
294    }
295
296    /// Get the data that has previously been set by [TransactionContext::set_data].
297    /// This is meant to be used as a check point at the end of a transaction.
298    pub async fn get_data(&self) -> Result<Option<Vec<u8>>> {
299        let inner = self.inner()?;
300        match inner.transaction.get_unique::<ConsumerData>().await {
301            Ok(maybe_data) => Ok(maybe_data.map(Arc::unwrap_or_clone).map(Into::into)),
302            Err(CryptoKeystoreError::NotFound(..)) => Ok(None),
303            Err(err) => Err(KeystoreError::wrap("finding unique consumer data")(err).into()),
304        }
305    }
306}
307
308impl TransactionContextInner {
309    pub(crate) fn transaction(&self) -> &core_crypto_keystore::Transaction {
310        &self.transaction
311    }
312}