1#![doc = include_str!("../docs/encryption.md")]
17#![cfg_attr(target_family = "wasm", allow(unused_imports))]
18
19#[cfg(feature = "experimental-send-custom-to-device")]
20use std::{collections::BTreeSet, ops::Deref};
21use std::{
22 collections::{BTreeMap, HashSet},
23 io::{Cursor, Read, Write},
24 iter, mem,
25 path::{Path, PathBuf},
26 str::FromStr,
27 sync::Arc,
28 time::Duration,
29};
30
31#[cfg(feature = "experimental-send-custom-to-device")]
32use as_variant::as_variant;
33use eyeball::{SharedObservable, Subscriber};
34use futures_core::Stream;
35use futures_util::{
36 future::try_join,
37 stream::{self, StreamExt},
38};
39#[cfg(feature = "experimental-send-custom-to-device")]
40use matrix_sdk_base::crypto::CollectStrategy;
41use matrix_sdk_base::{
42 StateStoreDataKey, StateStoreDataValue,
43 cross_process_lock::{AcquireCrossProcessLockFn, CrossProcessLock, CrossProcessLockError},
44 crypto::{
45 CrossSigningBootstrapRequests, OlmMachine, UncommittedCrossSigningReset,
46 store::{
47 LockableCryptoStore, SecretImportError,
48 types::{RoomKeyBundleInfo, RoomKeyInfo},
49 },
50 types::{
51 SecretsBundle, SignedKey,
52 requests::{
53 OutgoingRequest, OutgoingVerificationRequest, RoomMessageRequest, ToDeviceRequest,
54 },
55 },
56 },
57 sleep::sleep,
58 timeout::timeout,
59};
60use matrix_sdk_common::{executor::spawn, locks::Mutex as StdMutex};
61use ruma::{
62 DeviceId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, TransactionId, UserId,
63 api::{
64 client::{
65 keys::{get_keys, upload_keys, upload_signing_keys},
66 message::send_message_event,
67 to_device::send_event_to_device::v3::{
68 Request as RumaToDeviceRequest, Response as ToDeviceResponse,
69 },
70 uiaa::{
71 AuthData, AuthType, OAuth as OAuthData, OAuthParams, Password, UiaaInfo,
72 UserIdentifier,
73 },
74 },
75 error::{ErrorBody, StandardErrorBody},
76 },
77 assign,
78 events::room::{
79 MediaSource, ThumbnailInfo,
80 member::{MembershipChange, OriginalSyncRoomMemberEvent},
81 },
82};
83#[cfg(feature = "experimental-send-custom-to-device")]
84use ruma::{
85 events::{AnyToDeviceEventContent, ToDeviceEventType},
86 serde::Raw,
87 to_device::DeviceIdOrAllDevices,
88};
89use serde::{Deserialize, de::Error as _};
90use tasks::BundleReceiverTask;
91use tokio::sync::{Mutex, RwLockReadGuard};
92use tokio_stream::wrappers::errors::BroadcastStreamRecvError;
93use tracing::{Instrument, Span, debug, error, instrument, warn};
94use url::Url;
95use vodozemac::Curve25519PublicKey;
96
97use self::{
98 backups::{Backups, types::BackupClientState},
99 futures::UploadEncryptedFile,
100 identities::{Device, DeviceUpdates, IdentityUpdates, UserDevices, UserIdentity},
101 recovery::{Recovery, RecoveryState},
102 secret_storage::SecretStorage,
103 tasks::{BackupDownloadTask, BackupUploadingTask, ClientTasks},
104 verification::{SasVerification, Verification, VerificationRequest},
105};
106use crate::{
107 Client, Error, HttpError, Result, Room, TransmissionProgress,
108 attachment::Thumbnail,
109 client::{ClientInner, WeakClient},
110 cross_process_lock::CrossProcessLockGuard,
111 error::HttpResult,
112};
113
114pub mod backups;
115pub mod dehydrated_devices;
116pub mod futures;
117pub mod identities;
118pub mod recovery;
119pub mod secret_storage;
120pub(crate) mod tasks;
121pub mod verification;
122
123use matrix_sdk_base::crypto::OlmMachineBuilder;
124pub use matrix_sdk_base::crypto::{
125 CrossSigningStatus, CryptoStoreError, DecryptorError, EventError, KeyExportError, LocalTrust,
126 MediaEncryptionInfo, MegolmError, OlmError, RoomKeyImportResult, SessionCreationError,
127 SignatureError, VERSION,
128 olm::{
129 SessionCreationError as MegolmSessionCreationError,
130 SessionExportError as OlmSessionExportError,
131 },
132 vodozemac,
133};
134use matrix_sdk_common::cross_process_lock::CrossProcessLockConfig;
135
136#[cfg(feature = "experimental-send-custom-to-device")]
137use crate::config::RequestConfig;
138pub use crate::error::RoomKeyImportError;
139
140#[cfg(feature = "sqlite")]
143#[derive(Debug, thiserror::Error)]
144pub enum BundleExportError {
145 #[error(transparent)]
147 OpenStoreError(#[from] matrix_sdk_sqlite::OpenStoreError),
148 #[error(transparent)]
150 StoreError(#[from] CryptoStoreError),
151 #[error(transparent)]
154 SecretExport(#[from] matrix_sdk_base::crypto::store::SecretsBundleExportError),
155}
156
157#[derive(Debug, thiserror::Error)]
160pub enum BundleImportError {
161 #[error(transparent)]
163 SecretImport(#[from] SecretImportError),
164 #[error(transparent)]
166 DeviceKeys(#[from] Error),
167}
168
169#[cfg(feature = "sqlite")]
178pub async fn export_secrets_bundle_from_store(
179 database_path: impl AsRef<Path>,
180 passphrase: Option<&str>,
181) -> std::result::Result<Option<(OwnedUserId, SecretsBundle)>, BundleExportError> {
182 use matrix_sdk_base::crypto::store::CryptoStore;
183
184 let store = matrix_sdk_sqlite::SqliteCryptoStore::open(database_path, passphrase).await?;
185 let account =
186 store.load_account().await.map_err(|e| BundleExportError::StoreError(e.into()))?;
187
188 if let Some(account) = account {
189 let machine = OlmMachineBuilder::new(&account.user_id, &account.device_id)
190 .with_crypto_store(store)
191 .build()
192 .await
193 .map_err(BundleExportError::StoreError)?;
194
195 let bundle = machine.store().export_secrets_bundle().await?;
196
197 Ok(Some((account.user_id.to_owned(), bundle)))
198 } else {
199 Ok(None)
200 }
201}
202
203pub(crate) struct EncryptionData {
205 pub tasks: StdMutex<ClientTasks>,
208
209 pub encryption_settings: EncryptionSettings,
211
212 pub backup_state: BackupClientState,
214
215 pub recovery_state: SharedObservable<RecoveryState>,
217
218 pub dehydrated_devices_state: dehydrated_devices::DehydratedDevicesState,
221}
222
223impl EncryptionData {
224 pub fn new(encryption_settings: EncryptionSettings) -> Self {
225 Self {
226 encryption_settings,
227
228 tasks: StdMutex::new(Default::default()),
229 backup_state: Default::default(),
230 recovery_state: Default::default(),
231 dehydrated_devices_state: Default::default(),
232 }
233 }
234
235 pub fn initialize_tasks(&self, client: &Arc<ClientInner>) {
236 let weak_client = WeakClient::from_inner(client);
237
238 let mut tasks = self.tasks.lock();
239 tasks.upload_room_keys = Some(BackupUploadingTask::new(weak_client.clone()));
240
241 if self.encryption_settings.backup_download_strategy
242 == BackupDownloadStrategy::AfterDecryptionFailure
243 {
244 tasks.download_room_keys = Some(BackupDownloadTask::new(weak_client));
245 }
246 }
247
248 pub fn initialize_recovery_state_update_task(&self, client: &Client) {
254 let mut guard = self.tasks.lock();
255
256 let future = Recovery::update_state_after_backup_state_change(client);
257 let join_handle = spawn(future);
258
259 guard.update_recovery_state_after_backup = Some(join_handle);
260 }
261}
262
263#[derive(Clone, Copy, Debug, Default)]
265pub struct EncryptionSettings {
266 pub auto_enable_cross_signing: bool,
272
273 pub backup_download_strategy: BackupDownloadStrategy,
278
279 pub auto_enable_backups: bool,
281}
282
283#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
285#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
286pub enum BackupDownloadStrategy {
287 OneShot,
298
299 AfterDecryptionFailure,
301
302 #[default]
307 Manual,
308}
309
310#[derive(Clone, Copy, Debug, Eq, PartialEq)]
315pub enum VerificationState {
316 Unknown,
318 Verified,
321 Unverified,
323}
324
325#[derive(Debug)]
340pub struct CrossSigningResetHandle {
341 client: Client,
342 inner: Mutex<Option<UncommittedCrossSigningReset>>,
343 auth_type: CrossSigningResetAuthType,
344 is_cancelled: Mutex<bool>,
345}
346
347impl CrossSigningResetHandle {
348 pub(crate) fn new(
350 client: Client,
351 inner: UncommittedCrossSigningReset,
352 auth_type: CrossSigningResetAuthType,
353 ) -> Self {
354 Self { client, inner: Mutex::new(Some(inner)), auth_type, is_cancelled: Mutex::new(false) }
355 }
356
357 pub fn auth_type(&self) -> &CrossSigningResetAuthType {
360 &self.auth_type
361 }
362
363 pub async fn auth(&self, auth: AuthData) -> Result<bool> {
371 const RETRY_EVERY: Duration = Duration::from_millis(500);
373
374 const TIMEOUT: Duration = Duration::from_mins(2);
376
377 if *self.is_cancelled.lock().await || self.inner.lock().await.is_none() {
380 return Ok(false);
381 }
382
383 let mut upload_signing_keys_req: upload_signing_keys::v3::Request = {
384 let inner = self.inner.lock().await;
385 let Some(handle) = inner.as_ref() else {
388 return Ok(false);
389 };
390 handle.upload_signing_keys_req().into()
391 };
392 upload_signing_keys_req.auth = Some(auth);
393
394 let signing_keys_uploaded = timeout(
395 async {
396 debug!(
397 "Repeatedly PUTting to keys/device_signing/upload until it works \
398 or we hit a permanent failure."
399 );
400 while let Err(e) = self.client.send(upload_signing_keys_req.clone()).await {
401 if *self.is_cancelled.lock().await || self.inner.lock().await.is_none() {
405 return Ok(false);
406 }
407
408 match e.as_uiaa_response() {
409 Some(uiaa_info) => {
410 if !matches!(self.auth_type, CrossSigningResetAuthType::OAuth(_))
413 && uiaa_info.auth_error.is_some()
414 {
415 return Err(e.into());
416 }
417 }
418 None => return Err(e.into()),
419 }
420
421 debug!(
422 "PUT to keys/device_signing/upload failed with 401. Retrying after \
423 a short delay."
424 );
425 sleep(RETRY_EVERY).await;
426 }
427
428 Ok(true)
429 },
430 TIMEOUT,
431 )
432 .await
433 .unwrap_or_else(|_| {
434 warn!("Timed out waiting for keys/device_signing/upload to succeed.");
435 Err(Error::Timeout)
436 })?;
437
438 if !signing_keys_uploaded {
442 return Ok(false);
443 }
444
445 let mut guard = self.inner.lock().await;
448 let Some(handle) = mem::take(&mut *guard) else {
449 return Ok(false);
450 };
451
452 let upload_signatures_req = handle.commit().await?;
453
454 let olm = self.client.olm_machine().await;
455 let olm = olm.as_ref().ok_or(Error::NoOlmMachine)?;
456
457 self.client.send(upload_signatures_req).await?;
461
462 if let Some((_, request)) = olm.upload_device_keys().await? {
463 self.client.send_outgoing_request(request.into()).await?;
464 }
465
466 self.client.encryption().query_own_keys(olm).await;
468
469 Ok(true)
473 }
474
475 pub async fn cancel(&self) {
477 *self.is_cancelled.lock().await = true;
478 }
479}
480
481#[derive(Debug, Clone)]
484pub enum CrossSigningResetAuthType {
485 Uiaa(UiaaCrossSigningResetInfo),
487 OAuth(OAuthCrossSigningResetInfo),
490}
491
492impl CrossSigningResetAuthType {
493 fn new(error: &HttpError) -> Result<Option<Self>> {
494 if let Some(auth_info) = error.as_uiaa_response() {
495 if let Ok(Some(auth_info)) = OAuthCrossSigningResetInfo::from_auth_info(auth_info) {
496 Ok(Some(CrossSigningResetAuthType::OAuth(auth_info)))
497 } else {
498 Ok(Some(CrossSigningResetAuthType::Uiaa(
499 UiaaCrossSigningResetInfo::from_auth_info(auth_info)?,
500 )))
501 }
502 } else {
503 Ok(None)
504 }
505 }
506}
507
508#[derive(Debug, Clone)]
511pub struct UiaaCrossSigningResetInfo {
512 auth_info: UiaaInfo,
513}
514
515impl UiaaCrossSigningResetInfo {
516 fn from_auth_info(auth_info: &UiaaInfo) -> Result<Self> {
517 if auth_info.session.is_none() {
518 return Err(serde_json::Error::custom("UIAA info is missing a session token").into());
519 }
520
521 Ok(UiaaCrossSigningResetInfo { auth_info: auth_info.clone() })
522 }
523
524 pub fn session(&self) -> &str {
526 self.auth_info.session.as_deref().expect("The session is checked in from_auth_info")
527 }
528
529 pub fn auth_info(&self) -> &UiaaInfo {
532 &self.auth_info
533 }
534
535 pub fn as_password_auth_data(&self, identifier: UserIdentifier, password: String) -> AuthData {
541 AuthData::Password(assign!(Password::new(identifier, password), {
542 session: Some(self.session().to_owned()),
543 }))
544 }
545}
546
547#[derive(Debug, Clone, Deserialize)]
550pub struct OAuthCrossSigningResetInfo {
551 pub approval_url: Url,
553
554 pub session: String,
556}
557
558impl OAuthCrossSigningResetInfo {
559 fn from_auth_info(auth_info: &UiaaInfo) -> Result<Option<Self>> {
560 let Some(parameters) = auth_info.params::<OAuthParams>(&AuthType::OAuth)? else {
561 return Ok(None);
562 };
563
564 Ok(Some(OAuthCrossSigningResetInfo {
565 approval_url: parameters.url.as_str().try_into()?,
566 session: auth_info
567 .session
568 .as_ref()
569 .ok_or_else(|| serde_json::Error::custom("UIAA info is missing a session token"))?
570 .to_owned(),
571 }))
572 }
573
574 pub fn as_auth_data(&self) -> AuthData {
576 AuthData::OAuth(assign!(OAuthData::new(), { session: Some(self.session.clone()) }))
577 }
578}
579
580#[derive(Clone, Debug)]
583pub struct DuplicateOneTimeKeyErrorMessage {
584 pub old_key: Curve25519PublicKey,
586 pub new_key: Curve25519PublicKey,
588}
589
590impl FromStr for DuplicateOneTimeKeyErrorMessage {
591 type Err = serde_json::Error;
592
593 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
594 let mut split = s.split_terminator(';');
598
599 let old_key = split
600 .next()
601 .ok_or(serde_json::Error::custom("Old key is missing in the error message"))?;
602 let new_key = split
603 .next()
604 .ok_or(serde_json::Error::custom("New key is missing in the error message"))?;
605
606 let old_key_index = old_key
609 .find("Old key:")
610 .ok_or(serde_json::Error::custom("Old key is missing the prefix"))?;
611
612 let old_key = old_key[old_key_index..]
613 .trim()
614 .strip_prefix("Old key:")
615 .ok_or(serde_json::Error::custom("Old key is missing the prefix"))?;
616
617 let new_key = new_key
620 .trim()
621 .strip_prefix("new key:")
622 .ok_or(serde_json::Error::custom("New key is missing the prefix"))?;
623
624 let new_key = new_key.replace("'", "\"");
627
628 let old_key: SignedKey = serde_json::from_str(old_key)?;
630 let new_key: SignedKey = serde_json::from_str(&new_key)?;
631
632 let old_key = old_key.key();
634 let new_key = new_key.key();
635
636 Ok(Self { old_key, new_key })
637 }
638}
639
640impl Client {
641 pub(crate) async fn olm_machine(&self) -> RwLockReadGuard<'_, Option<OlmMachine>> {
642 self.base_client().olm_machine().await
643 }
644
645 pub(crate) async fn mark_request_as_sent(
646 &self,
647 request_id: &TransactionId,
648 response: impl Into<matrix_sdk_base::crypto::types::requests::AnyIncomingResponse<'_>>,
649 ) -> Result<(), matrix_sdk_base::Error> {
650 Ok(self
651 .olm_machine()
652 .await
653 .as_ref()
654 .expect(
655 "We should have an olm machine once we try to mark E2EE related requests as sent",
656 )
657 .mark_request_as_sent(request_id, response)
658 .await?)
659 }
660
661 #[instrument(skip(self, device_keys))]
667 pub(crate) async fn keys_query(
668 &self,
669 request_id: &TransactionId,
670 device_keys: BTreeMap<OwnedUserId, Vec<OwnedDeviceId>>,
671 ) -> Result<get_keys::v3::Response> {
672 let request = assign!(get_keys::v3::Request::new(), { device_keys });
673
674 let response = self.send(request).await?;
675 self.mark_request_as_sent(request_id, &response).await?;
676 self.encryption().update_state_after_keys_query(&response).await;
677
678 Ok(response)
679 }
680
681 pub fn upload_encrypted_file<'a, R: Read + ?Sized + 'a>(
715 &'a self,
716 reader: &'a mut R,
717 ) -> UploadEncryptedFile<'a, R> {
718 UploadEncryptedFile::new(self, reader)
719 }
720
721 pub(crate) async fn upload_encrypted_media_and_thumbnail(
724 &self,
725 data: &[u8],
726 thumbnail: Option<Thumbnail>,
727 send_progress: SharedObservable<TransmissionProgress>,
728 ) -> Result<(MediaSource, Option<(MediaSource, Box<ThumbnailInfo>)>)> {
729 let upload_thumbnail = self.upload_encrypted_thumbnail(thumbnail, send_progress.clone());
730
731 let upload_attachment = async {
732 let mut cursor = Cursor::new(data);
733 self.upload_encrypted_file(&mut cursor)
734 .with_send_progress_observable(send_progress)
735 .await
736 };
737
738 let (thumbnail, file) = try_join(upload_thumbnail, upload_attachment).await?;
739
740 Ok((MediaSource::Encrypted(Box::new(file)), thumbnail))
741 }
742
743 async fn upload_encrypted_thumbnail(
746 &self,
747 thumbnail: Option<Thumbnail>,
748 send_progress: SharedObservable<TransmissionProgress>,
749 ) -> Result<Option<(MediaSource, Box<ThumbnailInfo>)>> {
750 let Some(thumbnail) = thumbnail else {
751 return Ok(None);
752 };
753
754 let (data, _, thumbnail_info) = thumbnail.into_parts();
755 let mut cursor = Cursor::new(data);
756
757 let file = self
758 .upload_encrypted_file(&mut cursor)
759 .with_send_progress_observable(send_progress)
760 .await?;
761
762 Ok(Some((MediaSource::Encrypted(Box::new(file)), thumbnail_info)))
763 }
764
765 pub(crate) async fn claim_one_time_keys(
771 &self,
772 users: impl Iterator<Item = &UserId>,
773 ) -> Result<()> {
774 let _lock = self.locks().key_claim_lock.lock().await;
775
776 if let Some((request_id, request)) = self
777 .olm_machine()
778 .await
779 .as_ref()
780 .ok_or(Error::NoOlmMachine)?
781 .get_missing_sessions(users)
782 .await?
783 {
784 let response = self.send(request).await?;
785 self.mark_request_as_sent(&request_id, &response).await?;
786 }
787
788 Ok(())
789 }
790
791 #[instrument(skip(self, request))]
801 pub(crate) async fn keys_upload(
802 &self,
803 request_id: &TransactionId,
804 request: &upload_keys::v3::Request,
805 ) -> Result<upload_keys::v3::Response> {
806 debug!(
807 device_keys = request.device_keys.is_some(),
808 one_time_key_count = request.one_time_keys.len(),
809 "Uploading public encryption keys",
810 );
811
812 let response = self.send(request.clone()).await?;
813 self.mark_request_as_sent(request_id, &response).await?;
814
815 Ok(response)
816 }
817
818 pub(crate) async fn room_send_helper(
819 &self,
820 request: &RoomMessageRequest,
821 ) -> Result<send_message_event::v3::Response> {
822 let content = request.content.clone();
823 let txn_id = request.txn_id.clone();
824 let room_id = &request.room_id;
825
826 self.get_room(room_id)
827 .expect("Can't send a message to a room that isn't known to the store")
828 .send(*content)
829 .with_transaction_id(txn_id)
830 .await
831 .map(|result| result.response)
832 }
833
834 pub(crate) async fn send_to_device(
835 &self,
836 request: &ToDeviceRequest,
837 ) -> HttpResult<ToDeviceResponse> {
838 let request = RumaToDeviceRequest::new_raw(
839 request.event_type.clone(),
840 request.txn_id.clone(),
841 request.messages.clone(),
842 );
843
844 self.send(request).await
845 }
846
847 pub(crate) async fn send_verification_request(
848 &self,
849 request: OutgoingVerificationRequest,
850 ) -> Result<()> {
851 use matrix_sdk_base::crypto::types::requests::OutgoingVerificationRequest::*;
852
853 match request {
854 ToDevice(t) => {
855 self.send_to_device(&t).await?;
856 }
857 InRoom(r) => {
858 self.room_send_helper(&r).await?;
859 }
860 }
861
862 Ok(())
863 }
864
865 async fn send_outgoing_request(&self, r: OutgoingRequest) -> Result<()> {
866 use matrix_sdk_base::crypto::types::requests::AnyOutgoingRequest;
867
868 match r.request() {
869 AnyOutgoingRequest::KeysQuery(request) => {
870 self.keys_query(r.request_id(), request.device_keys.clone()).await?;
871 }
872 AnyOutgoingRequest::KeysUpload(request) => {
873 let response = self.keys_upload(r.request_id(), request).await;
874
875 if let Err(e) = &response {
876 match e.as_client_api_error() {
877 Some(e) if e.status_code == 400 => {
878 if let ErrorBody::Standard(StandardErrorBody { message, .. }) = &e.body
879 {
880 {
886 let already_reported = self
887 .state_store()
888 .get_kv_data(StateStoreDataKey::OneTimeKeyAlreadyUploaded)
889 .await?
890 .is_some();
891
892 if message.starts_with("One time key") && !already_reported {
893 let error_message =
894 DuplicateOneTimeKeyErrorMessage::from_str(message);
895
896 if let Ok(message) = &error_message {
897 error!(
898 sentry = true,
899 old_key = %message.old_key,
900 new_key = %message.new_key,
901 "Duplicate one-time keys have been uploaded"
902 );
903 } else {
904 error!(
905 sentry = true,
906 "Duplicate one-time keys have been uploaded"
907 );
908 }
909
910 self.state_store()
911 .set_kv_data(
912 StateStoreDataKey::OneTimeKeyAlreadyUploaded,
913 StateStoreDataValue::OneTimeKeyAlreadyUploaded,
914 )
915 .await?;
916
917 if let Err(e) = self
918 .inner
919 .duplicate_key_upload_error_sender
920 .send(error_message.ok())
921 {
922 error!(
923 "Failed to dispatch duplicate key upload error notification: {}",
924 e
925 );
926 }
927 }
928 }
929 }
930 }
931 _ => {}
932 }
933
934 response?;
935 }
936 }
937 AnyOutgoingRequest::ToDeviceRequest(request) => {
938 let response = self.send_to_device(request).await?;
939 self.mark_request_as_sent(r.request_id(), &response).await?;
940 }
941 AnyOutgoingRequest::SignatureUpload(request) => {
942 let response = self.send(request.clone()).await?;
943 self.mark_request_as_sent(r.request_id(), &response).await?;
944 }
945 AnyOutgoingRequest::RoomMessage(request) => {
946 let response = self.room_send_helper(request).await?;
947 self.mark_request_as_sent(r.request_id(), &response).await?;
948 }
949 AnyOutgoingRequest::KeysClaim(request) => {
950 let response = self.send(request.clone()).await?;
951 self.mark_request_as_sent(r.request_id(), &response).await?;
952 }
953 }
954
955 Ok(())
956 }
957
958 #[instrument(skip_all)]
959 pub(crate) async fn send_outgoing_requests(&self) -> Result<()> {
960 const MAX_CONCURRENT_REQUESTS: usize = 20;
961
962 if let Err(e) = self.claim_one_time_keys(iter::empty()).await {
965 warn!("Error while claiming one-time keys {:?}", e);
966 }
967
968 let outgoing_requests = stream::iter(
969 self.olm_machine()
970 .await
971 .as_ref()
972 .ok_or(Error::NoOlmMachine)?
973 .outgoing_requests()
974 .await?,
975 )
976 .map(|r| self.send_outgoing_request(r));
977
978 let requests = outgoing_requests.buffer_unordered(MAX_CONCURRENT_REQUESTS);
979
980 requests
981 .for_each(|r| async move {
982 match r {
983 Ok(_) => (),
984 Err(e) => warn!(error = ?e, "Error when sending out an outgoing E2EE request"),
985 }
986 })
987 .await;
988
989 Ok(())
990 }
991}
992
993#[cfg(feature = "experimental-send-custom-to-device")]
994impl Client {
995 pub async fn send_encrypted_to_device(
1023 &self,
1024 event_type: &ToDeviceEventType,
1025 recipients: BTreeMap<OwnedUserId, Vec<DeviceIdOrAllDevices>>,
1026 content: Raw<AnyToDeviceEventContent>,
1027 ) -> Result<BTreeMap<OwnedUserId, Vec<OwnedDeviceId>>> {
1028 let mut failures: BTreeMap<OwnedUserId, Vec<OwnedDeviceId>> = BTreeMap::new();
1029 let mut recipient_devices = Vec::<_>::new();
1030
1031 for (user_id, recipient_device_ids) in recipients {
1033 let (devices, unknown_devices) =
1034 self.resolve_recipient_devices(&user_id, recipient_device_ids).await?;
1035 recipient_devices.extend(devices);
1036 if !unknown_devices.is_empty() {
1037 failures.insert(user_id, unknown_devices);
1038 }
1039 }
1040
1041 if !recipient_devices.is_empty() {
1042 let encrypt_and_send_failures = self
1043 .encryption()
1044 .encrypt_and_send_raw_to_device(
1045 recipient_devices.iter().collect(),
1046 &event_type.to_string(),
1047 content,
1048 CollectStrategy::AllDevices,
1049 )
1050 .await?;
1051
1052 for (user_id, device_id) in encrypt_and_send_failures {
1053 failures.entry(user_id).or_default().push(device_id)
1054 }
1055 }
1056
1057 Ok(failures)
1058 }
1059
1060 async fn resolve_recipient_devices(
1069 &self,
1070 user_id: &UserId,
1071 recipient_device_ids: Vec<DeviceIdOrAllDevices>,
1072 ) -> Result<(Vec<Device>, Vec<OwnedDeviceId>)> {
1073 let user_devices = self.encryption().get_user_devices(user_id).await?;
1074
1075 if recipient_device_ids.contains(&DeviceIdOrAllDevices::AllDevices) {
1076 let devices: Vec<_> = user_devices.devices().collect();
1080
1081 if devices.is_empty() {
1082 warn!(
1083 "Recipient list contains `AllDevices` but no devices found for user {user_id}."
1084 );
1085 }
1086 if recipient_device_ids.len() > 1 {
1087 warn!(
1088 "The recipient_device_ids list for {user_id} contains both `AllDevices` and explicit `DeviceId` entries. Only consider `AllDevices`",
1089 );
1090 }
1091
1092 Ok((devices, Vec::new()))
1093 } else {
1094 let (found_device_ids, devices): (BTreeSet<_>, Vec<_>) = user_devices
1097 .devices()
1098 .map(|device| (device.device_id().to_owned(), device))
1099 .filter(|(device_id, _)| {
1100 recipient_device_ids
1101 .contains(&DeviceIdOrAllDevices::DeviceId(device_id.clone()))
1102 })
1103 .unzip();
1104
1105 let requested_device_ids: BTreeSet<_> = recipient_device_ids
1106 .into_iter()
1107 .filter_map(|d| as_variant!(d, DeviceIdOrAllDevices::DeviceId))
1108 .collect();
1109
1110 let missing_devices =
1113 requested_device_ids.difference(&found_device_ids).map(ToOwned::to_owned).collect();
1114
1115 Ok((devices, missing_devices))
1116 }
1117 }
1118}
1119
1120#[cfg(any(feature = "testing", test))]
1121impl Client {
1122 pub async fn olm_machine_for_testing(&self) -> RwLockReadGuard<'_, Option<OlmMachine>> {
1124 self.olm_machine().await
1125 }
1126
1127 pub fn abort_bundle_receiver_task(&self) {
1129 let tasks = self.inner.e2ee.tasks.lock();
1130 if let Some(task) = tasks.receive_historic_room_key_bundles.as_ref() {
1131 task.abort()
1132 }
1133 }
1134}
1135
1136#[derive(Debug, Clone)]
1140pub struct Encryption {
1141 client: Client,
1143}
1144
1145impl Encryption {
1146 pub(crate) fn new(client: Client) -> Self {
1147 Self { client }
1148 }
1149
1150 pub(crate) fn settings(&self) -> EncryptionSettings {
1152 self.client.inner.e2ee.encryption_settings
1153 }
1154
1155 pub async fn ed25519_key(&self) -> Option<String> {
1158 self.client.olm_machine().await.as_ref().map(|o| o.identity_keys().ed25519.to_base64())
1159 }
1160
1161 pub async fn curve25519_key(&self) -> Option<Curve25519PublicKey> {
1163 self.client.olm_machine().await.as_ref().map(|o| o.identity_keys().curve25519)
1164 }
1165
1166 pub async fn device_creation_timestamp(&self) -> MilliSecondsSinceUnixEpoch {
1168 match self.get_own_device().await {
1169 Ok(Some(device)) => device.first_time_seen_ts(),
1170 _ => MilliSecondsSinceUnixEpoch::now(),
1172 }
1173 }
1174
1175 pub async fn import_secrets_bundle(
1188 &self,
1189 bundle: &SecretsBundle,
1190 ) -> Result<(), BundleImportError> {
1191 self.import_secrets_bundle_impl(bundle).await?;
1192
1193 self.ensure_device_keys_upload().await?;
1196 self.wait_for_e2ee_initialization_tasks().await;
1197
1198 if !self.backups().are_enabled().await {
1203 self.backups().maybe_resume_backups().await?;
1204 }
1205
1206 Ok(())
1207 }
1208
1209 pub(crate) async fn import_secrets_bundle_impl(
1210 &self,
1211 bundle: &SecretsBundle,
1212 ) -> Result<(), SecretImportError> {
1213 let olm_machine = self.client.olm_machine().await;
1214 let olm_machine =
1215 olm_machine.as_ref().expect("This should only be called once we have an OlmMachine");
1216
1217 olm_machine.store().import_secrets_bundle(bundle).await
1218 }
1219
1220 pub async fn cross_signing_status(&self) -> Option<CrossSigningStatus> {
1225 let olm = self.client.olm_machine().await;
1226 let machine = olm.as_ref()?;
1227 Some(machine.cross_signing_status().await)
1228 }
1229
1230 pub async fn has_devices_to_verify_against(&self) -> Result<bool> {
1236 let olm_machine = self.client.olm_machine().await;
1237 let olm_machine = olm_machine.as_ref().ok_or(Error::NoOlmMachine)?;
1238
1239 self.ensure_initial_key_query().await?;
1240
1241 let devices = olm_machine.get_user_devices(olm_machine.user_id(), None).await?;
1242
1243 Ok(devices.has_other_devices_to_verify_against())
1244 }
1245
1246 pub async fn tracked_users(&self) -> Result<HashSet<OwnedUserId>, CryptoStoreError> {
1251 if let Some(machine) = self.client.olm_machine().await.as_ref() {
1252 machine.tracked_users().await
1253 } else {
1254 Ok(HashSet::new())
1255 }
1256 }
1257
1258 pub fn verification_state(&self) -> Subscriber<VerificationState> {
1281 self.client.inner.verification_state.subscribe_reset()
1282 }
1283
1284 pub async fn get_verification(&self, user_id: &UserId, flow_id: &str) -> Option<Verification> {
1286 let olm = self.client.olm_machine().await;
1287 let olm = olm.as_ref()?;
1288 #[allow(clippy::bind_instead_of_map)]
1289 olm.get_verification(user_id, flow_id).and_then(|v| match v {
1290 matrix_sdk_base::crypto::Verification::SasV1(sas) => {
1291 Some(SasVerification { inner: sas, client: self.client.clone() }.into())
1292 }
1293 #[cfg(feature = "qrcode")]
1294 matrix_sdk_base::crypto::Verification::QrV1(qr) => {
1295 Some(verification::QrVerification { inner: qr, client: self.client.clone() }.into())
1296 }
1297 _ => None,
1298 })
1299 }
1300
1301 pub async fn get_verification_request(
1304 &self,
1305 user_id: &UserId,
1306 flow_id: impl AsRef<str>,
1307 ) -> Option<VerificationRequest> {
1308 let olm = self.client.olm_machine().await;
1309 let olm = olm.as_ref()?;
1310
1311 olm.get_verification_request(user_id, flow_id)
1312 .map(|r| VerificationRequest { inner: r, client: self.client.clone() })
1313 }
1314
1315 pub async fn get_device(
1348 &self,
1349 user_id: &UserId,
1350 device_id: &DeviceId,
1351 ) -> Result<Option<Device>, CryptoStoreError> {
1352 let olm = self.client.olm_machine().await;
1353 let Some(machine) = olm.as_ref() else { return Ok(None) };
1354 let device = machine.get_device(user_id, device_id, None).await?;
1355 Ok(device.map(|d| Device { inner: d, client: self.client.clone() }))
1356 }
1357
1358 pub async fn get_own_device(&self) -> Result<Option<Device>, CryptoStoreError> {
1365 let olm = self.client.olm_machine().await;
1366 let Some(machine) = olm.as_ref() else { return Ok(None) };
1367 let device = machine.get_device(machine.user_id(), machine.device_id(), None).await?;
1368 Ok(device.map(|d| Device { inner: d, client: self.client.clone() }))
1369 }
1370
1371 pub async fn get_user_devices(&self, user_id: &UserId) -> Result<UserDevices, Error> {
1397 let devices = self
1398 .client
1399 .olm_machine()
1400 .await
1401 .as_ref()
1402 .ok_or(Error::NoOlmMachine)?
1403 .get_user_devices(user_id, None)
1404 .await?;
1405
1406 Ok(UserDevices { inner: devices, client: self.client.clone() })
1407 }
1408
1409 pub async fn get_user_identity(
1445 &self,
1446 user_id: &UserId,
1447 ) -> Result<Option<UserIdentity>, CryptoStoreError> {
1448 let olm = self.client.olm_machine().await;
1449 let Some(olm) = olm.as_ref() else { return Ok(None) };
1450 let identity = olm.get_identity(user_id, None).await?;
1451
1452 Ok(identity.map(|i| UserIdentity::new(self.client.clone(), i)))
1453 }
1454
1455 pub async fn request_user_identity(&self, user_id: &UserId) -> Result<Option<UserIdentity>> {
1493 let olm = self.client.olm_machine().await;
1494 let Some(olm) = olm.as_ref() else { return Ok(None) };
1495
1496 let (request_id, request) = olm.query_keys_for_users(iter::once(user_id));
1497 self.client.keys_query(&request_id, request.device_keys).await?;
1498
1499 let identity = olm.get_identity(user_id, None).await?;
1500 Ok(identity.map(|i| UserIdentity::new(self.client.clone(), i)))
1501 }
1502
1503 pub async fn devices_stream(&self) -> Result<impl Stream<Item = DeviceUpdates> + use<>> {
1535 let olm = self.client.olm_machine().await;
1536 let olm = olm.as_ref().ok_or(Error::NoOlmMachine)?;
1537 let client = self.client.to_owned();
1538
1539 Ok(olm
1540 .store()
1541 .devices_stream()
1542 .map(move |updates| DeviceUpdates::new(client.to_owned(), updates)))
1543 }
1544
1545 pub async fn user_identities_stream(
1574 &self,
1575 ) -> Result<impl Stream<Item = IdentityUpdates> + use<>> {
1576 let olm = self.client.olm_machine().await;
1577 let olm = olm.as_ref().ok_or(Error::NoOlmMachine)?;
1578 let client = self.client.to_owned();
1579
1580 Ok(olm
1581 .store()
1582 .user_identities_stream()
1583 .map(move |updates| IdentityUpdates::new(client.to_owned(), updates)))
1584 }
1585
1586 pub async fn bootstrap_cross_signing(&self, auth_data: Option<AuthData>) -> Result<()> {
1630 let olm = self.client.olm_machine().await;
1631 let olm = olm.as_ref().ok_or(Error::NoOlmMachine)?;
1632
1633 let CrossSigningBootstrapRequests {
1634 upload_signing_keys_req,
1635 upload_keys_req,
1636 upload_signatures_req,
1637 } = olm.bootstrap_cross_signing(false).await?;
1638
1639 let mut upload_signing_keys_req: upload_signing_keys::v3::Request =
1640 upload_signing_keys_req.into();
1641 upload_signing_keys_req.auth = auth_data;
1642
1643 if let Some(req) = upload_keys_req {
1644 self.client.send_outgoing_request(req).await?;
1645 }
1646 self.client.send::<upload_signing_keys::v3::Request>(upload_signing_keys_req).await?;
1647 self.client.send(upload_signatures_req).await?;
1648 self.query_own_keys(olm).await;
1649
1650 Ok(())
1651 }
1652
1653 pub async fn reset_cross_signing(&self) -> Result<Option<CrossSigningResetHandle>> {
1687 let olm = self.client.olm_machine().await;
1688 let olm = olm.as_ref().ok_or(Error::NoOlmMachine)?;
1689
1690 let handle = olm.reset_cross_signing().await?;
1691
1692 if let Err(error) = self
1696 .client
1697 .send::<upload_signing_keys::v3::Request>(handle.upload_signing_keys_req().into())
1698 .await
1699 {
1700 if let Ok(Some(auth_type)) = CrossSigningResetAuthType::new(&error) {
1701 let client = self.client.clone();
1702
1703 Ok(Some(CrossSigningResetHandle::new(client, handle, auth_type)))
1704 } else {
1705 Err(error.into())
1706 }
1707 } else {
1708 let upload_signatures_req = handle.commit().await?;
1713 self.client.send(upload_signatures_req).await?;
1714
1715 if let Some((_, request)) = olm.upload_device_keys().await? {
1716 self.client.send_outgoing_request(request.into()).await?;
1717 }
1718 self.query_own_keys(olm).await;
1719
1720 Ok(None)
1721 }
1722 }
1723
1724 async fn query_own_keys(&self, olm: &OlmMachine) {
1730 let (request_id, request) = olm.query_keys_for_users([olm.user_id()]);
1731 if let Err(error) = self.client.keys_query(&request_id, request.device_keys).await {
1732 warn!(
1733 "Couldn't query our own keys after uploading cross-signing signatures: {error:?}"
1734 );
1735 }
1736 }
1737
1738 async fn ensure_initial_key_query(&self) -> Result<()> {
1741 let olm_machine = self.client.olm_machine().await;
1742 let olm_machine = olm_machine.as_ref().ok_or(Error::NoOlmMachine)?;
1743
1744 let user_id = olm_machine.user_id();
1745
1746 if self.client.encryption().get_user_identity(user_id).await?.is_none() {
1747 let (request_id, request) = olm_machine.query_keys_for_users([olm_machine.user_id()]);
1748 self.client.keys_query(&request_id, request.device_keys).await?;
1749 }
1750
1751 Ok(())
1752 }
1753
1754 pub async fn bootstrap_cross_signing_if_needed(
1803 &self,
1804 auth_data: Option<AuthData>,
1805 ) -> Result<()> {
1806 let olm_machine = self.client.olm_machine().await;
1807 let olm_machine = olm_machine.as_ref().ok_or(Error::NoOlmMachine)?;
1808 let user_id = olm_machine.user_id();
1809
1810 self.ensure_initial_key_query().await?;
1811
1812 if self.client.encryption().get_user_identity(user_id).await?.is_none() {
1813 self.bootstrap_cross_signing(auth_data).await?;
1814 }
1815
1816 Ok(())
1817 }
1818
1819 #[cfg(not(target_family = "wasm"))]
1870 pub async fn export_room_keys(
1871 &self,
1872 path: PathBuf,
1873 passphrase: &str,
1874 predicate: impl FnMut(&matrix_sdk_base::crypto::olm::InboundGroupSession) -> bool,
1875 ) -> Result<()> {
1876 let olm = self.client.olm_machine().await;
1877 let olm = olm.as_ref().ok_or(Error::NoOlmMachine)?;
1878
1879 let keys = olm.store().export_room_keys(predicate).await?;
1880 let passphrase = zeroize::Zeroizing::new(passphrase.to_owned());
1881
1882 let encrypt = move || -> Result<()> {
1883 let export: String =
1884 matrix_sdk_base::crypto::encrypt_room_key_export(&keys, &passphrase, 500_000)?;
1885 let mut file = std::fs::File::create(path)?;
1886 file.write_all(&export.into_bytes())?;
1887 Ok(())
1888 };
1889
1890 let task = tokio::task::spawn_blocking(encrypt);
1891 task.await.expect("Task join error")
1892 }
1893
1894 #[cfg(not(target_family = "wasm"))]
1931 pub async fn import_room_keys(
1932 &self,
1933 path: PathBuf,
1934 passphrase: &str,
1935 ) -> Result<RoomKeyImportResult, RoomKeyImportError> {
1936 let olm = self.client.olm_machine().await;
1937 let olm = olm.as_ref().ok_or(RoomKeyImportError::StoreClosed)?;
1938 let passphrase = zeroize::Zeroizing::new(passphrase.to_owned());
1939
1940 let decrypt = move || {
1941 let file = std::fs::File::open(path)?;
1942 matrix_sdk_base::crypto::decrypt_room_key_export(file, &passphrase)
1943 };
1944
1945 let task = tokio::task::spawn_blocking(decrypt);
1946 let import = task.await.expect("Task join error")?;
1947
1948 let ret = olm.store().import_exported_room_keys(import, |_, _| {}).await?;
1949
1950 self.backups().maybe_trigger_backup();
1951
1952 Ok(ret)
1953 }
1954
1955 pub async fn room_keys_received_stream(
1986 &self,
1987 ) -> Option<impl Stream<Item = Result<Vec<RoomKeyInfo>, BroadcastStreamRecvError>> + use<>>
1988 {
1989 let olm = self.client.olm_machine().await;
1990 let olm = olm.as_ref()?;
1991
1992 Some(olm.store().room_keys_received_stream())
1993 }
1994
1995 pub async fn historic_room_key_stream(
2027 &self,
2028 ) -> Option<impl Stream<Item = RoomKeyBundleInfo> + use<>> {
2029 let olm = self.client.olm_machine().await;
2030 let olm = olm.as_ref()?;
2031
2032 Some(olm.store().historic_room_key_stream())
2033 }
2034
2035 pub fn secret_storage(&self) -> SecretStorage {
2037 SecretStorage { client: self.client.to_owned() }
2038 }
2039
2040 pub fn backups(&self) -> Backups {
2042 Backups { client: self.client.to_owned() }
2043 }
2044
2045 pub fn recovery(&self) -> Recovery {
2047 Recovery { client: self.client.to_owned() }
2048 }
2049
2050 pub fn dehydrated_devices(&self) -> dehydrated_devices::DehydratedDevices {
2057 dehydrated_devices::DehydratedDevices { client: self.client.to_owned() }
2058 }
2059
2060 pub async fn enable_cross_process_store_lock(&self, lock_value: String) -> Result<(), Error> {
2071 if let Some(prev_lock) = self.client.locks().cross_process_crypto_store_lock.get() {
2073 let prev_holder = prev_lock.lock_holder();
2074 if prev_holder.is_some() && prev_holder.unwrap() == lock_value {
2075 return Ok(());
2076 }
2077 warn!(
2078 "Recreating cross-process store lock with a different holder value: \
2079 prev was {prev_holder:?}, new is {lock_value}"
2080 );
2081 }
2082
2083 let olm_machine = self.client.base_client().olm_machine().await;
2084 let olm_machine = olm_machine.as_ref().ok_or(Error::NoOlmMachine)?;
2085
2086 let lock = olm_machine.store().create_store_lock(
2087 "cross_process_lock".to_owned(),
2088 CrossProcessLockConfig::multi_process(lock_value.to_owned()),
2089 );
2090
2091 {
2097 let lock_result = lock.try_lock_once().await?;
2098
2099 if lock_result.is_ok() {
2100 olm_machine
2101 .initialize_crypto_store_generation(
2102 &self.client.locks().crypto_store_generation,
2103 )
2104 .await?;
2105 }
2106 }
2107
2108 self.client
2109 .locks()
2110 .cross_process_crypto_store_lock
2111 .set(lock)
2112 .map_err(|_| Error::BadCryptoStoreState)?;
2113
2114 Ok(())
2115 }
2116
2117 #[instrument(skip(self), fields(olm_machine_new_generation, olm_machine_generation))]
2122 async fn on_lock_newly_acquired(&self) -> Result<u64, Error> {
2123 let olm_machine_guard = self.client.olm_machine().await;
2124 if let Some(olm_machine) = olm_machine_guard.as_ref() {
2125 let (new_gen, generation_number) = olm_machine
2126 .maintain_crypto_store_generation(&self.client.locks().crypto_store_generation)
2127 .await?;
2128
2129 Span::current()
2130 .record("olm_machine_new_generation", new_gen)
2131 .record("olm_machine_generation", generation_number);
2132 debug!("OlmMachine generation maintained in CryptoStore");
2133
2134 if new_gen {
2136 drop(olm_machine_guard);
2138 self.client.base_client().regenerate_olm(None).await?;
2140 }
2141 Ok(generation_number)
2142 } else {
2143 warn!("Encryption::on_lock_newly_acquired: called before OlmMachine initialised");
2148 Ok(0)
2149 }
2150 }
2151
2152 pub async fn spin_lock_store(
2160 &self,
2161 max_backoff: Option<u32>,
2162 ) -> Result<Option<CrossProcessLockGuard>, Error> {
2163 self.lock_store(async move |lock| lock.spin_lock(max_backoff).await).await
2164 }
2165
2166 pub async fn try_lock_store_once(&self) -> Result<Option<CrossProcessLockGuard>, Error> {
2174 match self.lock_store(CrossProcessLock::try_lock_once).await {
2175 Err(Error::CrossProcessLockError(e))
2176 if matches!(*e, CrossProcessLockError::Unobtained(_)) =>
2177 {
2178 Ok(None)
2179 }
2180 other => other,
2181 }
2182 }
2183
2184 pub async fn lock_store<F: AcquireCrossProcessLockFn<LockableCryptoStore>>(
2191 &self,
2192 acquire: F,
2193 ) -> Result<Option<CrossProcessLockGuard>, Error> {
2194 let wrap_err = |e: CryptoStoreError| {
2195 Error::CrossProcessLockError(Box::new(CrossProcessLockError::TryLock(Arc::new(e))))
2196 };
2197 if let Some(lock) = self.client.locks().cross_process_crypto_store_lock.get() {
2198 let guard = acquire(lock).await.map_err(wrap_err)??;
2199 let _ = self.on_lock_newly_acquired().await?;
2200 Ok(Some(guard.into_guard()))
2201 } else {
2202 Ok(None)
2203 }
2204 }
2205
2206 #[cfg(any(test, feature = "testing"))]
2208 pub async fn uploaded_key_count(&self) -> Result<u64> {
2209 let olm_machine = self.client.olm_machine().await;
2210 let olm_machine = olm_machine.as_ref().ok_or(Error::AuthenticationRequired)?;
2211 Ok(olm_machine.uploaded_key_count().await?)
2212 }
2213
2214 pub(crate) async fn spawn_initialization_task(&self, auth_data: Option<AuthData>) {
2239 let bundle_receiver_task = if self.client.inner.enable_share_history_on_invite {
2244 Some(BundleReceiverTask::new(&self.client).await)
2245 } else {
2246 None
2247 };
2248
2249 let mut tasks = self.client.inner.e2ee.tasks.lock();
2250
2251 let this = self.clone();
2252
2253 tasks.setup_e2ee = Some(spawn(
2254 async move {
2255 this.update_verification_state().await;
2258
2259 if this.settings().auto_enable_cross_signing
2260 && let Err(e) = this.bootstrap_cross_signing_if_needed(auth_data).await
2261 {
2262 error!("Couldn't bootstrap cross signing {e:?}");
2263 }
2264
2265 if let Err(e) = this.backups().setup_and_resume().await {
2266 error!("Couldn't setup and resume backups {e:?}");
2267 }
2268 if let Err(e) = this.recovery().setup().await {
2269 error!("Couldn't setup and resume recovery {e:?}");
2270 }
2271 }
2272 .instrument(Span::current()),
2273 ));
2274
2275 tasks.receive_historic_room_key_bundles = bundle_receiver_task;
2276
2277 self.setup_room_membership_session_discard_handler();
2278 }
2279
2280 pub async fn wait_for_e2ee_initialization_tasks(&self) {
2283 let task = self.client.inner.e2ee.tasks.lock().setup_e2ee.take();
2284
2285 if let Some(task) = task
2286 && let Err(err) = task.await
2287 {
2288 warn!("Error when initializing backups: {err}");
2289 }
2290 }
2291
2292 pub(crate) async fn ensure_device_keys_upload(&self) -> Result<()> {
2302 let olm = self.client.olm_machine().await;
2303 let olm = olm.as_ref().ok_or(Error::NoOlmMachine)?;
2304
2305 if let Some((request_id, request)) = olm.upload_device_keys().await? {
2306 self.client.keys_upload(&request_id, &request).await?;
2307
2308 let (request_id, request) = olm.query_keys_for_users([olm.user_id()]);
2309 self.client.keys_query(&request_id, request.device_keys).await?;
2310 }
2311
2312 Ok(())
2313 }
2314
2315 pub(crate) async fn update_state_after_keys_query(&self, response: &get_keys::v3::Response) {
2316 self.recovery().update_state_after_keys_query(response).await;
2317
2318 if let Some(user_id) = self.client.user_id() {
2320 let contains_own_device = response.device_keys.contains_key(user_id);
2321
2322 if contains_own_device {
2323 self.update_verification_state().await;
2324 }
2325 }
2326 }
2327
2328 async fn update_verification_state(&self) {
2329 match self.get_own_device().await {
2330 Ok(device) => {
2331 if let Some(device) = device {
2332 let is_verified = device.is_cross_signed_by_owner();
2333
2334 if is_verified {
2335 self.client.inner.verification_state.set(VerificationState::Verified);
2336 } else if matches!(self.get_user_identity(device.user_id()).await, Ok(None)) {
2337 self.client.inner.verification_state.set(VerificationState::Unknown);
2341 } else {
2342 self.client.inner.verification_state.set(VerificationState::Unverified);
2343 }
2344 } else {
2345 warn!("Couldn't find out own device in the store.");
2346 self.client.inner.verification_state.set(VerificationState::Unknown);
2347 }
2348 }
2349 Err(error) => {
2350 warn!("Failed retrieving own device: {error}");
2351 self.client.inner.verification_state.set(VerificationState::Unknown);
2352 }
2353 }
2354 }
2355
2356 fn setup_room_membership_session_discard_handler(&self) {
2376 let client = self.client.downgrade();
2377 self.client.add_event_handler(|ev: OriginalSyncRoomMemberEvent, room: Room| async move {
2378 let Some(client) = client.get() else {
2379 return;
2381 };
2382 let Some(user_id) = client.user_id() else {
2383 return;
2385 };
2386 let olm = client.olm_machine().await;
2387 let Some(olm) = olm.as_ref() else {
2388 warn!("Cannot discard session - Olm machine is not available");
2389 return;
2390 };
2391
2392 if matches!(
2393 ev.membership_change(),
2394 MembershipChange::Joined |
2395 MembershipChange::Invited |
2396 MembershipChange::KnockAccepted |
2397 MembershipChange::InvitationAccepted |
2398 MembershipChange::ProfileChanged { .. }
2399 ) || ev.state_key == user_id {
2400 return;
2402 }
2403
2404 debug!(room_id = ?room.room_id(), member_id = ?ev.state_key, "Discarding session as a user left the room");
2405
2406 if let Err(e) = olm.discard_room_key(room.room_id()).await {
2410 warn!(
2411 room_id = ?room.room_id(),
2412 "Error discarding room key after member leave: {e:?}"
2413 );
2414 }
2415 });
2416 }
2417
2418 #[cfg(feature = "experimental-send-custom-to-device")]
2428 pub async fn encrypt_and_send_raw_to_device(
2429 &self,
2430 recipient_devices: Vec<&Device>,
2431 event_type: &str,
2432 content: Raw<AnyToDeviceEventContent>,
2433 share_strategy: CollectStrategy,
2434 ) -> Result<Vec<(OwnedUserId, OwnedDeviceId)>> {
2435 let users = recipient_devices.iter().map(|device| device.user_id());
2436
2437 self.client.claim_one_time_keys(users).await?;
2441
2442 let olm = self.client.olm_machine().await;
2443 let olm = olm.as_ref().expect("Olm machine wasn't started");
2444
2445 let (requests, withhelds) = olm
2446 .encrypt_content_for_devices(
2447 recipient_devices.into_iter().map(|d| d.deref().clone()).collect(),
2448 event_type,
2449 &content
2450 .deserialize_as::<serde_json::Value>()
2451 .expect("Deserialize as Value will always work"),
2452 share_strategy,
2453 )
2454 .await?;
2455
2456 let mut failures: Vec<(OwnedUserId, OwnedDeviceId)> = Default::default();
2457
2458 withhelds.iter().for_each(|(d, _)| {
2460 failures.push((d.user_id().to_owned(), d.device_id().to_owned()));
2461 });
2462
2463 for request in requests {
2465 let ruma_request = RumaToDeviceRequest::new_raw(
2466 request.event_type.clone(),
2467 request.txn_id.clone(),
2468 request.messages.clone(),
2469 );
2470
2471 let send_result = self
2472 .client
2473 .send_inner(ruma_request, Some(RequestConfig::short_retry()), Default::default())
2474 .await;
2475
2476 if send_result.is_err() {
2479 for (user_id, device_map) in request.messages {
2481 for device_id in device_map.keys() {
2482 match device_id {
2483 DeviceIdOrAllDevices::DeviceId(device_id) => {
2484 failures.push((user_id.clone(), device_id.to_owned()));
2485 }
2486 DeviceIdOrAllDevices::AllDevices => {
2487 }
2489 }
2490 }
2491 }
2492 }
2493 }
2494
2495 Ok(failures)
2496 }
2497}
2498
2499#[cfg(all(test, not(target_family = "wasm")))]
2500mod tests {
2501 use std::{
2502 ops::Not,
2503 str::FromStr,
2504 sync::{
2505 Arc,
2506 atomic::{AtomicBool, Ordering},
2507 },
2508 };
2509
2510 use matrix_sdk_test::{
2511 DEFAULT_TEST_ROOM_ID, JoinedRoomBuilder, SyncResponseBuilder, async_test,
2512 event_factory::EventFactory,
2513 };
2514 use ruma::{
2515 event_id,
2516 events::{reaction::ReactionEventContent, relation::Annotation},
2517 user_id,
2518 };
2519 use serde_json::json;
2520 use wiremock::{
2521 Mock, MockServer, Request, ResponseTemplate,
2522 matchers::{header, method, path_regex},
2523 };
2524
2525 use crate::{
2526 Client, assert_next_matches_with_timeout,
2527 config::RequestConfig,
2528 encryption::{
2529 DuplicateOneTimeKeyErrorMessage, OAuthCrossSigningResetInfo, VerificationState,
2530 },
2531 test_utils::{
2532 client::mock_matrix_session, logged_in_client, no_retry_test_client, set_client_session,
2533 },
2534 };
2535
2536 #[async_test]
2537 async fn test_reaction_sending() {
2538 let server = MockServer::start().await;
2539 let client = logged_in_client(Some(server.uri())).await;
2540
2541 let event_id = event_id!("$2:example.org");
2542
2543 Mock::given(method("GET"))
2544 .and(path_regex(r"^/_matrix/client/r0/rooms/.*/state/m.*room.*encryption.?"))
2545 .and(header("authorization", "Bearer 1234"))
2546 .respond_with(
2547 ResponseTemplate::new(200)
2548 .set_body_json(EventFactory::new().room_encryption().into_content()),
2549 )
2550 .mount(&server)
2551 .await;
2552
2553 Mock::given(method("PUT"))
2554 .and(path_regex(r"^/_matrix/client/r0/rooms/.*/send/m\.reaction/.*".to_owned()))
2555 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2556 "event_id": event_id,
2557 })))
2558 .mount(&server)
2559 .await;
2560
2561 let f = EventFactory::new().sender(user_id!("@example:localhost"));
2562 let response = SyncResponseBuilder::default()
2563 .add_joined_room(
2564 JoinedRoomBuilder::default()
2565 .add_state_event(
2566 f.member(user_id!("@example:localhost")).display_name("example"),
2567 )
2568 .add_state_event(f.power_levels())
2569 .add_state_event(f.room_encryption()),
2570 )
2571 .build_sync_response();
2572
2573 client.base_client().receive_sync_response(response).await.unwrap();
2574
2575 let room = client.get_room(&DEFAULT_TEST_ROOM_ID).expect("Room should exist");
2576 assert!(
2577 room.latest_encryption_state().await.expect("Getting encryption state").is_encrypted()
2578 );
2579
2580 let event_id = event_id!("$1:example.org");
2581 let reaction = ReactionEventContent::new(Annotation::new(event_id.into(), "🐈".to_owned()));
2582 room.send(reaction).await.expect("Sending the reaction should not fail");
2583
2584 room.send_raw("m.reaction", json!({})).await.expect("Sending the reaction should not fail");
2585 }
2586
2587 #[cfg(feature = "sqlite")]
2588 #[async_test]
2589 async fn test_generation_counter_invalidates_olm_machine() {
2590 use matrix_sdk_base::store::RoomLoadSettings;
2593 let tmp_dir = tempfile::tempdir().unwrap();
2594 let sqlite_path = tmp_dir.path().join("generation_counter_sqlite.db");
2595 let session = mock_matrix_session();
2596
2597 let client1 = Client::builder()
2598 .homeserver_url("http://localhost:1234")
2599 .request_config(RequestConfig::new().disable_retry())
2600 .sqlite_store(&sqlite_path, None)
2601 .build()
2602 .await
2603 .unwrap();
2604 client1
2605 .matrix_auth()
2606 .restore_session(session.clone(), RoomLoadSettings::default())
2607 .await
2608 .unwrap();
2609
2610 let client2 = Client::builder()
2611 .homeserver_url("http://localhost:1234")
2612 .request_config(RequestConfig::new().disable_retry())
2613 .sqlite_store(sqlite_path, None)
2614 .build()
2615 .await
2616 .unwrap();
2617 client2.matrix_auth().restore_session(session, RoomLoadSettings::default()).await.unwrap();
2618
2619 let guard = client1.encryption().try_lock_store_once().await.unwrap();
2622 assert!(guard.is_none());
2623
2624 client1.encryption().enable_cross_process_store_lock("client1".to_owned()).await.unwrap();
2625 client2.encryption().enable_cross_process_store_lock("client2".to_owned()).await.unwrap();
2626
2627 let acquired1 = client1.encryption().spin_lock_store(None).await.unwrap();
2629 assert!(acquired1.is_some());
2630
2631 let initial_olm_machine =
2634 client1.olm_machine().await.clone().expect("must have an olm machine");
2635
2636 let decryption_key = matrix_sdk_base::crypto::store::types::BackupDecryptionKey::new();
2639 let backup_key = decryption_key.megolm_v1_public_key();
2640 backup_key.set_version("1".to_owned());
2641 initial_olm_machine
2642 .backup_machine()
2643 .save_decryption_key(Some(decryption_key.to_owned()), Some("1".to_owned()))
2644 .await
2645 .expect("Should save");
2646
2647 initial_olm_machine.backup_machine().enable_backup_v1(backup_key.clone()).await.unwrap();
2648
2649 assert!(client1.encryption().backups().are_enabled().await);
2650
2651 let acquired2 = client2.encryption().try_lock_store_once().await.unwrap();
2653 assert!(acquired2.is_none());
2654
2655 drop(acquired1);
2657
2658 let acquired1 = client1.encryption().spin_lock_store(None).await.unwrap();
2660 assert!(acquired1.is_some());
2661
2662 let olm_machine = client1.olm_machine().await.clone().expect("must have an olm machine");
2664 assert!(initial_olm_machine.same_as(&olm_machine));
2665
2666 drop(acquired1);
2668
2669 let acquired2 = client2.encryption().spin_lock_store(None).await.unwrap();
2671 assert!(acquired2.is_some());
2672
2673 drop(acquired2);
2675
2676 let acquired1 = client1.encryption().spin_lock_store(None).await.unwrap();
2678 assert!(acquired1.is_some());
2679
2680 let olm_machine = client1.olm_machine().await.clone().expect("must have an olm machine");
2682
2683 assert!(!initial_olm_machine.same_as(&olm_machine));
2684
2685 let backup_key_new = olm_machine.backup_machine().get_backup_keys().await.unwrap();
2686 assert!(backup_key_new.decryption_key.is_some());
2687 assert_eq!(
2688 backup_key_new.decryption_key.unwrap().megolm_v1_public_key().to_base64(),
2689 backup_key.to_base64()
2690 );
2691 assert!(client1.encryption().backups().are_enabled().await);
2692 }
2693
2694 #[cfg(feature = "sqlite")]
2695 #[async_test]
2696 async fn test_generation_counter_no_spurious_invalidation() {
2697 use matrix_sdk_base::store::RoomLoadSettings;
2700 let tmp_dir = tempfile::tempdir().unwrap();
2701 let sqlite_path = tmp_dir.path().join("generation_counter_no_spurious_invalidations.db");
2702 let session = mock_matrix_session();
2703
2704 let client = Client::builder()
2705 .homeserver_url("http://localhost:1234")
2706 .request_config(RequestConfig::new().disable_retry())
2707 .sqlite_store(&sqlite_path, None)
2708 .build()
2709 .await
2710 .unwrap();
2711 client
2712 .matrix_auth()
2713 .restore_session(session.clone(), RoomLoadSettings::default())
2714 .await
2715 .unwrap();
2716
2717 let initial_olm_machine = client.olm_machine().await.as_ref().unwrap().clone();
2718
2719 client.encryption().enable_cross_process_store_lock("client1".to_owned()).await.unwrap();
2720
2721 let after_enabling_lock = client.olm_machine().await.as_ref().unwrap().clone();
2723 assert!(initial_olm_machine.same_as(&after_enabling_lock));
2724
2725 {
2726 let client2 = Client::builder()
2728 .homeserver_url("http://localhost:1234")
2729 .request_config(RequestConfig::new().disable_retry())
2730 .sqlite_store(sqlite_path, None)
2731 .build()
2732 .await
2733 .unwrap();
2734 client2
2735 .matrix_auth()
2736 .restore_session(session, RoomLoadSettings::default())
2737 .await
2738 .unwrap();
2739
2740 client2
2741 .encryption()
2742 .enable_cross_process_store_lock("client2".to_owned())
2743 .await
2744 .unwrap();
2745
2746 let guard = client2.encryption().spin_lock_store(None).await.unwrap();
2747 assert!(guard.is_some());
2748
2749 drop(guard);
2750 }
2751
2752 {
2753 let acquired = client.encryption().spin_lock_store(None).await.unwrap();
2754 assert!(acquired.is_some());
2755 }
2756
2757 let after_taking_lock_first_time = client.olm_machine().await.as_ref().unwrap().clone();
2759 assert!(!initial_olm_machine.same_as(&after_taking_lock_first_time));
2760
2761 {
2762 let acquired = client.encryption().spin_lock_store(None).await.unwrap();
2763 assert!(acquired.is_some());
2764 }
2765
2766 let after_taking_lock_second_time = client.olm_machine().await.as_ref().unwrap().clone();
2768 assert!(after_taking_lock_first_time.same_as(&after_taking_lock_second_time));
2769 }
2770
2771 #[async_test]
2772 async fn test_update_verification_state_is_updated_before_any_requests_happen() {
2773 let client = no_retry_test_client(None).await;
2775 let server = MockServer::start().await;
2776
2777 let mut verification_state = client.encryption().verification_state();
2779
2780 assert_next_matches_with_timeout!(verification_state, VerificationState::Unknown);
2782
2783 let keys_requested = Arc::new(AtomicBool::new(false));
2786 let inner_bool = keys_requested.clone();
2787
2788 Mock::given(method("GET"))
2789 .and(path_regex(
2790 r"/_matrix/client/r0/user/.*/account_data/m.secret_storage.default_key",
2791 ))
2792 .respond_with(move |_req: &Request| {
2793 inner_bool.fetch_or(true, Ordering::SeqCst);
2794 ResponseTemplate::new(200).set_body_json(json!({}))
2795 })
2796 .mount(&server)
2797 .await;
2798
2799 set_client_session(&client).await;
2801
2802 assert!(keys_requested.load(Ordering::SeqCst).not());
2805 assert_next_matches_with_timeout!(verification_state, VerificationState::Unknown);
2806 }
2807
2808 #[test]
2809 fn test_oauth_reset_info_from_uiaa_info() {
2810 let auth_info = json!({
2811 "session": "dummy",
2812 "flows": [
2813 {
2814 "stages": [
2815 "org.matrix.cross_signing_reset"
2816 ]
2817 }
2818 ],
2819 "params": {
2820 "org.matrix.cross_signing_reset": {
2821 "url": "https://example.org/account/account?action=org.matrix.cross_signing_reset"
2822 }
2823 },
2824 "msg": "To reset..."
2825 });
2826
2827 let auth_info = serde_json::from_value(auth_info)
2828 .expect("We should be able to deserialize the UiaaInfo");
2829 OAuthCrossSigningResetInfo::from_auth_info(&auth_info)
2830 .expect("We should be able to fetch the cross-signing reset info from the auth info");
2831 }
2832
2833 #[test]
2834 fn test_duplicate_one_time_key_error_parsing() {
2835 let message = concat!(
2836 r#"One time key signed_curve25519:AAAAAAAAAAA already exists. "#,
2837 r#"Old key: {"key":"dBcZBzQaiQYWf6rBPh2QypIOB/dxSoTeyaFaxNNbeHs","#,
2838 r#""signatures":{"@example:matrix.org":{"ed25519:AAAAAAAAAA":""#,
2839 r#"Fk45zHAbrd+1j9wZXLjL2Y/+DU/Mnz9yuvlfYBOOT7qExN2Jdud+5BAuNs8nZ/caS4wTF39Kg3zQpzaGERoCBg"}}};"#,
2840 r#" new key: {'key': 'CY0TWVK1/Kj3ZADuBcGe3UKvpT+IKAPMUsMeJhSDqno', "#,
2841 r#"'signatures': {'@example:matrix.org': {'ed25519:AAAAAAAAAA': "#,
2842 r#"'BQ9Gp0p+6srF+c8OyruqKKd9R4yaub3THYAyyBB/7X/rG8BwcAqFynzl1aGyFYun4Q+087a5OSiglCXI+/kQAA'}}}"#
2843 );
2844 let message = DuplicateOneTimeKeyErrorMessage::from_str(message)
2845 .expect("We should be able to parse the error message");
2846
2847 assert_eq!(message.old_key.to_base64(), "dBcZBzQaiQYWf6rBPh2QypIOB/dxSoTeyaFaxNNbeHs");
2848 assert_eq!(message.new_key.to_base64(), "CY0TWVK1/Kj3ZADuBcGe3UKvpT+IKAPMUsMeJhSDqno");
2849
2850 DuplicateOneTimeKeyErrorMessage::from_str("One time key already exists.")
2851 .expect_err("We shouldn't be able to parse an incomplete error message");
2852 }
2853
2854 fn devices_to_verify_against_keys_query_response(
2858 devices: Vec<serde_json::Value>,
2859 ) -> serde_json::Value {
2860 let device_keys: serde_json::Map<String, serde_json::Value> = devices
2861 .into_iter()
2862 .map(|device| (device.get("device_id").unwrap().as_str().unwrap().to_owned(), device))
2863 .collect();
2864 json!({
2865 "device_keys": {
2866 "@example:localhost": device_keys,
2867 },
2868 "master_keys": {
2869 "@example:localhost": {
2870 "keys": {
2871 "ed25519:PJklDgml7Xtt1Wr8jsWvB+lC5YD/bVDpHL+fYuItNxU": "PJklDgml7Xtt1Wr8jsWvB+lC5YD/bVDpHL+fYuItNxU",
2872 },
2873 "usage": ["master"],
2874 "user_id": "@example:localhost",
2875 },
2876 },
2877 "self_signing_keys": {
2878 "@example:localhost": {
2879 "keys": {
2880 "ed25519:jobZVcxG+PBLwZMsF4XEJSJTVqOgDxd0Ud3J/bw3HYM": "jobZVcxG+PBLwZMsF4XEJSJTVqOgDxd0Ud3J/bw3HYM",
2881 },
2882 "usage": ["self_signing"],
2883 "user_id": "@example:localhost",
2884 "signatures": {
2885 "@example:localhost": {
2886 "ed25519:PJklDgml7Xtt1Wr8jsWvB+lC5YD/bVDpHL+fYuItNxU": "etO1bB+rCk+TQ/FcjQ8eWu/RsRNQNNQ1Ek+PD6//j8yz6igRjfvuHZaMvr/quAFrirfgExph2TdOwlDgN5bFCQ",
2887 },
2888 },
2889 },
2890 },
2891 "user_signing_keys": {
2892 "@example:localhost": {
2893 "keys": {
2894 "ed25519:CBaovtekFxzf2Ijjhk4B49drOH0/qmhBbptFlVW7HC0": "CBaovtekFxzf2Ijjhk4B49drOH0/qmhBbptFlVW7HC0",
2895 },
2896 "usage": ["user_signing"],
2897 "user_id": "@example:localhost",
2898 "signatures": {
2899 "@example:localhost": {
2900 "ed25519:PJklDgml7Xtt1Wr8jsWvB+lC5YD/bVDpHL+fYuItNxU": "E/DFi/hQTIb/7eSB+HbCXeTLFaLjqWHzLO9GwjL1qdhfO7ew4p6YdtXSH3T2YYr1dKCPteH/4nMYVwOhww2CBg",
2901 },
2902 },
2903 },
2904 }
2905 })
2906 }
2907
2908 #[async_test]
2911 async fn test_devices_to_verify_against_no_devices() {
2914 let server = MockServer::start().await;
2915 let client = logged_in_client(Some(server.uri())).await;
2916
2917 Mock::given(method("POST"))
2918 .and(path_regex(r"^/_matrix/client/r0/keys/query".to_owned()))
2919 .respond_with(
2920 ResponseTemplate::new(200)
2921 .set_body_json(devices_to_verify_against_keys_query_response(vec![])),
2922 )
2923 .mount(&server)
2924 .await;
2925
2926 assert!(!client.encryption().has_devices_to_verify_against().await.unwrap());
2927 }
2928
2929 #[async_test]
2930 async fn test_devices_to_verify_against_cross_signed() {
2933 let server = MockServer::start().await;
2934 let client = logged_in_client(Some(server.uri())).await;
2935
2936 Mock::given(method("POST"))
2937 .and(path_regex(r"^/_matrix/client/r0/keys/query".to_owned()))
2938 .respond_with(ResponseTemplate::new(200).set_body_json(
2939 devices_to_verify_against_keys_query_response(vec![
2940 json!({
2941 "algorithms": [
2942 "m.olm.v1.curve25519-aes-sha2",
2943 "m.megolm.v1.aes-sha2",
2944 ],
2945 "user_id": "@example:localhost",
2946 "device_id": "SIGNEDDEVICE",
2947 "keys": {
2948 "curve25519:SIGNEDDEVICE": "o1LqUtH/sqd3WF+BB2Qr77uw3sDmZhMOz68/IV9aHxs",
2949 "ed25519:SIGNEDDEVICE": "iVoEfMOoUqxXVMLdpZCOgvQuCrT3/kQWkBmB3Phi/lo",
2950 },
2951 "signatures": {
2952 "@example:localhost": {
2953 "ed25519:SIGNEDDEVICE": "C7yRu1fNrdD2EobVdtANMqk3LBtWtTRWrIU22xVS8/Om1kmA/luzek64R3N6JsZhYczVmZYBKhUC9kRvHHwOBg",
2954 "ed25519:jobZVcxG+PBLwZMsF4XEJSJTVqOgDxd0Ud3J/bw3HYM": "frfh2HP28GclmGvwTic00Fj4nZCvm4RlRA6U56mnD5920hOi04+L055ojzp6ybZXvC/GQYfyTHwQXlUN1nvxBA",
2955 },
2956 },
2957 })
2958 ])
2959 ))
2960 .mount(&server)
2961 .await;
2962
2963 assert!(client.encryption().has_devices_to_verify_against().await.unwrap());
2964 }
2965
2966 #[async_test]
2967 async fn test_devices_to_verify_against_dehydrated_and_unsigned() {
2970 let server = MockServer::start().await;
2971 let client = logged_in_client(Some(server.uri())).await;
2972 let user_id = client.user_id().unwrap();
2973 let olm_machine = client.olm_machine().await;
2974 let olm_machine = olm_machine.as_ref().unwrap();
2975
2976 Mock::given(method("POST"))
2977 .and(path_regex(r"^/_matrix/client/r0/keys/query".to_owned()))
2978 .respond_with(ResponseTemplate::new(200).set_body_json(
2979 devices_to_verify_against_keys_query_response(vec![
2980 json!({
2981 "algorithms": [
2982 "m.olm.v1.curve25519-aes-sha2",
2983 "m.megolm.v1.aes-sha2",
2984 ],
2985 "user_id": "@example:localhost",
2986 "device_id": "DEHYDRATEDDEVICE",
2987 "keys": {
2988 "curve25519:DEHYDRATEDDEVICE": "XOn5VguAgokZ3p9mBz2yOB395fn6j75G8jIPcXEWQGY",
2989 "ed25519:DEHYDRATEDDEVICE": "4GG5xmBT7z4rgUgmWNlKZ+ABE3QlGgTorF+luCnKfYI",
2990 },
2991 "dehydrated": true,
2992 "signatures": {
2993 "@example:localhost": {
2994 "ed25519:DEHYDRATEDDEVICE": "+OMasB7nzVlMV+zRDxkh4h8h/Q0bY42P1SPv7X2IURIelT5G+d+AYSmg30N4maphxEDBqt/vI8/lIr71exc3Dg",
2995 "ed25519:jobZVcxG+PBLwZMsF4XEJSJTVqOgDxd0Ud3J/bw3HYM": "8DzynAgbYgXX1Md5d4Vw91Zstpoi4dpG7levFeVhi4psCAWuBnV76Qu1s2TGjQQ0CLDXEqcxxuX9X4eUK5TGCg",
2996 },
2997 },
2998 }),
2999 json!({
3000 "algorithms": [
3001 "m.olm.v1.curve25519-aes-sha2",
3002 "m.megolm.v1.aes-sha2",
3003 ],
3004 "user_id": "@example:localhost",
3005 "device_id": "UNSIGNEDDEVICE",
3006 "keys": {
3007 "curve25519:UNSIGNEDDEVICE": "mMby6NpprkHxj+ONfO9Z5lBqVUHJBMkrPFSNJhogBkg",
3008 "ed25519:UNSIGNEDDEVICE": "Zifq39ZDrlIaSRf0Hh22owEqXCPE+1JSSgs6LDlubwQ",
3009 },
3010 "signatures": {
3011 "@example:localhost": {
3012 "ed25519:UNSIGNEDDEVICE": "+L29RoDKoTufPGm/Bae65KHno7Z1H7GYhxSKpB4RQZRS7NrR29AMW1PVhEsIozYuDVEFuMZ0L8H3dlcaHxagBA",
3013 },
3014 },
3015 }),
3016 ])
3017 ))
3018 .mount(&server)
3019 .await;
3020
3021 let (request_id, request) = olm_machine.query_keys_for_users([user_id]);
3022 client.keys_query(&request_id, request.device_keys).await.unwrap();
3023
3024 assert!(!client.encryption().has_devices_to_verify_against().await.unwrap());
3025 }
3026
3027 #[cfg(feature = "experimental-send-custom-to-device")]
3028 mod resolve_recipient_devices {
3029 use matrix_sdk_test::async_test;
3030 use ruma::{
3031 OwnedDeviceId, device_id, owned_device_id, to_device::DeviceIdOrAllDevices, user_id,
3032 };
3033
3034 use super::super::Device;
3035 use crate::{Client, test_utils::mocks::MatrixMockServer};
3036
3037 const BOB_FIRST_DEVICE: &str = "B0B0B0B0B";
3038 const BOB_SECOND_DEVICE: &str = "B0B2B0B2";
3039 const BOB_THIRD_DEVICE: &str = "B0B3B0B3";
3040
3041 async fn alice_and_bob_with_two_bob_devices() -> (MatrixMockServer, Client, Client) {
3047 let server = MatrixMockServer::new().await;
3048 server.mock_crypto_endpoints_preset().await;
3049
3050 let (alice, bob) = server.set_up_alice_and_bob_for_encryption().await;
3051 assert_eq!(bob.device_id().unwrap(), device_id!(BOB_FIRST_DEVICE));
3052
3053 server
3054 .set_up_new_device_for_encryption(&bob, device_id!(BOB_SECOND_DEVICE), vec![&alice])
3055 .await;
3056
3057 server
3059 .mock_sync()
3060 .ok_and_run(&alice, |builder| {
3061 builder.add_change_device(bob.user_id().unwrap());
3062 })
3063 .await;
3064
3065 (server, alice, bob)
3066 }
3067
3068 fn device_ids(devices: Vec<Device>) -> Vec<OwnedDeviceId> {
3071 let mut device_ids: Vec<_> =
3072 devices.into_iter().map(|d| d.device_id().to_owned()).collect();
3073 device_ids.sort();
3074 device_ids
3075 }
3076
3077 #[async_test]
3078 async fn test_all_devices_resolves_to_every_known_device() {
3079 let (_server, alice, bob) = alice_and_bob_with_two_bob_devices().await;
3080
3081 let (devices, unknown_devices) = alice
3082 .resolve_recipient_devices(
3083 bob.user_id().unwrap(),
3084 vec![DeviceIdOrAllDevices::AllDevices],
3085 )
3086 .await
3087 .unwrap();
3088
3089 assert_eq!(
3090 device_ids(devices),
3091 vec![owned_device_id!(BOB_FIRST_DEVICE), owned_device_id!(BOB_SECOND_DEVICE)]
3092 );
3093 assert!(unknown_devices.is_empty(), "`AllDevices` can't reference an unknown device");
3094 }
3095
3096 #[async_test]
3097 async fn test_explicit_device_ids_are_filtered_to_the_requested_ones() {
3098 let (_server, alice, bob) = alice_and_bob_with_two_bob_devices().await;
3099
3100 let (devices, unknown_devices) = alice
3101 .resolve_recipient_devices(
3102 bob.user_id().unwrap(),
3103 vec![DeviceIdOrAllDevices::DeviceId(owned_device_id!(BOB_SECOND_DEVICE))],
3104 )
3105 .await
3106 .unwrap();
3107
3108 assert_eq!(device_ids(devices), vec![owned_device_id!(BOB_SECOND_DEVICE)]);
3109 assert!(unknown_devices.is_empty());
3110 }
3111
3112 #[async_test]
3114 async fn test_several_explicit_device_ids_are_all_resolved() {
3115 let (server, alice, bob) = alice_and_bob_with_two_bob_devices().await;
3116
3117 server
3118 .set_up_new_device_for_encryption(&bob, device_id!(BOB_THIRD_DEVICE), vec![&alice])
3119 .await;
3120
3121 server
3123 .mock_sync()
3124 .ok_and_run(&alice, |builder| {
3125 builder.add_change_device(bob.user_id().unwrap());
3126 })
3127 .await;
3128
3129 let (devices, unknown_devices) = alice
3130 .resolve_recipient_devices(
3131 bob.user_id().unwrap(),
3132 vec![
3133 DeviceIdOrAllDevices::DeviceId(owned_device_id!(BOB_FIRST_DEVICE)),
3134 DeviceIdOrAllDevices::DeviceId(owned_device_id!(BOB_THIRD_DEVICE)),
3135 ],
3136 )
3137 .await
3138 .unwrap();
3139
3140 assert_eq!(
3141 device_ids(devices),
3142 vec![owned_device_id!(BOB_FIRST_DEVICE), owned_device_id!(BOB_THIRD_DEVICE)],
3143 "the second device was not requested and must be left out"
3144 );
3145 assert!(unknown_devices.is_empty());
3146 }
3147
3148 #[async_test]
3149 async fn test_unknown_device_is_reported_back() {
3150 let (_server, alice, bob) = alice_and_bob_with_two_bob_devices().await;
3151
3152 let (devices, unknown_devices) = alice
3153 .resolve_recipient_devices(
3154 bob.user_id().unwrap(),
3155 vec![DeviceIdOrAllDevices::DeviceId(owned_device_id!("UNKNOWNDEVICE"))],
3156 )
3157 .await
3158 .unwrap();
3159
3160 assert!(devices.is_empty());
3161 assert_eq!(unknown_devices, vec![owned_device_id!("UNKNOWNDEVICE")]);
3162 }
3163
3164 #[async_test]
3167 async fn test_known_and_unknown_devices_are_split() {
3168 let (_server, alice, bob) = alice_and_bob_with_two_bob_devices().await;
3169
3170 let (devices, unknown_devices) = alice
3171 .resolve_recipient_devices(
3172 bob.user_id().unwrap(),
3173 vec![
3174 DeviceIdOrAllDevices::DeviceId(owned_device_id!(BOB_FIRST_DEVICE)),
3175 DeviceIdOrAllDevices::DeviceId(owned_device_id!("UNKNOWNDEVICE")),
3176 ],
3177 )
3178 .await
3179 .unwrap();
3180
3181 assert_eq!(device_ids(devices), vec![owned_device_id!(BOB_FIRST_DEVICE)]);
3182 assert_eq!(unknown_devices, vec![owned_device_id!("UNKNOWNDEVICE")]);
3183 }
3184
3185 #[async_test]
3189 async fn test_all_devices_takes_precedence_over_explicit_device_ids() {
3190 let (_server, alice, bob) = alice_and_bob_with_two_bob_devices().await;
3191
3192 let (devices, unknown_devices) = alice
3193 .resolve_recipient_devices(
3194 bob.user_id().unwrap(),
3195 vec![
3196 DeviceIdOrAllDevices::AllDevices,
3197 DeviceIdOrAllDevices::DeviceId(owned_device_id!("UNKNOWNDEVICE")),
3198 ],
3199 )
3200 .await
3201 .unwrap();
3202
3203 assert_eq!(
3204 device_ids(devices),
3205 vec![owned_device_id!(BOB_FIRST_DEVICE), owned_device_id!(BOB_SECOND_DEVICE)]
3206 );
3207 assert!(unknown_devices.is_empty());
3208 }
3209
3210 #[async_test]
3213 async fn test_empty_recipient_list_resolves_to_no_device() {
3214 let (_server, alice, bob) = alice_and_bob_with_two_bob_devices().await;
3215
3216 let (devices, unknown_devices) =
3217 alice.resolve_recipient_devices(bob.user_id().unwrap(), vec![]).await.unwrap();
3218
3219 assert!(devices.is_empty());
3220 assert!(unknown_devices.is_empty());
3221 }
3222
3223 #[async_test]
3226 async fn test_unknown_user_has_no_device() {
3227 let (_server, alice, _bob) = alice_and_bob_with_two_bob_devices().await;
3228 let unknown_user_id = user_id!("@carol:example.org");
3229
3230 let (devices, unknown_devices) = alice
3231 .resolve_recipient_devices(
3232 unknown_user_id,
3233 vec![DeviceIdOrAllDevices::DeviceId(owned_device_id!(BOB_FIRST_DEVICE))],
3234 )
3235 .await
3236 .unwrap();
3237
3238 assert!(devices.is_empty());
3239 assert_eq!(unknown_devices, vec![owned_device_id!(BOB_FIRST_DEVICE)]);
3240
3241 let (devices, unknown_devices) = alice
3244 .resolve_recipient_devices(unknown_user_id, vec![DeviceIdOrAllDevices::AllDevices])
3245 .await
3246 .unwrap();
3247
3248 assert!(devices.is_empty());
3249 assert!(unknown_devices.is_empty());
3250 }
3251 }
3252}