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 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#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
42#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
43pub trait CryptoStore: AsyncTraitDeps {
44 type Error: fmt::Debug + Into<CryptoStoreError>;
46
47 async fn load_account(&self) -> Result<Option<Account>, Self::Error>;
49
50 async fn load_identity(&self) -> Result<Option<PrivateCrossSigningIdentity>, Self::Error>;
52
53 async fn save_changes(&self, changes: Changes) -> Result<(), Self::Error>;
59
60 async fn save_pending_changes(&self, changes: PendingChanges) -> Result<(), Self::Error>;
69
70 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 async fn get_sessions(&self, sender_key: &str) -> Result<Option<Vec<Session>>, Self::Error>;
92
93 async fn get_inbound_group_session(
102 &self,
103 room_id: &RoomId,
104 session_id: &str,
105 ) -> Result<Option<InboundGroupSession>, Self::Error>;
106
107 async fn get_withheld_info(
113 &self,
114 room_id: &RoomId,
115 session_id: &str,
116 ) -> Result<Option<RoomKeyWithheldEvent>, Self::Error>;
117
118 async fn get_inbound_group_sessions(&self) -> Result<Vec<InboundGroupSession>, Self::Error>;
120
121 async fn inbound_group_session_counts(
124 &self,
125 backup_version: Option<&str>,
126 ) -> Result<RoomKeyCounts, Self::Error>;
127
128 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 async fn inbound_group_sessions_for_backup(
170 &self,
171 backup_version: &str,
172 limit: usize,
173 ) -> Result<Vec<InboundGroupSession>, Self::Error>;
174
175 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 async fn reset_backup_state(&self) -> Result<(), Self::Error>;
195
196 async fn load_backup_keys(&self) -> Result<BackupKeys, Self::Error>;
198
199 async fn load_dehydrated_device_pickle_key(
201 &self,
202 ) -> Result<Option<DehydratedDeviceKey>, Self::Error>;
203
204 async fn delete_dehydrated_device_pickle_key(&self) -> Result<(), Self::Error>;
206
207 async fn get_outbound_group_session(
210 &self,
211 room_id: &RoomId,
212 ) -> Result<Option<OutboundGroupSession>, Self::Error>;
213
214 async fn load_tracked_users(&self) -> Result<Vec<TrackedUser>, Self::Error>;
217
218 async fn save_tracked_users(&self, users: &[(&UserId, bool)]) -> Result<(), Self::Error>;
223
224 async fn get_device(
232 &self,
233 user_id: &UserId,
234 device_id: &DeviceId,
235 ) -> Result<Option<DeviceData>, Self::Error>;
236
237 async fn get_user_devices(
243 &self,
244 user_id: &UserId,
245 ) -> Result<HashMap<OwnedDeviceId, DeviceData>, Self::Error>;
246
247 async fn get_own_device(&self) -> Result<DeviceData, Self::Error>;
252
253 async fn get_user_identity(
259 &self,
260 user_id: &UserId,
261 ) -> Result<Option<UserIdentityData>, Self::Error>;
262
263 async fn is_message_known(&self, message_hash: &OlmMessageHash) -> Result<bool, Self::Error>;
265
266 async fn get_outgoing_secret_requests(
274 &self,
275 request_id: &TransactionId,
276 ) -> Result<Option<GossipRequest>, Self::Error>;
277
278 async fn get_secret_request_by_info(
285 &self,
286 secret_info: &SecretInfo,
287 ) -> Result<Option<GossipRequest>, Self::Error>;
288
289 async fn get_unsent_secret_requests(&self) -> Result<Vec<GossipRequest>, Self::Error>;
291
292 async fn delete_outgoing_secret_requests(
300 &self,
301 request_id: &TransactionId,
302 ) -> Result<(), Self::Error>;
303
304 async fn get_secrets_from_inbox(
307 &self,
308 secret_name: &SecretName,
309 ) -> Result<Vec<GossippedSecret>, Self::Error>;
310
311 async fn delete_secrets_from_inbox(&self, secret_name: &SecretName) -> Result<(), Self::Error>;
314
315 async fn get_room_settings(
322 &self,
323 room_id: &RoomId,
324 ) -> Result<Option<RoomSettings>, Self::Error>;
325
326 async fn get_custom_value(&self, key: &str) -> Result<Option<Vec<u8>>, Self::Error>;
332
333 async fn set_custom_value(&self, key: &str, value: Vec<u8>) -> Result<(), Self::Error>;
341
342 async fn remove_custom_value(&self, key: &str) -> Result<(), Self::Error>;
348
349 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 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
598pub type DynCryptoStore = dyn CryptoStore<Error = CryptoStoreError>;
600
601pub 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
620impl<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 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}