matrix_sdk_crypto/store/
traits.rs

1// Copyright 2023 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::{collections::HashMap, fmt, sync::Arc};
16
17use async_trait::async_trait;
18use matrix_sdk_common::AsyncTraitDeps;
19use ruma::{
20    events::secret::request::SecretName, DeviceId, OwnedDeviceId, RoomId, TransactionId, UserId,
21};
22use vodozemac::Curve25519PublicKey;
23
24use super::{
25    BackupKeys, Changes, CryptoStoreError, DehydratedDeviceKey, PendingChanges, Result,
26    RoomKeyCounts, RoomSettings,
27};
28#[cfg(doc)]
29use crate::olm::SenderData;
30use crate::{
31    olm::{
32        InboundGroupSession, OlmMessageHash, OutboundGroupSession, PrivateCrossSigningIdentity,
33        SenderDataType, Session,
34    },
35    types::events::room_key_withheld::RoomKeyWithheldEvent,
36    Account, DeviceData, GossipRequest, GossippedSecret, SecretInfo, TrackedUser, UserIdentityData,
37};
38
39/// Represents a store that the `OlmMachine` uses to store E2EE data (such as
40/// cryptographic keys).
41#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
42#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
43pub trait CryptoStore: AsyncTraitDeps {
44    /// The error type used by this crypto store.
45    type Error: fmt::Debug + Into<CryptoStoreError>;
46
47    /// Load an account that was previously stored.
48    async fn load_account(&self) -> Result<Option<Account>, Self::Error>;
49
50    /// Try to load a private cross signing identity, if one is stored.
51    async fn load_identity(&self) -> Result<Option<PrivateCrossSigningIdentity>, Self::Error>;
52
53    /// Save the set of changes to the store.
54    ///
55    /// # Arguments
56    ///
57    /// * `changes` - The set of changes that should be stored.
58    async fn save_changes(&self, changes: Changes) -> Result<(), Self::Error>;
59
60    /// Save the set of changes to the store.
61    ///
62    /// This is an updated version of `save_changes` that will replace it as
63    /// #2624 makes progress.
64    ///
65    /// # Arguments
66    ///
67    /// * `changes` - The set of changes that should be stored.
68    async fn save_pending_changes(&self, changes: PendingChanges) -> Result<(), Self::Error>;
69
70    /// Save a list of inbound group sessions to the store.
71    ///
72    /// # Arguments
73    ///
74    /// * `sessions` - The sessions to be saved.
75    /// * `backed_up_to_version` - If the keys should be marked as having been
76    ///   backed up, the version of the backup.
77    ///
78    /// Note: some implementations ignore `backup_version` and assume the
79    /// current backup version, which is normally the same.
80    async fn save_inbound_group_sessions(
81        &self,
82        sessions: Vec<InboundGroupSession>,
83        backed_up_to_version: Option<&str>,
84    ) -> Result<(), Self::Error>;
85
86    /// Get all the sessions that belong to the given sender key.
87    ///
88    /// # Arguments
89    ///
90    /// * `sender_key` - The sender key that was used to establish the sessions.
91    async fn get_sessions(&self, sender_key: &str) -> Result<Option<Vec<Session>>, Self::Error>;
92
93    /// Get the inbound group session from our store.
94    ///
95    /// # Arguments
96    /// * `room_id` - The room id of the room that the session belongs to.
97    ///
98    /// * `sender_key` - The sender key that sent us the session.
99    ///
100    /// * `session_id` - The unique id of the session.
101    async fn get_inbound_group_session(
102        &self,
103        room_id: &RoomId,
104        session_id: &str,
105    ) -> Result<Option<InboundGroupSession>, Self::Error>;
106
107    /// Get withheld info for this key.
108    /// Allows to know if the session was not sent on purpose.
109    /// This only returns withheld info sent by the owner of the group session,
110    /// not the one you can get from a response to a key request from
111    /// another of your device.
112    async fn get_withheld_info(
113        &self,
114        room_id: &RoomId,
115        session_id: &str,
116    ) -> Result<Option<RoomKeyWithheldEvent>, Self::Error>;
117
118    /// Get all the inbound group sessions we have stored.
119    async fn get_inbound_group_sessions(&self) -> Result<Vec<InboundGroupSession>, Self::Error>;
120
121    /// Get the number inbound group sessions we have and how many of them are
122    /// backed up.
123    async fn inbound_group_session_counts(
124        &self,
125        backup_version: Option<&str>,
126    ) -> Result<RoomKeyCounts, Self::Error>;
127
128    /// Get a batch of inbound group sessions for the device with the supplied
129    /// curve key, whose sender data is of the supplied type.
130    ///
131    /// Sessions are not necessarily returned in any specific order, but the
132    /// returned batches are consistent: if this function is called repeatedly
133    /// with `after_session_id` set to the session ID from the last result
134    /// from the previous call, until an empty result is returned, then
135    /// eventually all matching sessions are returned. (New sessions that are
136    /// added in the course of iteration may or may not be returned.)
137    ///
138    /// This function is used when the device information is updated via a
139    /// `/keys/query` response and we want to update the sender data based
140    /// on the new information.
141    ///
142    /// # Arguments
143    ///
144    /// * `curve_key` - only return sessions created by the device with this
145    ///   curve key.
146    ///
147    /// * `sender_data_type` - only return sessions whose [`SenderData`] record
148    ///   is in this state.
149    ///
150    /// * `after_session_id` - return the sessions after this id, or start at
151    ///   the earliest if this is None.
152    ///
153    /// * `limit` - return a maximum of this many sessions.
154    async fn get_inbound_group_sessions_for_device_batch(
155        &self,
156        curve_key: Curve25519PublicKey,
157        sender_data_type: SenderDataType,
158        after_session_id: Option<String>,
159        limit: usize,
160    ) -> Result<Vec<InboundGroupSession>, Self::Error>;
161
162    /// Return a batch of ['InboundGroupSession'] ("room keys") that have not
163    /// yet been backed up in the supplied backup version.
164    ///
165    /// The size of the returned `Vec` is <= `limit`.
166    ///
167    /// Note: some implementations ignore `backup_version` and assume the
168    /// current backup version, which is normally the same.
169    async fn inbound_group_sessions_for_backup(
170        &self,
171        backup_version: &str,
172        limit: usize,
173    ) -> Result<Vec<InboundGroupSession>, Self::Error>;
174
175    /// Store the fact that the supplied sessions were backed up into the backup
176    /// with version `backup_version`.
177    ///
178    /// Note: some implementations ignore `backup_version` and assume the
179    /// current backup version, which is normally the same.
180    async fn mark_inbound_group_sessions_as_backed_up(
181        &self,
182        backup_version: &str,
183        room_and_session_ids: &[(&RoomId, &str)],
184    ) -> Result<(), Self::Error>;
185
186    /// Reset the backup state of all the stored inbound group sessions.
187    ///
188    /// Note: this is mostly implemented by stores that ignore the
189    /// `backup_version` argument on `inbound_group_sessions_for_backup` and
190    /// `mark_inbound_group_sessions_as_backed_up`. Implementations that
191    /// pay attention to the supplied backup version probably don't need to
192    /// update their storage when the current backup version changes, so have
193    /// empty implementations of this method.
194    async fn reset_backup_state(&self) -> Result<(), Self::Error>;
195
196    /// Get the backup keys we have stored.
197    async fn load_backup_keys(&self) -> Result<BackupKeys, Self::Error>;
198
199    /// Get the dehydrated device pickle key we have stored.
200    async fn load_dehydrated_device_pickle_key(
201        &self,
202    ) -> Result<Option<DehydratedDeviceKey>, Self::Error>;
203
204    /// Deletes the previously stored dehydrated device pickle key.
205    async fn delete_dehydrated_device_pickle_key(&self) -> Result<(), Self::Error>;
206
207    /// Get the outbound group session we have stored that is used for the
208    /// given room.
209    async fn get_outbound_group_session(
210        &self,
211        room_id: &RoomId,
212    ) -> Result<Option<OutboundGroupSession>, Self::Error>;
213
214    /// Provide the list of users whose devices we are keeping track of, and
215    /// whether they are considered dirty/outdated.
216    async fn load_tracked_users(&self) -> Result<Vec<TrackedUser>, Self::Error>;
217
218    /// Update the list of users whose devices we are keeping track of, and
219    /// whether they are considered dirty/outdated.
220    ///
221    /// Replaces any existing entry with a matching user ID.
222    async fn save_tracked_users(&self, users: &[(&UserId, bool)]) -> Result<(), Self::Error>;
223
224    /// Get the device for the given user with the given device ID.
225    ///
226    /// # Arguments
227    ///
228    /// * `user_id` - The user that the device belongs to.
229    ///
230    /// * `device_id` - The unique id of the device.
231    async fn get_device(
232        &self,
233        user_id: &UserId,
234        device_id: &DeviceId,
235    ) -> Result<Option<DeviceData>, Self::Error>;
236
237    /// Get all the devices of the given user.
238    ///
239    /// # Arguments
240    ///
241    /// * `user_id` - The user for which we should get all the devices.
242    async fn get_user_devices(
243        &self,
244        user_id: &UserId,
245    ) -> Result<HashMap<OwnedDeviceId, DeviceData>, Self::Error>;
246
247    /// Get the device for the current client.
248    ///
249    /// Since our own device is set when the store is created, this will always
250    /// return a device (unless there is an error).
251    async fn get_own_device(&self) -> Result<DeviceData, Self::Error>;
252
253    /// Get the user identity that is attached to the given user id.
254    ///
255    /// # Arguments
256    ///
257    /// * `user_id` - The user for which we should get the identity.
258    async fn get_user_identity(
259        &self,
260        user_id: &UserId,
261    ) -> Result<Option<UserIdentityData>, Self::Error>;
262
263    /// Check if a hash for an Olm message stored in the database.
264    async fn is_message_known(&self, message_hash: &OlmMessageHash) -> Result<bool, Self::Error>;
265
266    /// Get an outgoing secret request that we created that matches the given
267    /// request id.
268    ///
269    /// # Arguments
270    ///
271    /// * `request_id` - The unique request id that identifies this outgoing
272    /// secret request.
273    async fn get_outgoing_secret_requests(
274        &self,
275        request_id: &TransactionId,
276    ) -> Result<Option<GossipRequest>, Self::Error>;
277
278    /// Get an outgoing key request that we created that matches the given
279    /// requested key info.
280    ///
281    /// # Arguments
282    ///
283    /// * `key_info` - The key info of an outgoing secret request.
284    async fn get_secret_request_by_info(
285        &self,
286        secret_info: &SecretInfo,
287    ) -> Result<Option<GossipRequest>, Self::Error>;
288
289    /// Get all outgoing secret requests that we have in the store.
290    async fn get_unsent_secret_requests(&self) -> Result<Vec<GossipRequest>, Self::Error>;
291
292    /// Delete an outgoing key request that we created that matches the given
293    /// request id.
294    ///
295    /// # Arguments
296    ///
297    /// * `request_id` - The unique request id that identifies this outgoing key
298    /// request.
299    async fn delete_outgoing_secret_requests(
300        &self,
301        request_id: &TransactionId,
302    ) -> Result<(), Self::Error>;
303
304    /// Get all the secrets with the given [`SecretName`] we have currently
305    /// stored.
306    async fn get_secrets_from_inbox(
307        &self,
308        secret_name: &SecretName,
309    ) -> Result<Vec<GossippedSecret>, Self::Error>;
310
311    /// Delete all the secrets with the given [`SecretName`] we have currently
312    /// stored.
313    async fn delete_secrets_from_inbox(&self, secret_name: &SecretName) -> Result<(), Self::Error>;
314
315    /// Get the room settings, such as the encryption algorithm or whether to
316    /// encrypt only for trusted devices.
317    ///
318    /// # Arguments
319    ///
320    /// * `room_id` - The room id of the room
321    async fn get_room_settings(
322        &self,
323        room_id: &RoomId,
324    ) -> Result<Option<RoomSettings>, Self::Error>;
325
326    /// Get arbitrary data from the store
327    ///
328    /// # Arguments
329    ///
330    /// * `key` - The key to fetch data for
331    async fn get_custom_value(&self, key: &str) -> Result<Option<Vec<u8>>, Self::Error>;
332
333    /// Put arbitrary data into the store
334    ///
335    /// # Arguments
336    ///
337    /// * `key` - The key to insert data into
338    ///
339    /// * `value` - The value to insert
340    async fn set_custom_value(&self, key: &str, value: Vec<u8>) -> Result<(), Self::Error>;
341
342    /// Remove arbitrary data into the store
343    ///
344    /// # Arguments
345    ///
346    /// * `key` - The key to insert data into
347    async fn remove_custom_value(&self, key: &str) -> Result<(), Self::Error>;
348
349    /// Try to take a leased lock.
350    ///
351    /// This attempts to take a lock for the given lease duration.
352    ///
353    /// - If we already had the lease, this will extend the lease.
354    /// - If we didn't, but the previous lease has expired, we will acquire the
355    ///   lock.
356    /// - If there was no previous lease, we will acquire the lock.
357    /// - Otherwise, we don't get the lock.
358    ///
359    /// Returns whether taking the lock succeeded.
360    async fn try_take_leased_lock(
361        &self,
362        lease_duration_ms: u32,
363        key: &str,
364        holder: &str,
365    ) -> Result<bool, Self::Error>;
366
367    /// Load the next-batch token for a to-device query, if any.
368    async fn next_batch_token(&self) -> Result<Option<String>, Self::Error>;
369}
370
371#[repr(transparent)]
372struct EraseCryptoStoreError<T>(T);
373
374#[cfg(not(tarpaulin_include))]
375impl<T: fmt::Debug> fmt::Debug for EraseCryptoStoreError<T> {
376    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377        self.0.fmt(f)
378    }
379}
380
381#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
382#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
383impl<T: CryptoStore> CryptoStore for EraseCryptoStoreError<T> {
384    type Error = CryptoStoreError;
385
386    async fn load_account(&self) -> Result<Option<Account>> {
387        self.0.load_account().await.map_err(Into::into)
388    }
389
390    async fn load_identity(&self) -> Result<Option<PrivateCrossSigningIdentity>> {
391        self.0.load_identity().await.map_err(Into::into)
392    }
393
394    async fn save_changes(&self, changes: Changes) -> Result<()> {
395        self.0.save_changes(changes).await.map_err(Into::into)
396    }
397
398    async fn save_pending_changes(&self, changes: PendingChanges) -> Result<()> {
399        self.0.save_pending_changes(changes).await.map_err(Into::into)
400    }
401
402    async fn save_inbound_group_sessions(
403        &self,
404        sessions: Vec<InboundGroupSession>,
405        backed_up_to_version: Option<&str>,
406    ) -> Result<()> {
407        self.0.save_inbound_group_sessions(sessions, backed_up_to_version).await.map_err(Into::into)
408    }
409
410    async fn get_sessions(&self, sender_key: &str) -> Result<Option<Vec<Session>>> {
411        self.0.get_sessions(sender_key).await.map_err(Into::into)
412    }
413
414    async fn get_inbound_group_session(
415        &self,
416        room_id: &RoomId,
417        session_id: &str,
418    ) -> Result<Option<InboundGroupSession>> {
419        self.0.get_inbound_group_session(room_id, session_id).await.map_err(Into::into)
420    }
421
422    async fn get_inbound_group_sessions(&self) -> Result<Vec<InboundGroupSession>> {
423        self.0.get_inbound_group_sessions().await.map_err(Into::into)
424    }
425
426    async fn get_inbound_group_sessions_for_device_batch(
427        &self,
428        curve_key: Curve25519PublicKey,
429        sender_data_type: SenderDataType,
430        after_session_id: Option<String>,
431        limit: usize,
432    ) -> Result<Vec<InboundGroupSession>> {
433        self.0
434            .get_inbound_group_sessions_for_device_batch(
435                curve_key,
436                sender_data_type,
437                after_session_id,
438                limit,
439            )
440            .await
441            .map_err(Into::into)
442    }
443
444    async fn inbound_group_session_counts(
445        &self,
446        backup_version: Option<&str>,
447    ) -> Result<RoomKeyCounts> {
448        self.0.inbound_group_session_counts(backup_version).await.map_err(Into::into)
449    }
450    async fn inbound_group_sessions_for_backup(
451        &self,
452        backup_version: &str,
453        limit: usize,
454    ) -> Result<Vec<InboundGroupSession>> {
455        self.0.inbound_group_sessions_for_backup(backup_version, limit).await.map_err(Into::into)
456    }
457
458    async fn mark_inbound_group_sessions_as_backed_up(
459        &self,
460        backup_version: &str,
461        room_and_session_ids: &[(&RoomId, &str)],
462    ) -> Result<()> {
463        self.0
464            .mark_inbound_group_sessions_as_backed_up(backup_version, room_and_session_ids)
465            .await
466            .map_err(Into::into)
467    }
468
469    async fn reset_backup_state(&self) -> Result<()> {
470        self.0.reset_backup_state().await.map_err(Into::into)
471    }
472
473    async fn load_backup_keys(&self) -> Result<BackupKeys> {
474        self.0.load_backup_keys().await.map_err(Into::into)
475    }
476
477    async fn load_dehydrated_device_pickle_key(&self) -> Result<Option<DehydratedDeviceKey>> {
478        self.0.load_dehydrated_device_pickle_key().await.map_err(Into::into)
479    }
480
481    async fn delete_dehydrated_device_pickle_key(&self) -> Result<(), Self::Error> {
482        self.0.delete_dehydrated_device_pickle_key().await.map_err(Into::into)
483    }
484
485    async fn get_outbound_group_session(
486        &self,
487        room_id: &RoomId,
488    ) -> Result<Option<OutboundGroupSession>> {
489        self.0.get_outbound_group_session(room_id).await.map_err(Into::into)
490    }
491
492    async fn load_tracked_users(&self) -> Result<Vec<TrackedUser>> {
493        self.0.load_tracked_users().await.map_err(Into::into)
494    }
495
496    async fn save_tracked_users(&self, users: &[(&UserId, bool)]) -> Result<()> {
497        self.0.save_tracked_users(users).await.map_err(Into::into)
498    }
499
500    async fn get_device(
501        &self,
502        user_id: &UserId,
503        device_id: &DeviceId,
504    ) -> Result<Option<DeviceData>> {
505        self.0.get_device(user_id, device_id).await.map_err(Into::into)
506    }
507
508    async fn get_user_devices(
509        &self,
510        user_id: &UserId,
511    ) -> Result<HashMap<OwnedDeviceId, DeviceData>> {
512        self.0.get_user_devices(user_id).await.map_err(Into::into)
513    }
514
515    async fn get_own_device(&self) -> Result<DeviceData> {
516        self.0.get_own_device().await.map_err(Into::into)
517    }
518
519    async fn get_user_identity(&self, user_id: &UserId) -> Result<Option<UserIdentityData>> {
520        self.0.get_user_identity(user_id).await.map_err(Into::into)
521    }
522
523    async fn is_message_known(&self, message_hash: &OlmMessageHash) -> Result<bool> {
524        self.0.is_message_known(message_hash).await.map_err(Into::into)
525    }
526
527    async fn get_outgoing_secret_requests(
528        &self,
529        request_id: &TransactionId,
530    ) -> Result<Option<GossipRequest>> {
531        self.0.get_outgoing_secret_requests(request_id).await.map_err(Into::into)
532    }
533
534    async fn get_secret_request_by_info(
535        &self,
536        secret_info: &SecretInfo,
537    ) -> Result<Option<GossipRequest>> {
538        self.0.get_secret_request_by_info(secret_info).await.map_err(Into::into)
539    }
540
541    async fn get_unsent_secret_requests(&self) -> Result<Vec<GossipRequest>> {
542        self.0.get_unsent_secret_requests().await.map_err(Into::into)
543    }
544
545    async fn delete_outgoing_secret_requests(&self, request_id: &TransactionId) -> Result<()> {
546        self.0.delete_outgoing_secret_requests(request_id).await.map_err(Into::into)
547    }
548
549    async fn get_secrets_from_inbox(
550        &self,
551        secret_name: &SecretName,
552    ) -> Result<Vec<GossippedSecret>> {
553        self.0.get_secrets_from_inbox(secret_name).await.map_err(Into::into)
554    }
555
556    async fn delete_secrets_from_inbox(&self, secret_name: &SecretName) -> Result<()> {
557        self.0.delete_secrets_from_inbox(secret_name).await.map_err(Into::into)
558    }
559
560    async fn get_withheld_info(
561        &self,
562        room_id: &RoomId,
563        session_id: &str,
564    ) -> Result<Option<RoomKeyWithheldEvent>, Self::Error> {
565        self.0.get_withheld_info(room_id, session_id).await.map_err(Into::into)
566    }
567
568    async fn get_room_settings(&self, room_id: &RoomId) -> Result<Option<RoomSettings>> {
569        self.0.get_room_settings(room_id).await.map_err(Into::into)
570    }
571
572    async fn get_custom_value(&self, key: &str) -> Result<Option<Vec<u8>>, Self::Error> {
573        self.0.get_custom_value(key).await.map_err(Into::into)
574    }
575
576    async fn set_custom_value(&self, key: &str, value: Vec<u8>) -> Result<(), Self::Error> {
577        self.0.set_custom_value(key, value).await.map_err(Into::into)
578    }
579
580    async fn remove_custom_value(&self, key: &str) -> Result<(), Self::Error> {
581        self.0.remove_custom_value(key).await.map_err(Into::into)
582    }
583
584    async fn try_take_leased_lock(
585        &self,
586        lease_duration_ms: u32,
587        key: &str,
588        holder: &str,
589    ) -> Result<bool, Self::Error> {
590        self.0.try_take_leased_lock(lease_duration_ms, key, holder).await.map_err(Into::into)
591    }
592
593    async fn next_batch_token(&self) -> Result<Option<String>, Self::Error> {
594        self.0.next_batch_token().await.map_err(Into::into)
595    }
596}
597
598/// A type-erased [`CryptoStore`].
599pub type DynCryptoStore = dyn CryptoStore<Error = CryptoStoreError>;
600
601/// A type that can be type-erased into `Arc<DynCryptoStore>`.
602///
603/// This trait is not meant to be implemented directly outside
604/// `matrix-sdk-crypto`, but it is automatically implemented for everything that
605/// implements `CryptoStore`.
606pub trait IntoCryptoStore {
607    #[doc(hidden)]
608    fn into_crypto_store(self) -> Arc<DynCryptoStore>;
609}
610
611impl<T> IntoCryptoStore for T
612where
613    T: CryptoStore + 'static,
614{
615    fn into_crypto_store(self) -> Arc<DynCryptoStore> {
616        Arc::new(EraseCryptoStoreError(self))
617    }
618}
619
620// Turns a given `Arc<T>` into `Arc<DynCryptoStore>` by attaching the
621// CryptoStore impl vtable of `EraseCryptoStoreError<T>`.
622impl<T> IntoCryptoStore for Arc<T>
623where
624    T: CryptoStore + 'static,
625{
626    fn into_crypto_store(self) -> Arc<DynCryptoStore> {
627        let ptr: *const T = Arc::into_raw(self);
628        let ptr_erased = ptr as *const EraseCryptoStoreError<T>;
629        // SAFETY: EraseCryptoStoreError is repr(transparent) so T and
630        //         EraseCryptoStoreError<T> have the same layout and ABI
631        unsafe { Arc::from_raw(ptr_erased) }
632    }
633}
634
635impl IntoCryptoStore for Arc<DynCryptoStore> {
636    fn into_crypto_store(self) -> Arc<DynCryptoStore> {
637        self
638    }
639}