Skip to main content

core_crypto/mls/conversation/immutable/
mod.rs

1mod clients;
2mod commit_delay;
3mod credential;
4mod duplicate;
5mod e2ei;
6mod history_sharing;
7mod persistence;
8
9use std::sync::{Arc, Weak};
10
11use async_lock::{RwLock, RwLockReadGuard};
12use core_crypto_keystore::{
13    Transaction,
14    ancillary::ConversationIdRef as KeystoreConversationIdRef,
15    entities::{PersistedMlsGroup, StoredCredentialPk},
16    traits::{EntityDatabaseMutation as _, FetchFromDatabase},
17};
18use openmls::group::{InnerState, MlsGroup};
19
20use super::{ConversationIdRef, Error, Result, SecretKey, group_metadata};
21use crate::{
22    CipherSuite, ConversationConfiguration, ConversationId, CredentialRef, ExternalSender, KeystoreError, OpenMlsError,
23    PendingStatus, Session, mls::TntMessageCounter,
24};
25
26#[derive(derive_more::Constructor, derive_more::Deref, derive_more::DerefMut, derive_more::Debug)]
27pub(crate) struct MlsGroupState {
28    #[deref]
29    #[deref_mut]
30    group: MlsGroup,
31    /// The count of transient messages plus targeted messages sent (hereafter `tx`) this epoch.
32    /// Supposed to be used when encrypting tnt messages only, and to be reset whenever the mls epoch is
33    /// incremented. Do not access this field directly, use [MlsGroupState::obtain_tnt_message_tx_counter] and
34    /// [MlsGroupState::reset_tnt_message_tx_counter] only.
35    ///
36    /// The purpose of these counters is replay protection on the recipient side: we provide the count when sending a
37    /// message to a receiver, and they check if the counter is greater than any they've seen before.
38    tnt_message_tx_counter: TntMessageCounter,
39    /// This group is in a pending state, not yet finalized and ready to process messages.
40    pub(crate) pending_status: PendingStatus,
41}
42
43impl MlsGroupState {
44    pub(crate) fn mls_group(&self) -> &MlsGroup {
45        &self.group
46    }
47
48    pub(in crate::mls::conversation) fn mls_group_mut(&mut self) -> &mut MlsGroup {
49        &mut self.group
50    }
51
52    /// Get the transient message sender (tx) counter bound to this conversation after incrementing it.
53    pub(in crate::mls::conversation) fn obtain_tnt_message_tx_counter(&mut self) -> Result<TntMessageCounter> {
54        self.tnt_message_tx_counter.increment()?;
55        self.group.set_state(InnerState::Changed);
56
57        Ok(self.tnt_message_tx_counter)
58    }
59
60    pub(in crate::mls::conversation) fn reset_tnt_message_tx_counter(&mut self) {
61        self.tnt_message_tx_counter = Default::default();
62        self.group.set_state(InnerState::Changed);
63    }
64
65    pub(crate) async fn persist(&mut self, tx: &Transaction) -> Result<()> {
66        // We must change the mls group persisted state before persisting, otherwise it will never reach the DB.
67        self.mls_group_mut().set_state(InnerState::Persisted);
68        let id = self.group.group_id();
69        let group = self.mls_group();
70
71        // While we are an active member the group itself tells us which credential we present. Once
72        // we have been evicted it no longer does: our leaf is gone from the ratchet tree, and our
73        // former slot may even have been recycled by a member added in the same commit, in which
74        // case `own_leaf_index` resolves to *their* leaf and we would link this conversation to
75        // their credential. So rather than derive, reuse what the row already records: the
76        // credential we held while we were a member is the one we used, and being evicted does not
77        // change that. Handling our own eviction wipes the conversation immediately afterwards, so
78        // this value is seldom durable — but `persist` still has to produce a valid one, because
79        // every mutation of a group reaches the keystore through here.
80        let credential = if group.is_active() {
81            group_metadata::current_credential_pk(group, tx).await?
82        } else {
83            let persisted = tx
84                .get_borrowed::<PersistedMlsGroup>(KeystoreConversationIdRef::new(id.as_slice()))
85                .await
86                .map_err(KeystoreError::wrap(
87                    "finding the existing row of an evicted conversation",
88                ))?
89                // We can only have been evicted from a conversation we were a member of, and
90                // joining one always persists it, so the row is always already there: the only
91                // other caller of this function performs the first persist of a group we have just
92                // joined or created, which is necessarily still active.
93                .ok_or(Error::MlsGroupInvalidState(
94                    "an evicted conversation must already have been persisted",
95                ))?;
96            StoredCredentialPk::new(
97                persisted.credential_id,
98                persisted.credential_type,
99                persisted.credential_not_before,
100            )
101        };
102
103        PersistedMlsGroup {
104            id: id.as_slice().into(),
105            state: core_crypto_keystore::ser(group).map_err(KeystoreError::wrap("serializing group state"))?,
106            epoch: group.epoch().as_u64(),
107            ciphersuite: group.ciphersuite() as u16,
108            credential_id: credential.public_key_hash,
109            credential_type: credential.credential_type,
110            credential_not_before: credential.not_before,
111            own_leaf_index: group.own_leaf_index().u32(),
112            is_pending: self.pending_status.is_pending(),
113            tnt_tx_counter: self.tnt_message_tx_counter.into(),
114        }
115        .save(tx)
116        .map_err(KeystoreError::wrap("persisting mls group"))?;
117
118        Ok(())
119    }
120}
121
122/// A Conversation exposes the read-only interface of an MLS conversation.
123#[derive(Debug, derive_more::Constructor)]
124pub struct Conversation {
125    pub(in crate::mls::conversation) id: ConversationId,
126    pub(in crate::mls::conversation) group: RwLock<MlsGroupState>,
127    configuration: RwLock<ConversationConfiguration>,
128    session: Weak<Session>,
129}
130
131impl Conversation {
132    /// Returns the conversation's ID
133    pub fn id(&self) -> &ConversationIdRef {
134        self.id.as_ref()
135    }
136
137    /// Returns an immutable guard over the underlying MLS group
138    pub(crate) async fn group(&self) -> RwLockReadGuard<'_, MlsGroupState> {
139        self.group.read().await
140    }
141
142    /// Returns the conversation's configuration
143    pub async fn configuration(&self) -> RwLockReadGuard<'_, ConversationConfiguration> {
144        self.configuration.read().await
145    }
146
147    /// Returns current epoch of the MLS group
148    pub async fn epoch(&self) -> u64 {
149        self.group().await.epoch().as_u64()
150    }
151
152    /// Returns this conversation's cipher suite
153    pub async fn cipher_suite(&self) -> CipherSuite {
154        self.configuration().await.cipher_suite
155    }
156
157    /// Returns a reference to the credential used in this conversation
158    pub async fn credential_ref(&self) -> Result<CredentialRef> {
159        let credential = self
160            .find_current_credential()
161            .await
162            .map_err(|_| Error::IdentityInitializationError)?;
163        Ok(CredentialRef::from_credential(&credential))
164    }
165
166    /// Upgrades a reference to this conversation's session.
167    ///
168    /// Be _very careful_ about cloning the returned `Arc`. A conversation only holds a weak reference to ensure
169    /// we don't form a reference cycle; don't let the produced `Arc` outlive this conversation, or these cycles
170    /// will be reintroduced.
171    pub(in crate::mls::conversation) fn session(&self) -> Result<Arc<Session>> {
172        self.session.upgrade().ok_or(Error::SessionDropped)
173    }
174
175    /// Derives a new key from the one in the group, to be used elsewhere.
176    ///
177    /// # Arguments
178    /// * `key_length` - the length of the key to be derived. If the value is higher than the bounds of `u16` or the
179    ///   context hash * 255, an error will be returned
180    ///
181    /// # Errors
182    /// OpenMls secret generation error
183    pub async fn export_secret_key(&self, key_length: usize) -> Result<SecretKey> {
184        const EXPORTER_LABEL: &str = "exporter";
185        const EXPORTER_CONTEXT: &[u8] = &[];
186        self.group()
187            .await
188            .export_secret(
189                &self.session()?.crypto_provider,
190                EXPORTER_LABEL,
191                EXPORTER_CONTEXT,
192                key_length,
193            )
194            .map(Into::into)
195            .map_err(OpenMlsError::wrap("exporting secret key"))
196            .map_err(Into::into)
197    }
198
199    /// Returns an iterator over all external senders present in an `MlsGroupState`.
200    fn get_external_sender_from_group(group: &MlsGroup) -> impl Iterator<Item = ExternalSender> {
201        group
202            .group_context_extensions()
203            .external_senders()
204            .into_iter()
205            .flatten()
206            .cloned()
207            .map(Into::into)
208    }
209
210    /// Returns the first external sender present in this group.
211    ///
212    /// This should be used to initialize a subconversation
213    pub async fn get_external_sender(&self) -> Result<ExternalSender> {
214        let group = self.group().await;
215        Self::get_external_sender_from_group(&group)
216            .next()
217            .ok_or(Error::MissingExternalSenderExtension)
218    }
219}
220
221#[cfg(test)]
222mod test_utils {
223    use openmls::prelude::SignaturePublicKey;
224
225    use super::*;
226
227    impl Conversation {
228        pub async fn signature_keys(&self) -> Vec<SignaturePublicKey> {
229            let group = self.group().await;
230            group
231                .members()
232                .map(|m| m.signature_key)
233                .map(|mpk| SignaturePublicKey::from(mpk.as_slice()))
234                .collect()
235        }
236
237        pub async fn encryption_keys(&self) -> Vec<Vec<u8>> {
238            let group = self.group().await;
239            group.members().map(|m| m.encryption_key).collect()
240        }
241
242        pub async fn extensions(&self) -> openmls::prelude::Extensions {
243            let group = self.group().await;
244            group.export_group_context().extensions().to_owned()
245        }
246    }
247}