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::{cross_process_lock::CrossProcessLockGeneration, 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<Option<CrossProcessLockGeneration>, 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    /// Returns the size of the store in bytes, if known.
404    async fn get_size(&self) -> Result<Option<usize>, Self::Error>;
405}
406
407#[repr(transparent)]
408struct EraseCryptoStoreError<T>(T);
409
410#[cfg(not(tarpaulin_include))]
411impl<T: fmt::Debug> fmt::Debug for EraseCryptoStoreError<T> {
412    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
413        self.0.fmt(f)
414    }
415}
416
417#[cfg_attr(target_family = "wasm", async_trait(?Send))]
418#[cfg_attr(not(target_family = "wasm"), async_trait)]
419impl<T: CryptoStore> CryptoStore for EraseCryptoStoreError<T> {
420    type Error = CryptoStoreError;
421
422    async fn load_account(&self) -> Result<Option<Account>> {
423        self.0.load_account().await.map_err(Into::into)
424    }
425
426    async fn load_identity(&self) -> Result<Option<PrivateCrossSigningIdentity>> {
427        self.0.load_identity().await.map_err(Into::into)
428    }
429
430    async fn save_changes(&self, changes: Changes) -> Result<()> {
431        self.0.save_changes(changes).await.map_err(Into::into)
432    }
433
434    async fn save_pending_changes(&self, changes: PendingChanges) -> Result<()> {
435        self.0.save_pending_changes(changes).await.map_err(Into::into)
436    }
437
438    async fn save_inbound_group_sessions(
439        &self,
440        sessions: Vec<InboundGroupSession>,
441        backed_up_to_version: Option<&str>,
442    ) -> Result<()> {
443        self.0.save_inbound_group_sessions(sessions, backed_up_to_version).await.map_err(Into::into)
444    }
445
446    async fn get_sessions(&self, sender_key: &str) -> Result<Option<Vec<Session>>> {
447        self.0.get_sessions(sender_key).await.map_err(Into::into)
448    }
449
450    async fn get_inbound_group_session(
451        &self,
452        room_id: &RoomId,
453        session_id: &str,
454    ) -> Result<Option<InboundGroupSession>> {
455        self.0.get_inbound_group_session(room_id, session_id).await.map_err(Into::into)
456    }
457
458    async fn get_inbound_group_sessions(&self) -> Result<Vec<InboundGroupSession>> {
459        self.0.get_inbound_group_sessions().await.map_err(Into::into)
460    }
461
462    async fn get_inbound_group_sessions_by_room_id(
463        &self,
464        room_id: &RoomId,
465    ) -> Result<Vec<InboundGroupSession>> {
466        self.0.get_inbound_group_sessions_by_room_id(room_id).await.map_err(Into::into)
467    }
468
469    async fn get_inbound_group_sessions_for_device_batch(
470        &self,
471        curve_key: Curve25519PublicKey,
472        sender_data_type: SenderDataType,
473        after_session_id: Option<String>,
474        limit: usize,
475    ) -> Result<Vec<InboundGroupSession>> {
476        self.0
477            .get_inbound_group_sessions_for_device_batch(
478                curve_key,
479                sender_data_type,
480                after_session_id,
481                limit,
482            )
483            .await
484            .map_err(Into::into)
485    }
486
487    async fn inbound_group_session_counts(
488        &self,
489        backup_version: Option<&str>,
490    ) -> Result<RoomKeyCounts> {
491        self.0.inbound_group_session_counts(backup_version).await.map_err(Into::into)
492    }
493    async fn inbound_group_sessions_for_backup(
494        &self,
495        backup_version: &str,
496        limit: usize,
497    ) -> Result<Vec<InboundGroupSession>> {
498        self.0.inbound_group_sessions_for_backup(backup_version, limit).await.map_err(Into::into)
499    }
500
501    async fn mark_inbound_group_sessions_as_backed_up(
502        &self,
503        backup_version: &str,
504        room_and_session_ids: &[(&RoomId, &str)],
505    ) -> Result<()> {
506        self.0
507            .mark_inbound_group_sessions_as_backed_up(backup_version, room_and_session_ids)
508            .await
509            .map_err(Into::into)
510    }
511
512    async fn reset_backup_state(&self) -> Result<()> {
513        self.0.reset_backup_state().await.map_err(Into::into)
514    }
515
516    async fn load_backup_keys(&self) -> Result<BackupKeys> {
517        self.0.load_backup_keys().await.map_err(Into::into)
518    }
519
520    async fn load_dehydrated_device_pickle_key(&self) -> Result<Option<DehydratedDeviceKey>> {
521        self.0.load_dehydrated_device_pickle_key().await.map_err(Into::into)
522    }
523
524    async fn delete_dehydrated_device_pickle_key(&self) -> Result<(), Self::Error> {
525        self.0.delete_dehydrated_device_pickle_key().await.map_err(Into::into)
526    }
527
528    async fn get_outbound_group_session(
529        &self,
530        room_id: &RoomId,
531    ) -> Result<Option<OutboundGroupSession>> {
532        self.0.get_outbound_group_session(room_id).await.map_err(Into::into)
533    }
534
535    async fn load_tracked_users(&self) -> Result<Vec<TrackedUser>> {
536        self.0.load_tracked_users().await.map_err(Into::into)
537    }
538
539    async fn save_tracked_users(&self, users: &[(&UserId, bool)]) -> Result<()> {
540        self.0.save_tracked_users(users).await.map_err(Into::into)
541    }
542
543    async fn get_device(
544        &self,
545        user_id: &UserId,
546        device_id: &DeviceId,
547    ) -> Result<Option<DeviceData>> {
548        self.0.get_device(user_id, device_id).await.map_err(Into::into)
549    }
550
551    async fn get_user_devices(
552        &self,
553        user_id: &UserId,
554    ) -> Result<HashMap<OwnedDeviceId, DeviceData>> {
555        self.0.get_user_devices(user_id).await.map_err(Into::into)
556    }
557
558    async fn get_own_device(&self) -> Result<DeviceData> {
559        self.0.get_own_device().await.map_err(Into::into)
560    }
561
562    async fn get_user_identity(&self, user_id: &UserId) -> Result<Option<UserIdentityData>> {
563        self.0.get_user_identity(user_id).await.map_err(Into::into)
564    }
565
566    async fn is_message_known(&self, message_hash: &OlmMessageHash) -> Result<bool> {
567        self.0.is_message_known(message_hash).await.map_err(Into::into)
568    }
569
570    async fn get_outgoing_secret_requests(
571        &self,
572        request_id: &TransactionId,
573    ) -> Result<Option<GossipRequest>> {
574        self.0.get_outgoing_secret_requests(request_id).await.map_err(Into::into)
575    }
576
577    async fn get_secret_request_by_info(
578        &self,
579        secret_info: &SecretInfo,
580    ) -> Result<Option<GossipRequest>> {
581        self.0.get_secret_request_by_info(secret_info).await.map_err(Into::into)
582    }
583
584    async fn get_unsent_secret_requests(&self) -> Result<Vec<GossipRequest>> {
585        self.0.get_unsent_secret_requests().await.map_err(Into::into)
586    }
587
588    async fn delete_outgoing_secret_requests(&self, request_id: &TransactionId) -> Result<()> {
589        self.0.delete_outgoing_secret_requests(request_id).await.map_err(Into::into)
590    }
591
592    async fn get_secrets_from_inbox(
593        &self,
594        secret_name: &SecretName,
595    ) -> Result<Vec<GossippedSecret>> {
596        self.0.get_secrets_from_inbox(secret_name).await.map_err(Into::into)
597    }
598
599    async fn delete_secrets_from_inbox(&self, secret_name: &SecretName) -> Result<()> {
600        self.0.delete_secrets_from_inbox(secret_name).await.map_err(Into::into)
601    }
602
603    async fn get_withheld_info(
604        &self,
605        room_id: &RoomId,
606        session_id: &str,
607    ) -> Result<Option<RoomKeyWithheldEntry>, Self::Error> {
608        self.0.get_withheld_info(room_id, session_id).await.map_err(Into::into)
609    }
610
611    async fn get_withheld_sessions_by_room_id(
612        &self,
613        room_id: &RoomId,
614    ) -> Result<Vec<RoomKeyWithheldEntry>, Self::Error> {
615        self.0.get_withheld_sessions_by_room_id(room_id).await.map_err(Into::into)
616    }
617
618    async fn get_room_settings(&self, room_id: &RoomId) -> Result<Option<RoomSettings>> {
619        self.0.get_room_settings(room_id).await.map_err(Into::into)
620    }
621
622    async fn get_received_room_key_bundle_data(
623        &self,
624        room_id: &RoomId,
625        user_id: &UserId,
626    ) -> Result<Option<StoredRoomKeyBundleData>> {
627        self.0.get_received_room_key_bundle_data(room_id, user_id).await.map_err(Into::into)
628    }
629
630    async fn get_custom_value(&self, key: &str) -> Result<Option<Vec<u8>>, Self::Error> {
631        self.0.get_custom_value(key).await.map_err(Into::into)
632    }
633
634    async fn set_custom_value(&self, key: &str, value: Vec<u8>) -> Result<(), Self::Error> {
635        self.0.set_custom_value(key, value).await.map_err(Into::into)
636    }
637
638    async fn remove_custom_value(&self, key: &str) -> Result<(), Self::Error> {
639        self.0.remove_custom_value(key).await.map_err(Into::into)
640    }
641
642    async fn try_take_leased_lock(
643        &self,
644        lease_duration_ms: u32,
645        key: &str,
646        holder: &str,
647    ) -> Result<Option<CrossProcessLockGeneration>, Self::Error> {
648        self.0.try_take_leased_lock(lease_duration_ms, key, holder).await.map_err(Into::into)
649    }
650
651    async fn next_batch_token(&self) -> Result<Option<String>, Self::Error> {
652        self.0.next_batch_token().await.map_err(Into::into)
653    }
654
655    async fn get_size(&self) -> Result<Option<usize>, Self::Error> {
656        self.0.get_size().await.map_err(Into::into)
657    }
658}
659
660/// A type-erased [`CryptoStore`].
661pub type DynCryptoStore = dyn CryptoStore<Error = CryptoStoreError>;
662
663/// A type that can be type-erased into `Arc<DynCryptoStore>`.
664///
665/// This trait is not meant to be implemented directly outside
666/// `matrix-sdk-crypto`, but it is automatically implemented for everything that
667/// implements `CryptoStore`.
668pub trait IntoCryptoStore {
669    #[doc(hidden)]
670    fn into_crypto_store(self) -> Arc<DynCryptoStore>;
671}
672
673impl<T> IntoCryptoStore for T
674where
675    T: CryptoStore + 'static,
676{
677    fn into_crypto_store(self) -> Arc<DynCryptoStore> {
678        Arc::new(EraseCryptoStoreError(self))
679    }
680}
681
682// Turns a given `Arc<T>` into `Arc<DynCryptoStore>` by attaching the
683// CryptoStore impl vtable of `EraseCryptoStoreError<T>`.
684impl<T> IntoCryptoStore for Arc<T>
685where
686    T: CryptoStore + 'static,
687{
688    fn into_crypto_store(self) -> Arc<DynCryptoStore> {
689        let ptr: *const T = Arc::into_raw(self);
690        let ptr_erased = ptr as *const EraseCryptoStoreError<T>;
691        // SAFETY: EraseCryptoStoreError is repr(transparent) so T and
692        //         EraseCryptoStoreError<T> have the same layout and ABI
693        unsafe { Arc::from_raw(ptr_erased) }
694    }
695}
696
697impl IntoCryptoStore for Arc<DynCryptoStore> {
698    fn into_crypto_store(self) -> Arc<DynCryptoStore> {
699        self
700    }
701}