Skip to main content

matrix_sdk_crypto/store/
crypto_store_wrapper.rs

1use std::{future, ops::Deref, sync::Arc};
2
3use futures_core::Stream;
4use futures_util::StreamExt;
5use matrix_sdk_common::cross_process_lock::{CrossProcessLock, CrossProcessLockConfig};
6use ruma::{DeviceId, OwnedDeviceId, OwnedUserId, UserId};
7use tokio::sync::{Mutex, broadcast};
8use tokio_stream::wrappers::{BroadcastStream, errors::BroadcastStreamRecvError};
9use tracing::{debug, trace, warn};
10
11use super::{
12    DeviceChanges, IdentityChanges, LockableCryptoStore, caches::SessionStore,
13    types::RoomKeyBundleInfo,
14};
15use crate::{
16    CryptoStoreError, OwnUserIdentityData, Session, UserIdentityData,
17    olm::InboundGroupSession,
18    store,
19    store::{
20        Changes, DynCryptoStore, IntoCryptoStore, RoomKeyInfo, RoomKeyWithheldInfo,
21        types::SecretsInboxItem,
22    },
23};
24
25/// A wrapper for crypto store implementations that adds update notifiers.
26///
27/// This is shared between [`StoreInner`] and
28/// [`crate::verification::VerificationStore`].
29#[derive(Debug)]
30pub(crate) struct CryptoStoreWrapper {
31    user_id: OwnedUserId,
32    device_id: OwnedDeviceId,
33
34    store: Arc<DynCryptoStore>,
35
36    /// A cache for the Olm Sessions.
37    sessions: SessionStore,
38
39    /// The sender side of a broadcast stream that is notified whenever we get
40    /// an update to an inbound group session.
41    room_keys_received_sender: broadcast::Sender<Vec<RoomKeyInfo>>,
42
43    /// The sender side of a broadcast stream that is notified whenever we
44    /// receive an `m.room_key.withheld` message.
45    room_keys_withheld_received_sender: broadcast::Sender<Vec<RoomKeyWithheldInfo>>,
46
47    /// The sender side of a broadcast channel which sends out secrets we
48    /// received as a `m.secret.send` event.
49    secrets_broadcaster: broadcast::Sender<SecretsInboxItem>,
50
51    /// The sender side of a broadcast channel which sends out devices and user
52    /// identities which got updated or newly created.
53    identities_broadcaster:
54        broadcast::Sender<(Option<OwnUserIdentityData>, IdentityChanges, DeviceChanges)>,
55
56    /// The sender side of a broadcast channel which sends out information about
57    /// historic room key bundles we have received.
58    historic_room_key_bundles_broadcaster: broadcast::Sender<RoomKeyBundleInfo>,
59}
60
61/// Capacity of the room keys received broadcast channel.
62pub const ROOM_KEYS_RECEIVED_CAPACITY: usize = 10;
63/// Capacity of the room keys withheld broadcast channel.
64pub const ROOM_KEYS_WITHHELD_RECEIVED_CAPACITY: usize = 10;
65/// Capacity of the secrets inbox broadcast channel.
66pub const SECRETS_BROADCASTER_CAPACITY: usize = 10;
67/// Capacity of the identity data broadcast channel.
68pub const IDENTITIES_BROADCASTER_CAPACITY: usize = 20;
69/// Capacity of the historic room key bundle broadcast channel.
70pub const HISTORIC_ROOM_KEY_BUNDLES_BROADCASTER_CAPACITY: usize = 10;
71
72impl CryptoStoreWrapper {
73    pub(crate) fn new(user_id: &UserId, device_id: &DeviceId, store: impl IntoCryptoStore) -> Self {
74        let room_keys_received_sender = broadcast::Sender::new(ROOM_KEYS_RECEIVED_CAPACITY);
75        let room_keys_withheld_received_sender =
76            broadcast::Sender::new(ROOM_KEYS_WITHHELD_RECEIVED_CAPACITY);
77        let secrets_broadcaster = broadcast::Sender::new(SECRETS_BROADCASTER_CAPACITY);
78        // The identities broadcaster is responsible for user identities as well
79        // as devices, that's why we increase the capacity here.
80        let identities_broadcaster = broadcast::Sender::new(IDENTITIES_BROADCASTER_CAPACITY);
81        let historic_room_key_bundles_broadcaster =
82            broadcast::Sender::new(HISTORIC_ROOM_KEY_BUNDLES_BROADCASTER_CAPACITY);
83
84        Self {
85            user_id: user_id.to_owned(),
86            device_id: device_id.to_owned(),
87            store: store.into_crypto_store(),
88            sessions: SessionStore::new(),
89            room_keys_received_sender,
90            room_keys_withheld_received_sender,
91            secrets_broadcaster,
92            identities_broadcaster,
93            historic_room_key_bundles_broadcaster,
94        }
95    }
96
97    /// Save the set of changes to the store.
98    ///
99    /// Also responsible for sending updates to the broadcast streams such as
100    /// `room_keys_received_sender` and `secrets_broadcaster`.
101    ///
102    /// # Arguments
103    ///
104    /// - `changes` - The set of changes that should be stored.
105    pub async fn save_changes(&self, changes: Changes) -> store::Result<()> {
106        let room_key_updates: Vec<_> =
107            changes.inbound_group_sessions.iter().map(RoomKeyInfo::from).collect();
108
109        let withheld_session_updates: Vec<_> = changes
110            .withheld_session_info
111            .iter()
112            .flat_map(|(room_id, session_map)| {
113                session_map.iter().map(|(session_id, withheld_event)| RoomKeyWithheldInfo {
114                    room_id: room_id.to_owned(),
115                    session_id: session_id.to_owned(),
116                    withheld_event: withheld_event.clone(),
117                })
118            })
119            .collect();
120
121        // If our own identity verified status changes we need to do some checks
122        // on other identities. So remember the verification status before
123        // processing the changes
124        let own_identity_was_verified_before_change = self
125            .store
126            .get_user_identity(self.user_id.as_ref())
127            .await?
128            .as_ref()
129            .and_then(|i| i.own())
130            .is_some_and(|own| own.is_verified());
131
132        let secrets = changes.secrets.to_owned();
133        let devices = changes.devices.to_owned();
134        let identities = changes.identities.to_owned();
135        let room_key_bundle_updates: Vec<_> =
136            changes.received_room_key_bundles.iter().map(RoomKeyBundleInfo::from).collect();
137
138        if devices
139            .changed
140            .iter()
141            .any(|d| d.user_id() == self.user_id && d.device_id() == self.device_id)
142        {
143            // If our own device key changes, we need to clear the session cache
144            // because the sessions contain a copy of our device key.
145            self.sessions.clear().await;
146        } else {
147            // Otherwise add the sessions to the cache.
148            for session in &changes.sessions {
149                self.sessions.add(session.clone()).await;
150            }
151        }
152
153        self.store.save_changes(changes).await?;
154
155        // If we updated our own public identity, log it for debugging purposes
156        if tracing::level_enabled!(tracing::Level::DEBUG) {
157            for updated_identity in
158                identities.new.iter().chain(identities.changed.iter()).filter_map(|id| id.own())
159            {
160                let master_key = updated_identity.master_key().get_first_key();
161                let user_signing_key = updated_identity.user_signing_key().get_first_key();
162                let self_signing_key = updated_identity.self_signing_key().get_first_key();
163
164                debug!(
165                    ?master_key,
166                    ?user_signing_key,
167                    ?self_signing_key,
168                    previously_verified = updated_identity.was_previously_verified(),
169                    verified = updated_identity.is_verified(),
170                    "Stored our own identity"
171                );
172            }
173        }
174
175        if !room_key_updates.is_empty() {
176            // Ignore the result. It can only fail if there are no listeners.
177            let _ = self.room_keys_received_sender.send(room_key_updates);
178        }
179
180        if !withheld_session_updates.is_empty() {
181            let _ = self.room_keys_withheld_received_sender.send(withheld_session_updates);
182        }
183
184        for secret in secrets {
185            let _ = self.secrets_broadcaster.send(secret);
186        }
187
188        for bundle_info in room_key_bundle_updates {
189            let _ = self.historic_room_key_bundles_broadcaster.send(bundle_info);
190        }
191
192        if !devices.is_empty() || !identities.is_empty() {
193            // Mapping the devices and user identities from the read-only
194            // variant to one's that contain side-effects requires our own
195            // identity. This is guaranteed to be up-to-date since we just
196            // persisted it.
197            let maybe_own_identity =
198                self.store.get_user_identity(&self.user_id).await?.and_then(|i| i.into_own());
199
200            // If our identity was not verified before the change and is now,
201            // that means this could impact the verification chain of other
202            // known identities.
203            if let Some(own_identity_after) = maybe_own_identity.as_ref() {
204                // Only do this if our identity is passing from not verified to
205                // verified, the previously_verified can only change in that
206                // case.
207                let own_identity_is_verified = own_identity_after.is_verified();
208
209                if !own_identity_was_verified_before_change && own_identity_is_verified {
210                    debug!(
211                        "Own identity is now verified, check all known identities for verification status changes"
212                    );
213                    // We need to review all the other identities to see if they
214                    // are verified now and mark them as such
215                    self.check_all_identities_and_update_was_previously_verified_flag_if_needed(
216                        own_identity_after,
217                    )
218                    .await?;
219                } else if own_identity_was_verified_before_change != own_identity_is_verified {
220                    // Log that the verification state of the identity changed.
221                    debug!(
222                        own_identity_is_verified,
223                        "The verification state of our own identity has changed",
224                    );
225                }
226            }
227
228            let _ = self.identities_broadcaster.send((maybe_own_identity, identities, devices));
229        }
230
231        Ok(())
232    }
233
234    async fn check_all_identities_and_update_was_previously_verified_flag_if_needed(
235        &self,
236        own_identity_after: &OwnUserIdentityData,
237    ) -> Result<(), CryptoStoreError> {
238        let tracked_users = self.store.load_tracked_users().await?;
239        let mut updated_identities: Vec<UserIdentityData> = Default::default();
240        for tracked_user in tracked_users {
241            if let Some(other_identity) = self
242                .store
243                .get_user_identity(tracked_user.user_id.as_ref())
244                .await?
245                .as_ref()
246                .and_then(|i| i.other())
247                && !other_identity.was_previously_verified()
248                && own_identity_after.is_identity_signed(other_identity)
249            {
250                trace!(?tracked_user.user_id, "Marking set verified_latch to true.");
251                other_identity.mark_as_previously_verified();
252                updated_identities.push(other_identity.clone().into());
253            }
254        }
255
256        if !updated_identities.is_empty() {
257            let identity_changes =
258                IdentityChanges { changed: updated_identities, ..Default::default() };
259            self.store
260                .save_changes(Changes {
261                    identities: identity_changes.clone(),
262                    ..Default::default()
263                })
264                .await?;
265
266            let _ = self.identities_broadcaster.send((
267                Some(own_identity_after.clone()),
268                identity_changes,
269                DeviceChanges::default(),
270            ));
271        }
272
273        Ok(())
274    }
275
276    pub async fn get_sessions(
277        &self,
278        sender_key: &str,
279    ) -> store::Result<Option<Arc<Mutex<Vec<Session>>>>> {
280        let sessions = self.sessions.get(sender_key).await;
281
282        let sessions = if sessions.is_none() {
283            let mut entries = self.sessions.entries.write().await;
284
285            let sessions = entries.get(sender_key);
286
287            if sessions.is_some() {
288                sessions.cloned()
289            } else {
290                let sessions = self.store.get_sessions(sender_key).await?;
291                let sessions = Arc::new(Mutex::new(sessions.unwrap_or_default()));
292
293                entries.insert(sender_key.to_owned(), sessions.clone());
294
295                Some(sessions)
296            }
297        } else {
298            sessions
299        };
300
301        Ok(sessions)
302    }
303
304    /// Save a list of inbound group sessions to the store.
305    ///
306    /// # Arguments
307    ///
308    /// - `sessions` - The sessions to be saved.
309    /// - `backed_up_to_version` - If the keys should be marked as having been
310    ///   backed up, the version of the backup.
311    ///
312    /// Note: some implementations ignore `backup_version` and assume the
313    /// current backup version, which is normally the same.
314    pub async fn save_inbound_group_sessions(
315        &self,
316        sessions: Vec<InboundGroupSession>,
317        backed_up_to_version: Option<&str>,
318    ) -> store::Result<()> {
319        let room_key_updates: Vec<_> = sessions.iter().map(RoomKeyInfo::from).collect();
320        self.store.save_inbound_group_sessions(sessions, backed_up_to_version).await?;
321
322        if !room_key_updates.is_empty() {
323            // Ignore the result. It can only fail if there are no listeners.
324            let _ = self.room_keys_received_sender.send(room_key_updates);
325        }
326        Ok(())
327    }
328
329    /// Receive notifications of room keys being received as a [`Stream`].
330    ///
331    /// Each time a room key is updated in any way, an update will be sent to
332    /// the stream. Updates that happen at the same time are batched into a
333    /// [`Vec`].
334    ///
335    /// If the reader of the stream lags too far behind an error will be sent to
336    /// the reader.
337    pub fn room_keys_received_stream(
338        &self,
339    ) -> impl Stream<Item = Result<Vec<RoomKeyInfo>, BroadcastStreamRecvError>> + use<> {
340        BroadcastStream::new(self.room_keys_received_sender.subscribe())
341    }
342
343    /// Receive notifications of received `m.room_key.withheld` messages.
344    ///
345    /// Each time an `m.room_key.withheld` is received and stored, an update
346    /// will be sent to the stream. Updates that happen at the same time are
347    /// batched into a [`Vec`].
348    ///
349    /// If the reader of the stream lags too far behind, a warning will be
350    /// logged and items will be dropped.
351    pub fn room_keys_withheld_received_stream(
352        &self,
353    ) -> impl Stream<Item = Vec<RoomKeyWithheldInfo>> + use<> {
354        let stream = BroadcastStream::new(self.room_keys_withheld_received_sender.subscribe());
355        Self::filter_errors_out_of_stream(stream, "room_keys_withheld_received_stream")
356    }
357
358    /// Receive notifications of gossipped secrets being received and stored in
359    /// the secret inbox as a [`Stream`].
360    pub fn secrets_stream(&self) -> impl Stream<Item = SecretsInboxItem> + use<> {
361        let stream = BroadcastStream::new(self.secrets_broadcaster.subscribe());
362        Self::filter_errors_out_of_stream(stream, "secrets_stream")
363    }
364
365    /// Receive notifications of historic room key bundles being received and
366    /// stored in the store as a [`Stream`].
367    pub fn historic_room_key_stream(&self) -> impl Stream<Item = RoomKeyBundleInfo> + use<> {
368        let stream = BroadcastStream::new(self.historic_room_key_bundles_broadcaster.subscribe());
369        Self::filter_errors_out_of_stream(stream, "bundle_stream")
370    }
371
372    /// Returns a stream of newly created or updated cryptographic identities.
373    ///
374    /// This is just a helper method which allows us to build higher level
375    /// device and user identity streams.
376    pub(super) fn identities_stream(
377        &self,
378    ) -> impl Stream<Item = (Option<OwnUserIdentityData>, IdentityChanges, DeviceChanges)> + use<>
379    {
380        let stream = BroadcastStream::new(self.identities_broadcaster.subscribe());
381        Self::filter_errors_out_of_stream(stream, "identities_stream")
382    }
383
384    /// Helper for *_stream functions: filters errors out of the stream,
385    /// creating a new Stream.
386    ///
387    /// `BroadcastStream`s gives us `Result`s which can fail with
388    /// `BroadcastStreamRecvError` if the reader falls behind. That's annoying
389    /// to work with, so here we just emit a warning and drop the errors.
390    fn filter_errors_out_of_stream<ItemType>(
391        stream: BroadcastStream<ItemType>,
392        stream_name: &str,
393    ) -> impl Stream<Item = ItemType> + use<ItemType>
394    where
395        ItemType: 'static + Clone + Send,
396    {
397        let stream_name = stream_name.to_owned();
398        stream.filter_map(move |result| {
399            future::ready(match result {
400                Ok(r) => Some(r),
401                Err(BroadcastStreamRecvError::Lagged(lag)) => {
402                    warn!("{stream_name} missed {lag} updates");
403                    None
404                }
405            })
406        })
407    }
408
409    /// Creates a [`CrossProcessLock`] for this store, that will contain the
410    /// given key and value when hold.
411    pub(crate) fn create_store_lock(
412        &self,
413        lock_key: String,
414        config: CrossProcessLockConfig,
415    ) -> CrossProcessLock<LockableCryptoStore> {
416        CrossProcessLock::new(LockableCryptoStore(self.store.clone()), lock_key, config)
417    }
418}
419
420impl Deref for CryptoStoreWrapper {
421    type Target = DynCryptoStore;
422
423    fn deref(&self) -> &Self::Target {
424        self.store.deref()
425    }
426}
427
428#[cfg(test)]
429mod test {
430    use matrix_sdk_test::async_test;
431    use ruma::user_id;
432
433    use super::*;
434    use crate::machine::test_helpers::get_machine_pair_with_setup_sessions_test_helper;
435
436    #[async_test]
437    async fn test_cache_cleared_after_device_update() {
438        let user_id = user_id!("@alice:example.com");
439        let (first, second) =
440            get_machine_pair_with_setup_sessions_test_helper(user_id, user_id, false).await;
441
442        let sender_key = second.identity_keys().curve25519.to_base64();
443
444        first
445            .store()
446            .inner
447            .store
448            .sessions
449            .get(&sender_key)
450            .await
451            .expect("We should have a session in the cache.");
452
453        let device_data = first
454            .get_device(user_id, first.device_id(), None)
455            .await
456            .unwrap()
457            .expect("We should have access to our own device.")
458            .inner;
459
460        // When we save a new version of our device keys
461        first
462            .store()
463            .save_changes(Changes {
464                devices: DeviceChanges { changed: vec![device_data], ..Default::default() },
465                ..Default::default()
466            })
467            .await
468            .unwrap();
469
470        // Then the session is no longer in the cache
471        assert!(
472            first.store().inner.store.sessions.get(&sender_key).await.is_none(),
473            "The session should no longer be in the cache after our own device keys changed"
474        );
475    }
476}