1use 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#[cfg_attr(target_family = "wasm", async_trait(?Send))]
45#[cfg_attr(not(target_family = "wasm"), async_trait)]
46pub trait CryptoStore: AsyncTraitDeps {
47 type Error: fmt::Debug + Into<CryptoStoreError>;
49
50 async fn load_account(&self) -> Result<Option<Account>, Self::Error>;
52
53 async fn load_identity(&self) -> Result<Option<PrivateCrossSigningIdentity>, Self::Error>;
55
56 async fn save_changes(&self, changes: Changes) -> Result<(), Self::Error>;
62
63 async fn save_pending_changes(&self, changes: PendingChanges) -> Result<(), Self::Error>;
72
73 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 async fn get_sessions(&self, sender_key: &str) -> Result<Option<Vec<Session>>, Self::Error>;
95
96 async fn get_inbound_group_session(
105 &self,
106 room_id: &RoomId,
107 session_id: &str,
108 ) -> Result<Option<InboundGroupSession>, Self::Error>;
109
110 async fn get_withheld_info(
116 &self,
117 room_id: &RoomId,
118 session_id: &str,
119 ) -> Result<Option<RoomKeyWithheldEntry>, Self::Error>;
120
121 async fn get_withheld_sessions_by_room_id(
130 &self,
131 room_id: &RoomId,
132 ) -> Result<Vec<RoomKeyWithheldEntry>, Self::Error>;
133
134 async fn get_inbound_group_sessions(&self) -> Result<Vec<InboundGroupSession>, Self::Error>;
136
137 async fn inbound_group_session_counts(
140 &self,
141 backup_version: Option<&str>,
142 ) -> Result<RoomKeyCounts, Self::Error>;
143
144 async fn get_inbound_group_sessions_by_room_id(
149 &self,
150 room_id: &RoomId,
151 ) -> Result<Vec<InboundGroupSession>, Self::Error>;
152
153 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 async fn inbound_group_sessions_for_backup(
195 &self,
196 backup_version: &str,
197 limit: usize,
198 ) -> Result<Vec<InboundGroupSession>, Self::Error>;
199
200 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 async fn reset_backup_state(&self) -> Result<(), Self::Error>;
220
221 async fn load_backup_keys(&self) -> Result<BackupKeys, Self::Error>;
223
224 async fn load_dehydrated_device_pickle_key(
226 &self,
227 ) -> Result<Option<DehydratedDeviceKey>, Self::Error>;
228
229 async fn delete_dehydrated_device_pickle_key(&self) -> Result<(), Self::Error>;
231
232 async fn get_outbound_group_session(
235 &self,
236 room_id: &RoomId,
237 ) -> Result<Option<OutboundGroupSession>, Self::Error>;
238
239 async fn load_tracked_users(&self) -> Result<Vec<TrackedUser>, Self::Error>;
242
243 async fn save_tracked_users(&self, users: &[(&UserId, bool)]) -> Result<(), Self::Error>;
248
249 async fn get_device(
257 &self,
258 user_id: &UserId,
259 device_id: &DeviceId,
260 ) -> Result<Option<DeviceData>, Self::Error>;
261
262 async fn get_user_devices(
268 &self,
269 user_id: &UserId,
270 ) -> Result<HashMap<OwnedDeviceId, DeviceData>, Self::Error>;
271
272 async fn get_own_device(&self) -> Result<DeviceData, Self::Error>;
277
278 async fn get_user_identity(
284 &self,
285 user_id: &UserId,
286 ) -> Result<Option<UserIdentityData>, Self::Error>;
287
288 async fn is_message_known(&self, message_hash: &OlmMessageHash) -> Result<bool, Self::Error>;
290
291 async fn get_outgoing_secret_requests(
299 &self,
300 request_id: &TransactionId,
301 ) -> Result<Option<GossipRequest>, Self::Error>;
302
303 async fn get_secret_request_by_info(
310 &self,
311 secret_info: &SecretInfo,
312 ) -> Result<Option<GossipRequest>, Self::Error>;
313
314 async fn get_unsent_secret_requests(&self) -> Result<Vec<GossipRequest>, Self::Error>;
316
317 async fn delete_outgoing_secret_requests(
325 &self,
326 request_id: &TransactionId,
327 ) -> Result<(), Self::Error>;
328
329 async fn get_secrets_from_inbox(
332 &self,
333 secret_name: &SecretName,
334 ) -> Result<Vec<GossippedSecret>, Self::Error>;
335
336 async fn delete_secrets_from_inbox(&self, secret_name: &SecretName) -> Result<(), Self::Error>;
339
340 async fn get_room_settings(
347 &self,
348 room_id: &RoomId,
349 ) -> Result<Option<RoomSettings>, Self::Error>;
350
351 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 async fn get_custom_value(&self, key: &str) -> Result<Option<Vec<u8>>, Self::Error>;
365
366 async fn set_custom_value(&self, key: &str, value: Vec<u8>) -> Result<(), Self::Error>;
374
375 async fn remove_custom_value(&self, key: &str) -> Result<(), Self::Error>;
381
382 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 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
653pub type DynCryptoStore = dyn CryptoStore<Error = CryptoStoreError>;
655
656pub 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
675impl<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 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}