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