1use 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#[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<Option<CrossProcessLockGeneration>, Self::Error>;
399
400 async fn next_batch_token(&self) -> Result<Option<String>, Self::Error>;
402
403 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
660pub type DynCryptoStore = dyn CryptoStore<Error = CryptoStoreError>;
662
663pub 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
682impl<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 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}