core_crypto/mls/conversation/immutable/
mod.rs1mod 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 tnt_message_tx_counter: TntMessageCounter,
39 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 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 self.mls_group_mut().set_state(InnerState::Persisted);
68 let id = self.group.group_id();
69 let group = self.mls_group();
70
71 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 .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#[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 pub fn id(&self) -> &ConversationIdRef {
134 self.id.as_ref()
135 }
136
137 pub(crate) async fn group(&self) -> RwLockReadGuard<'_, MlsGroupState> {
139 self.group.read().await
140 }
141
142 pub async fn configuration(&self) -> RwLockReadGuard<'_, ConversationConfiguration> {
144 self.configuration.read().await
145 }
146
147 pub async fn epoch(&self) -> u64 {
149 self.group().await.epoch().as_u64()
150 }
151
152 pub async fn cipher_suite(&self) -> CipherSuite {
154 self.configuration().await.cipher_suite
155 }
156
157 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 pub(in crate::mls::conversation) fn session(&self) -> Result<Arc<Session>> {
172 self.session.upgrade().ok_or(Error::SessionDropped)
173 }
174
175 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 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 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}