Skip to main content

matrix_sdk/encryption/
mod.rs

1// Copyright 2021 The Matrix.org Foundation C.I.C.
2// Copyright 2021 Damir Jelić
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16#![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/// Error type describing failures that can happen while exporting a
141/// [`SecretsBundle`] from a SQLite store.
142#[cfg(feature = "sqlite")]
143#[derive(Debug, thiserror::Error)]
144pub enum BundleExportError {
145    /// The SQLite store couldn't be opened.
146    #[error(transparent)]
147    OpenStoreError(#[from] matrix_sdk_sqlite::OpenStoreError),
148    /// Data from the SQLite store couldn't be exported.
149    #[error(transparent)]
150    StoreError(#[from] CryptoStoreError),
151    /// The store doesn't contain a secrets bundle or it couldn't be read from
152    /// the store.
153    #[error(transparent)]
154    SecretExport(#[from] matrix_sdk_base::crypto::store::SecretsBundleExportError),
155}
156
157/// Error type describing failures that can happen while importing a
158/// [`SecretsBundle`].
159#[derive(Debug, thiserror::Error)]
160pub enum BundleImportError {
161    /// The bundle couldn't be imported.
162    #[error(transparent)]
163    SecretImport(#[from] SecretImportError),
164    /// The cross-signed device keys couldn't been uploaded.
165    #[error(transparent)]
166    DeviceKeys(#[from] Error),
167}
168
169/// Attempt to export a [`SecretsBundle`] from a crypto store.
170///
171/// This method can be used to retrieve a [`SecretsBundle`] from an existing
172/// `matrix-sdk`-based client in order to import the [`SecretsBundle`] in
173/// another [`Client`] instance.
174///
175/// This can be useful for migration purposes or to allow existing client
176/// instances create new ones that will be fully verified.
177#[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
203/// All the data related to the encryption state.
204pub(crate) struct EncryptionData {
205    /// Background tasks related to encryption (key backup, initialization
206    /// tasks, etc.).
207    pub tasks: StdMutex<ClientTasks>,
208
209    /// End-to-end encryption settings.
210    pub encryption_settings: EncryptionSettings,
211
212    /// All state related to key backup.
213    pub backup_state: BackupClientState,
214
215    /// All state related to secret storage recovery.
216    pub recovery_state: SharedObservable<RecoveryState>,
217
218    /// State for the dehydrated-devices manager (event channel, scheduled
219    /// rotation task).
220    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    /// Initialize the background task which listens for changes in the
249    /// [`backups::BackupState`] and updataes the [`recovery::RecoveryState`].
250    ///
251    /// This should happen after the usual tasks have been set up and after the
252    /// E2EE initialization tasks have been set up.
253    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/// Settings for end-to-end encryption features.
264#[derive(Clone, Copy, Debug, Default)]
265pub struct EncryptionSettings {
266    /// Automatically bootstrap cross-signing for a user once they're logged, in
267    /// case it's not already done yet.
268    ///
269    /// This requires to login with a username and password, or that MSC3967 is
270    /// enabled on the server, as of 2023-10-20.
271    pub auto_enable_cross_signing: bool,
272
273    /// Select a strategy to download room keys from the backup, by default room
274    /// keys won't be downloaded from the backup automatically.
275    ///
276    /// Take a look at the [`BackupDownloadStrategy`] enum for more options.
277    pub backup_download_strategy: BackupDownloadStrategy,
278
279    /// Automatically create a backup version if no backup exists.
280    pub auto_enable_backups: bool,
281}
282
283/// Settings for end-to-end encryption features.
284#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
285#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
286pub enum BackupDownloadStrategy {
287    /// Automatically download all room keys from the backup when the backup
288    /// recovery key has been received. The backup recovery key can be received
289    /// in two ways:
290    ///
291    /// 1. Received as a `m.secret.send` to-device event, after a successful
292    ///    interactive verification.
293    /// 2. Imported from secret storage (4S) using the
294    ///    [`SecretStore::import_secrets()`] method.
295    ///
296    /// [`SecretStore::import_secrets()`]: crate::encryption::secret_storage::SecretStore::import_secrets
297    OneShot,
298
299    /// Attempt to download a single room key if an event fails to be decrypted.
300    AfterDecryptionFailure,
301
302    /// Don't download any room keys automatically. The user can manually
303    /// download room keys using the [`Backups::download_room_key()`] methods.
304    ///
305    /// This is the default option.
306    #[default]
307    Manual,
308}
309
310/// The verification state of our own device
311///
312/// This enum tells us if our own user identity trusts these devices, in other
313/// words it tells us if the user identity has signed the device.
314#[derive(Clone, Copy, Debug, Eq, PartialEq)]
315pub enum VerificationState {
316    /// The verification state is unknown for now.
317    Unknown,
318    /// The device is considered to be verified, it has been signed by its user
319    /// identity.
320    Verified,
321    /// The device is unverified.
322    Unverified,
323}
324
325/// A stateful struct remembering the cross-signing keys we need to upload.
326///
327/// Since the `/_matrix/client/v3/keys/device_signing/upload` might require
328/// additional authentication, this struct will contain information on the type
329/// of authentication the user needs to complete before the upload might be
330/// continued.
331///
332/// Not to be confused with [`UncommittedCrossSigningReset`], the internal
333/// struct used by the [`OlmMachine`] to track the cross-signing reset process
334/// this struct is a wrapper around.
335///
336/// More info can be found in the [spec].
337///
338/// [spec]: https://spec.matrix.org/v1.11/client-server-api/#post_matrixclientv3keysdevice_signingupload
339#[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    /// Set up a new `CrossSigningResetHandle`.
349    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    /// Get the [`CrossSigningResetAuthType`] this cross-signing reset process
358    /// is using.
359    pub fn auth_type(&self) -> &CrossSigningResetAuthType {
360        &self.auth_type
361    }
362
363    /// Continue the cross-signing reset by either waiting for the
364    /// authentication to be done on the side of the OAuth 2.0 server or by
365    /// providing additional [`AuthData`] the homeserver requires.
366    ///
367    /// Returns `true` if this call completed the reset. Returns `false` if the
368    /// reset was cancelled or if a concurrent call completed it instead, in
369    /// which case no new identity was uploaded by this call.
370    pub async fn auth(&self, auth: AuthData) -> Result<bool> {
371        // Poll to see whether the reset has been authorized twice per second.
372        const RETRY_EVERY: Duration = Duration::from_millis(500);
373
374        // Give up after two minutes of polling.
375        const TIMEOUT: Duration = Duration::from_mins(2);
376
377        // If someone else has already completed the cross-signing reset before
378        // we've even started, then we have nothing to do.
379        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            // Make sure that we don't continue with the reset if someone else
386            // has already completed it.
387            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 the cross-signing reset has been cancelled or if
402                    // someone else has already completed
403                    // it, then we have nothing to do.
404                    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                            // Return the error except if we are at the
411                            // `m.oauth` stage where we want to keep polling.
412                            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        // We must not continue with the reset if the signing keys weren't
439        // uploaded, since would leave the client and the server in an
440        // inconsistent state.
441        if !signing_keys_uploaded {
442            return Ok(false);
443        }
444
445        // Make sure that we don't continue with the reset if someone else has
446        // already completed it.
447        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        // Upload the signatures before any device keys. A failed device keys
458        // upload is retried after the next sync, while a failed signatures
459        // upload would not be retried.
460        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        // Query our own device keys since we just updated them.
467        self.client.encryption().query_own_keys(olm).await;
468
469        // We've already replaced `guard` with `None` above, so we don't need to
470        // tidy that up now.
471
472        Ok(true)
473    }
474
475    /// Cancel the ongoing identity reset process
476    pub async fn cancel(&self) {
477        *self.is_cancelled.lock().await = true;
478    }
479}
480
481/// information about the additional authentication that is required before the
482/// cross-signing keys can be uploaded.
483#[derive(Debug, Clone)]
484pub enum CrossSigningResetAuthType {
485    /// The homeserver requires user-interactive authentication.
486    Uiaa(UiaaCrossSigningResetInfo),
487    /// OAuth 2.0 is used for authentication and the user needs to open a URL to
488    /// approve the upload of cross-signing keys.
489    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/// User-interactive authentication specific information about the required
509/// authentication for the upload of cross-signing keys.
510#[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    /// Session key to use to complete the authentication.
525    pub fn session(&self) -> &str {
526        self.auth_info.session.as_deref().expect("The session is checked in from_auth_info")
527    }
528
529    /// The full UIAA info, containing the flows the homeserver supports, their
530    /// parameters and the stages that were already completed.
531    pub fn auth_info(&self) -> &UiaaInfo {
532        &self.auth_info
533    }
534
535    /// Create `m.login.password` UIAA [`AuthData`] to continue this reset
536    /// session.
537    ///
538    /// Only use this if the homeserver offers the `m.login.password` stage,
539    /// see [`UiaaCrossSigningResetInfo::auth_info`] for the available flows.
540    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/// OAuth 2.0 specific information about the required authentication for the
548/// upload of cross-signing keys.
549#[derive(Debug, Clone, Deserialize)]
550pub struct OAuthCrossSigningResetInfo {
551    /// The URL where the user can approve the reset of the cross-signing keys.
552    pub approval_url: Url,
553
554    /// Session key to use to complete the authentication.
555    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    /// Create UIAA [`AuthData`] to continue this reset session.
575    pub fn as_auth_data(&self) -> AuthData {
576        AuthData::OAuth(assign!(OAuthData::new(), { session: Some(self.session.clone()) }))
577    }
578}
579
580/// A struct that helps to parse the custom error message Synapse posts if a
581/// duplicate one-time key is uploaded.
582#[derive(Clone, Debug)]
583pub struct DuplicateOneTimeKeyErrorMessage {
584    /// The previously uploaded one-time key.
585    pub old_key: Curve25519PublicKey,
586    /// The one-time key we're attempting to upload right now.
587    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        // First we split the string into two parts, the part containing the old
595        // key and the part containing the new key. The parts are conveniently
596        // separated by a `;` character.
597        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        // Now we remove the lengthy prefix from the part containing the old
607        // key, we should be left with just the JSON of the signed key.
608        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        // The part containing the new key is much simpler, we just remove a
618        // static prefix.
619        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        // The JSON containing the new key is for some reason quoted using
625        // single quotes, so let's replace them with normal double quotes.
626        let new_key = new_key.replace("'", "\"");
627
628        // Let's deserialize now.
629        let old_key: SignedKey = serde_json::from_str(old_key)?;
630        let new_key: SignedKey = serde_json::from_str(&new_key)?;
631
632        // Pick out the Curve keys, we don't care about the rest that much.
633        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    /// Query the server for users device keys.
662    ///
663    /// # Panics
664    ///
665    /// Panics if no key query needs to be done.
666    #[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    /// Construct a [`EncryptedFile`][ruma::events::room::EncryptedFile] by
682    /// encrypting and uploading a provided reader.
683    ///
684    /// # Arguments
685    ///
686    /// - `content_type` - The content type of the file.
687    /// - `reader` - The reader that should be encrypted and uploaded.
688    ///
689    /// # Examples
690    ///
691    /// ```no_run
692    /// # use matrix_sdk::Client;
693    /// # use url::Url;
694    /// # use matrix_sdk::ruma::{room_id, OwnedRoomId};
695    /// use serde::{Deserialize, Serialize};
696    /// use matrix_sdk::ruma::events::{macros::EventContent, room::EncryptedFile};
697    ///
698    /// #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
699    /// #[ruma_event(type = "com.example.custom", kind = MessageLike)]
700    /// struct CustomEventContent {
701    ///     encrypted_file: EncryptedFile,
702    /// }
703    ///
704    /// # async {
705    /// # let homeserver = Url::parse("http://example.com")?;
706    /// # let client = Client::new(homeserver).await?;
707    /// # let room = client.get_room(&room_id!("!test:example.com")).unwrap();
708    /// let mut reader = std::io::Cursor::new(b"Hello, world!");
709    /// let encrypted_file = client.upload_encrypted_file(&mut reader).await?;
710    ///
711    /// room.send(CustomEventContent { encrypted_file }).await?;
712    /// # anyhow::Ok(()) };
713    /// ```
714    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    /// Encrypt and upload the file and thumbnails, and return the source
722    /// information.
723    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    /// Uploads an encrypted thumbnail to the media repository, and returns its
744    /// source and extra information.
745    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    /// Claim one-time keys creating new Olm sessions.
766    ///
767    /// # Arguments
768    ///
769    /// * `users` - The list of user/device pairs that we should claim keys for.
770    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    /// Upload the E2E encryption keys.
792    ///
793    /// This uploads the long lived device keys as well as the required amount
794    /// of one-time keys.
795    ///
796    /// # Panics
797    ///
798    /// Panics if the client isn't logged in, or if no encryption keys need to
799    /// be uploaded.
800    #[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                                // This is one of the nastiest errors we can
881                                // have. The server telling us that we already
882                                // have a one-time key uploaded means that we
883                                // forgot about some of our one-time keys. This
884                                // will lead to UTDs.
885                                {
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        // This is needed because sometimes we need to automatically claim some
963        // one-time keys to unwedge an existing Olm session.
964        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    /// Olm-encrypt a raw to-device message and send it to a set of recipient
996    /// devices.
997    ///
998    /// If there are a lot of recipient devices multiple `/sendToDevice`
999    /// requests might be sent out.
1000    ///
1001    /// The content is always encrypted.
1002    ///
1003    /// # Arguments
1004    ///
1005    /// - `event_type` - The type of the to-device event to send.
1006    /// - `recipients` - The devices to send the message to, as a `user id ->
1007    ///   device ids` map. [`DeviceIdOrAllDevices::AllDevices`] targets every
1008    ///   device of that user we know about.
1009    ///
1010    /// - `content` - The content of the to-device event, encrypted for and sent
1011    ///   to every recipient.
1012    ///
1013    /// # Returns
1014    ///
1015    /// The devices that did _not_ receive the message, as a
1016    /// `user id -> device ids` map. A device can end up in there because it is
1017    /// unknown to us, because the sharing strategy excluded it, or because
1018    /// encrypting for it or sending to it failed. An empty map means every
1019    /// recipient was served.
1020    ///
1021    /// [`send_event_to_device`]: ruma::api::client::to_device::send_event_to_device
1022    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        // Find out the actual user devices from their name/wildcard
1032        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    /// Resolve the devices ([`Device`]) of a single user from a list of
1061    /// DeviceIdOrAllDevices.
1062    ///
1063    /// # Returns
1064    ///
1065    /// A tuple of the [`Device`]s we know about and should send to, and the
1066    /// device IDs that were explicitly requested but are unknown to us.
1067    /// [`DeviceIdOrAllDevices::AllDevices`] never yields unknown devices.
1068    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            // If the user wants to send to all devices, there's nothing to
1077            // filter and no need to inspect other entries in the user's device
1078            // list.
1079            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            // If the user wants to send to only some devices, filter out any
1095            // devices that aren't part of the recipient_device_ids list.
1096            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's now find any devices that are part of the
1111            // recipient_device_ids list but were not found in our store.
1112            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    /// Get the olm machine, for testing purposes only.
1123    pub async fn olm_machine_for_testing(&self) -> RwLockReadGuard<'_, Option<OlmMachine>> {
1124        self.olm_machine().await
1125    }
1126
1127    /// Aborts the client's bundle receiver task, for testing purposes only.
1128    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/// A high-level API to manage the client's encryption.
1137///
1138/// To get this, use [`Client::encryption()`].
1139#[derive(Debug, Clone)]
1140pub struct Encryption {
1141    /// The underlying client.
1142    client: Client,
1143}
1144
1145impl Encryption {
1146    pub(crate) fn new(client: Client) -> Self {
1147        Self { client }
1148    }
1149
1150    /// Returns the current encryption settings for this client.
1151    pub(crate) fn settings(&self) -> EncryptionSettings {
1152        self.client.inner.e2ee.encryption_settings
1153    }
1154
1155    /// Get the public ed25519 key of our own device. This is usually what is
1156    /// called the fingerprint of the device.
1157    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    /// Get the public Curve25519 key of our own device.
1162    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    /// Get the current device creation timestamp.
1167    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            // Should not happen, there should always be an own device
1171            _ => MilliSecondsSinceUnixEpoch::now(),
1172        }
1173    }
1174
1175    /// This method will import all the private cross-signing keys and, if
1176    /// available, the private part of a backup key and its accompanying version
1177    /// into the store.
1178    ///
1179    /// Importing all the secrets will mark the device as verified and enable
1180    /// backups if a backup key was available in the bundle.
1181    ///
1182    /// **Warning**: Only import this from a trusted source, i.e. if an existing
1183    /// device is sharing this with a new device.
1184    ///
1185    /// **Warning*: Only call this method right after logging in and before the
1186    /// initial sync has been started.
1187    pub async fn import_secrets_bundle(
1188        &self,
1189        bundle: &SecretsBundle,
1190    ) -> Result<(), BundleImportError> {
1191        self.import_secrets_bundle_impl(bundle).await?;
1192
1193        // Upload the device keys, this will ensure that other devices see us as
1194        // a fully verified device as soon as this method returns.
1195        self.ensure_device_keys_upload().await?;
1196        self.wait_for_e2ee_initialization_tasks().await;
1197
1198        // If our initialization tasks completed before we imported the secrets
1199        // bundle, backups might not have been enabled.
1200        //
1201        // In this case attempt to enable them again.
1202        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    /// Get the status of the private cross signing keys.
1221    ///
1222    /// This can be used to check which private cross signing keys we have
1223    /// stored locally.
1224    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    /// Does the user have devices, other than the current one, that the
1231    /// current device can verify against?
1232    ///
1233    /// The device must be signed by the user's cross-signing key, must support
1234    /// Olm (have a Curve25519 key), and must not be a dehydrated device.
1235    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    /// Get all the tracked users we know about
1247    ///
1248    /// Tracked users are users for which we keep the device list of E2EE
1249    /// capable devices up to date.
1250    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    /// Get a [`Subscriber`] for the [`VerificationState`].
1259    ///
1260    /// # Examples
1261    ///
1262    /// ```no_run
1263    /// use matrix_sdk::{Client, encryption};
1264    /// use url::Url;
1265    ///
1266    /// # async {
1267    /// let homeserver = Url::parse("http://example.com")?;
1268    /// let client = Client::new(homeserver).await?;
1269    /// let mut subscriber = client.encryption().verification_state();
1270    ///
1271    /// let current_value = subscriber.get();
1272    ///
1273    /// println!("The current verification state is: {current_value:?}");
1274    ///
1275    /// if let Some(verification_state) = subscriber.next().await {
1276    ///     println!("Received verification state update {:?}", verification_state)
1277    /// }
1278    /// # anyhow::Ok(()) };
1279    /// ```
1280    pub fn verification_state(&self) -> Subscriber<VerificationState> {
1281        self.client.inner.verification_state.subscribe_reset()
1282    }
1283
1284    /// Get a verification object with the given flow id.
1285    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    /// Get a `VerificationRequest` object for the given user with the given
1302    /// flow id.
1303    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    /// Get a specific device of a user.
1316    ///
1317    /// # Arguments
1318    ///
1319    /// - `user_id` - The unique id of the user that the device belongs to.
1320    /// - `device_id` - The unique id of the device.
1321    ///
1322    /// Returns a `Device` if one is found and the crypto store didn't throw an
1323    /// error.
1324    ///
1325    /// This will always return None if the client hasn't been logged in.
1326    ///
1327    /// # Examples
1328    ///
1329    /// ```no_run
1330    /// # use matrix_sdk::{Client, ruma::{device_id, user_id}};
1331    /// # use url::Url;
1332    /// # async {
1333    /// # let alice = user_id!("@alice:example.org");
1334    /// # let homeserver = Url::parse("http://example.com")?;
1335    /// # let client = Client::new(homeserver).await?;
1336    /// if let Some(device) =
1337    ///     client.encryption().get_device(alice, device_id!("DEVICEID")).await?
1338    /// {
1339    ///     println!("{:?}", device.is_verified());
1340    ///
1341    ///     if !device.is_verified() {
1342    ///         let verification = device.request_verification().await?;
1343    ///     }
1344    /// }
1345    /// # anyhow::Ok(()) };
1346    /// ```
1347    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    /// A convenience method to retrieve your own device from the store.
1359    ///
1360    /// This is the same as calling [`Encryption::get_device()`] with your own
1361    /// user and device ID.
1362    ///
1363    /// This will always return a device, unless you are not logged in.
1364    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    /// Get a map holding all the devices of an user.
1372    ///
1373    /// This will always return an empty map if the client hasn't been logged
1374    /// in.
1375    ///
1376    /// # Arguments
1377    ///
1378    /// - `user_id` - The unique id of the user that the devices belong to.
1379    ///
1380    /// # Examples
1381    ///
1382    /// ```no_run
1383    /// # use matrix_sdk::{Client, ruma::user_id};
1384    /// # use url::Url;
1385    /// # async {
1386    /// # let alice = user_id!("@alice:example.org");
1387    /// # let homeserver = Url::parse("http://example.com")?;
1388    /// # let client = Client::new(homeserver).await?;
1389    /// let devices = client.encryption().get_user_devices(alice).await?;
1390    ///
1391    /// for device in devices.devices() {
1392    ///     println!("{device:?}");
1393    /// }
1394    /// # anyhow::Ok(()) };
1395    /// ```
1396    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    /// Get the E2EE identity of a user from the crypto store.
1410    ///
1411    /// Usually, we only have the E2EE identity of a user locally if the user is
1412    /// tracked, meaning that we are both members of the same encrypted room.
1413    ///
1414    /// To get the E2EE identity of a user even if it is not available locally
1415    /// use [`Encryption::request_user_identity()`].
1416    ///
1417    /// # Arguments
1418    ///
1419    /// - `user_id` - The unique id of the user that the identity belongs to.
1420    ///
1421    /// Returns a `UserIdentity` if one is found and the crypto store didn't
1422    /// throw an error.
1423    ///
1424    /// This will always return None if the client hasn't been logged in.
1425    ///
1426    /// # Examples
1427    ///
1428    /// ```no_run
1429    /// # use matrix_sdk::{Client, ruma::user_id};
1430    /// # use url::Url;
1431    /// # async {
1432    /// # let alice = user_id!("@alice:example.org");
1433    /// # let homeserver = Url::parse("http://example.com")?;
1434    /// # let client = Client::new(homeserver).await?;
1435    /// let user = client.encryption().get_user_identity(alice).await?;
1436    ///
1437    /// if let Some(user) = user {
1438    ///     println!("{:?}", user.is_verified());
1439    ///
1440    ///     let verification = user.request_verification().await?;
1441    /// }
1442    /// # anyhow::Ok(()) };
1443    /// ```
1444    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    /// Get the E2EE identity of a user from the homeserver.
1456    ///
1457    /// The E2EE identity returned is always guaranteed to be up-to-date. If the
1458    /// E2EE identity is not found, it should mean that the user did not set up
1459    /// cross-signing.
1460    ///
1461    /// If you want the E2EE identity of a user without making a request to the
1462    /// homeserver, use [`Encryption::get_user_identity()`] instead.
1463    ///
1464    /// # Arguments
1465    ///
1466    /// - `user_id` - The ID of the user that the identity belongs to.
1467    ///
1468    /// Returns a [`UserIdentity`] if one is found. Returns an error if there
1469    /// was an issue with the crypto store or with the request to the
1470    /// homeserver.
1471    ///
1472    /// This will always return `None` if the client hasn't been logged in.
1473    ///
1474    /// # Examples
1475    ///
1476    /// ```no_run
1477    /// # use matrix_sdk::{Client, ruma::user_id};
1478    /// # use url::Url;
1479    /// # async {
1480    /// # let alice = user_id!("@alice:example.org");
1481    /// # let homeserver = Url::parse("http://example.com")?;
1482    /// # let client = Client::new(homeserver).await?;
1483    /// let user = client.encryption().request_user_identity(alice).await?;
1484    ///
1485    /// if let Some(user) = user {
1486    ///     println!("User is verified: {:?}", user.is_verified());
1487    ///
1488    ///     let verification = user.request_verification().await?;
1489    /// }
1490    /// # anyhow::Ok(()) };
1491    /// ```
1492    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    /// Returns a stream of device updates, allowing users to listen for
1504    /// notifications about new or changed devices.
1505    ///
1506    /// The stream produced by this method emits updates whenever a new device
1507    /// is discovered or when an existing device's information is changed. Users
1508    /// can subscribe to this stream and receive updates in real-time.
1509    ///
1510    /// # Examples
1511    ///
1512    /// ```no_run
1513    /// # use matrix_sdk::Client;
1514    /// # use ruma::{device_id, user_id};
1515    /// # use std::pin::pin;
1516    /// # use futures_util::StreamExt;
1517    /// # let client: Client = unimplemented!();
1518    /// # async {
1519    /// let devices_stream = client.encryption().devices_stream().await?;
1520    /// let user_id = client
1521    ///     .user_id()
1522    ///     .expect("We should know our user id after we have logged in");
1523    /// let mut devices_stream = pin!(devices_stream);
1524    ///
1525    /// for device_updates in devices_stream.next().await {
1526    ///     if let Some(user_devices) = device_updates.new.get(user_id) {
1527    ///         for device in user_devices.values() {
1528    ///             println!("A new device has been added {}", device.device_id());
1529    ///         }
1530    ///     }
1531    /// }
1532    /// # anyhow::Ok(()) };
1533    /// ```
1534    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    /// Returns a stream of user identity updates, allowing users to listen for
1546    /// notifications about new or changed user identities.
1547    ///
1548    /// The stream produced by this method emits updates whenever a new user
1549    /// identity is discovered or when an existing identities information is
1550    /// changed. Users can subscribe to this stream and receive updates in
1551    /// real-time.
1552    ///
1553    /// # Examples
1554    ///
1555    /// ```no_run
1556    /// # use matrix_sdk::Client;
1557    /// # use ruma::{device_id, user_id};
1558    /// # use std::pin::pin;
1559    /// # use futures_util::StreamExt;
1560    /// # let client: Client = unimplemented!();
1561    /// # async {
1562    /// let identities_stream =
1563    ///     client.encryption().user_identities_stream().await?;
1564    /// let mut identities_stream = pin!(identities_stream);
1565    ///
1566    /// for identity_updates in identities_stream.next().await {
1567    ///     for (_, identity) in identity_updates.new {
1568    ///         println!("A new identity has been added {}", identity.user_id());
1569    ///     }
1570    /// }
1571    /// # anyhow::Ok(()) };
1572    /// ```
1573    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    /// Create and upload a new cross signing identity.
1587    ///
1588    /// # Arguments
1589    ///
1590    /// - `auth_data` - This request requires user interactive auth, the first
1591    ///   request needs to set this to `None` and will always fail with an
1592    ///   `UiaaResponse`. The response will contain information for the
1593    ///   interactive auth and the same request needs to be made but this time
1594    ///   with some `auth_data` provided.
1595    ///
1596    /// # Examples
1597    ///
1598    /// ```no_run
1599    /// # use std::collections::BTreeMap;
1600    /// # use matrix_sdk::{ruma::api::client::uiaa, Client};
1601    /// # use url::Url;
1602    /// # use serde_json::json;
1603    /// # async {
1604    /// # let homeserver = Url::parse("http://example.com")?;
1605    /// # let client = Client::new(homeserver).await?;
1606    /// if let Err(e) = client.encryption().bootstrap_cross_signing(None).await {
1607    ///     if let Some(response) = e.as_uiaa_response() {
1608    ///         let mut password = uiaa::Password::new(
1609    ///             uiaa::UserIdentifier::Matrix(uiaa::MatrixUserIdentifier::new(
1610    ///                 "example".to_owned(),
1611    ///             )),
1612    ///             "wordpass".to_owned(),
1613    ///         );
1614    ///         password.session = response.session.clone();
1615    ///
1616    ///         client
1617    ///             .encryption()
1618    ///             .bootstrap_cross_signing(Some(uiaa::AuthData::Password(
1619    ///                 password,
1620    ///             )))
1621    ///             .await
1622    ///             .expect("Couldn't bootstrap cross signing")
1623    ///     } else {
1624    ///         panic!("Error during cross signing bootstrap {:#?}", e);
1625    ///     }
1626    /// }
1627    /// # anyhow::Ok(()) };
1628    /// ```
1629    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    /// Reset the cross-signing keys.
1654    ///
1655    /// # Example
1656    ///
1657    /// ```no_run
1658    /// use matrix_sdk::encryption::CrossSigningResetAuthType;
1659    ///
1660    /// # async {
1661    /// # let homeserver = url::Url::parse("http://example.com")?;
1662    /// # let client = matrix_sdk::Client::new(homeserver).await?;
1663    /// # let user_id = unimplemented!();
1664    /// let encryption = client.encryption();
1665    ///
1666    /// if let Some(handle) = encryption.reset_cross_signing().await? {
1667    ///     match handle.auth_type() {
1668    ///         CrossSigningResetAuthType::Uiaa(uiaa) => {
1669    ///             let password = "1234".to_owned();
1670    ///
1671    ///             handle.auth(uiaa.as_password_auth_data(user_id, password)).await?;
1672    ///         }
1673    ///         CrossSigningResetAuthType::OAuth(oauth) => {
1674    ///             println!(
1675    ///                 "To reset your end-to-end encryption cross-signing identity, \
1676    ///                 you first need to approve it at {}",
1677    ///                 oauth.approval_url
1678    ///             );
1679    ///
1680    ///             handle.auth(oauth.as_auth_data()).await?;
1681    ///         }
1682    ///     }
1683    /// }
1684    /// # anyhow::Ok(()) };
1685    /// ```
1686    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        // Upload the signing keys first, since if the user bails out of the
1693        // reset flow, we don't want to have overwritten our identity in
1694        // the store.
1695        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            // Once the signing keys are uploaded, we can commit the reset and
1709            // upload the signatures, followed by any pending device keys. The
1710            // signatures go first, since a failed device keys upload is retried
1711            // after the next sync, while a failed signatures upload is not.
1712            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    /// Query the user's own device keys, so that the signatures we just
1725    /// uploaded for our own device are reflected locally.
1726    ///
1727    /// This is best-effort: the signatures are already uploaded, so if this
1728    /// fails a later sync will pick them up.
1729    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    /// Query the user's own device keys, if, and only if, we didn't have their
1739    /// identity in the first place.
1740    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    /// Create and upload a new cross signing identity, if that has not been
1755    /// done yet.
1756    ///
1757    /// This will only create a new cross-signing identity if the user had never
1758    /// done it before. If the user did it before, then this is a no-op.
1759    ///
1760    /// See also the documentation of [`Self::bootstrap_cross_signing`] for the
1761    /// behavior of this function.
1762    ///
1763    /// # Arguments
1764    ///
1765    /// - `auth_data` - This request requires user interactive auth, the first
1766    ///   request needs to set this to `None` and will always fail with an
1767    ///   `UiaaResponse`. The response will contain information for the
1768    ///   interactive auth and the same request needs to be made but this time
1769    ///   with some `auth_data` provided.
1770    ///
1771    /// # Examples
1772    ///
1773    /// ```no_run
1774    /// # use std::collections::BTreeMap;
1775    /// # use matrix_sdk::{ruma::api::client::uiaa, Client};
1776    /// # use url::Url;
1777    /// # use serde_json::json;
1778    /// # async {
1779    /// # let homeserver = Url::parse("http://example.com")?;
1780    /// # let client = Client::new(homeserver).await?;
1781    /// if let Err(e) = client.encryption().bootstrap_cross_signing_if_needed(None).await {
1782    ///     if let Some(response) = e.as_uiaa_response() {
1783    ///         let mut password = uiaa::Password::new(
1784    ///             uiaa::UserIdentifier::Matrix(uiaa::MatrixUserIdentifier::new("example".to_owned())),
1785    ///             "wordpass".to_owned(),
1786    ///         );
1787    ///         password.session = response.session.clone();
1788    ///
1789    ///         // Note, on the failed attempt we can use `bootstrap_cross_signing` immediately, to
1790    ///         // avoid checks.
1791    ///         client
1792    ///             .encryption()
1793    ///             .bootstrap_cross_signing(Some(uiaa::AuthData::Password(password)))
1794    ///             .await
1795    ///             .expect("Couldn't bootstrap cross signing")
1796    ///     } else {
1797    ///         panic!("Error during cross signing bootstrap {:#?}", e);
1798    ///     }
1799    /// }
1800    /// # anyhow::Ok(()) };
1801    /// ```
1802    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    /// Export E2EE keys that match the given predicate encrypting them with the
1820    /// given passphrase.
1821    ///
1822    /// # Arguments
1823    ///
1824    /// - `path` - The file path where the exported key file will be saved.
1825    /// - `passphrase` - The passphrase that will be used to encrypt the
1826    ///   exported room keys.
1827    ///
1828    /// - `predicate` - A closure that will be called for every known
1829    ///   `InboundGroupSession`, which represents a room key. If the closure
1830    ///   returns `true` the `InboundGroupSessoin` will be included in the
1831    ///   export, if the closure returns `false` it will not be included.
1832    ///
1833    /// # Panics
1834    ///
1835    /// This method will panic if it isn't run on a Tokio runtime.
1836    ///
1837    /// This method will panic if it can't get enough randomness from the OS to
1838    /// encrypt the exported keys securely.
1839    ///
1840    /// # Examples
1841    ///
1842    /// ```no_run
1843    /// # use std::{path::PathBuf, time::Duration};
1844    /// # use matrix_sdk::{
1845    /// #     Client, config::SyncSettings,
1846    /// #     ruma::room_id,
1847    /// # };
1848    /// # use url::Url;
1849    /// # async {
1850    /// # let homeserver = Url::parse("http://localhost:8080")?;
1851    /// # let mut client = Client::new(homeserver).await?;
1852    /// let path = PathBuf::from("/home/example/e2e-keys.txt");
1853    /// // Export all room keys.
1854    /// client
1855    ///     .encryption()
1856    ///     .export_room_keys(path, "secret-passphrase", |_| true)
1857    ///     .await?;
1858    ///
1859    /// // Export only the room keys for a certain room.
1860    /// let path = PathBuf::from("/home/example/e2e-room-keys.txt");
1861    /// let room_id = room_id!("!test:localhost");
1862    ///
1863    /// client
1864    ///     .encryption()
1865    ///     .export_room_keys(path, "secret-passphrase", |s| s.room_id() == room_id)
1866    ///     .await?;
1867    /// # anyhow::Ok(()) };
1868    /// ```
1869    #[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    /// Import E2EE keys from the given file path.
1895    ///
1896    /// # Arguments
1897    ///
1898    /// - `path` - The file path where the exported key file will can be found.
1899    /// - `passphrase` - The passphrase that should be used to decrypt the
1900    ///   exported room keys.
1901    ///
1902    /// Returns a tuple of numbers that represent the number of sessions that
1903    /// were imported and the total number of sessions that were found in the
1904    /// key export.
1905    ///
1906    /// # Panics
1907    ///
1908    /// This method will panic if it isn't run on a Tokio runtime.
1909    ///
1910    /// ```no_run
1911    /// # use std::{path::PathBuf, time::Duration};
1912    /// # use matrix_sdk::{
1913    /// #     Client, config::SyncSettings,
1914    /// #     ruma::room_id,
1915    /// # };
1916    /// # use url::Url;
1917    /// # async {
1918    /// # let homeserver = Url::parse("http://localhost:8080")?;
1919    /// # let mut client = Client::new(homeserver).await?;
1920    /// let path = PathBuf::from("/home/example/e2e-keys.txt");
1921    /// let result =
1922    ///     client.encryption().import_room_keys(path, "secret-passphrase").await?;
1923    ///
1924    /// println!(
1925    ///     "Imported {} room keys out of {}",
1926    ///     result.imported_count, result.total_count
1927    /// );
1928    /// # anyhow::Ok(()) };
1929    /// ```
1930    #[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    /// Receive notifications of room keys being received as a [`Stream`].
1956    ///
1957    /// Each time a room key is updated in any way, an update will be sent to
1958    /// the stream. Updates that happen at the same time are batched into a
1959    /// [`Vec`].
1960    ///
1961    /// If the reader of the stream lags too far behind, an error is broadcast
1962    /// containing the number of skipped items.
1963    ///
1964    /// # Examples
1965    ///
1966    /// ```no_run
1967    /// # use matrix_sdk::Client;
1968    /// # use url::Url;
1969    /// # async {
1970    /// # let homeserver = Url::parse("http://example.com")?;
1971    /// # let client = Client::new(homeserver).await?;
1972    /// use futures_util::StreamExt;
1973    ///
1974    /// let Some(mut room_keys_stream) =
1975    ///     client.encryption().room_keys_received_stream().await
1976    /// else {
1977    ///     return Ok(());
1978    /// };
1979    ///
1980    /// while let Some(update) = room_keys_stream.next().await {
1981    ///     println!("Received room keys {update:?}");
1982    /// }
1983    /// # anyhow::Ok(()) };
1984    /// ```
1985    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    /// Receive notifications of historic room key bundles as a [`Stream`].
1996    ///
1997    /// Historic room key bundles are defined in
1998    /// [MSC4268](https://github.com/matrix-org/matrix-spec-proposals/pull/4268).
1999    ///
2000    /// Each time a historic room key bundle was received, an update will be
2001    /// sent to the stream. This stream is useful for informative purposes
2002    /// exclusively, historic room key bundles are handled by the SDK
2003    /// automatically.
2004    ///
2005    /// # Examples
2006    ///
2007    /// ```no_run
2008    /// # use matrix_sdk::Client;
2009    /// # use url::Url;
2010    /// # async {
2011    /// # let homeserver = Url::parse("http://example.com")?;
2012    /// # let client = Client::new(homeserver).await?;
2013    /// use futures_util::StreamExt;
2014    ///
2015    /// let Some(mut bundle_stream) =
2016    ///     client.encryption().historic_room_key_stream().await
2017    /// else {
2018    ///     return Ok(());
2019    /// };
2020    ///
2021    /// while let Some(bundle_info) = bundle_stream.next().await {
2022    ///     println!("Received a historic room key bundle {bundle_info:?}");
2023    /// }
2024    /// # anyhow::Ok(()) };
2025    /// ```
2026    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    /// Get the secret storage manager of the client.
2036    pub fn secret_storage(&self) -> SecretStorage {
2037        SecretStorage { client: self.client.to_owned() }
2038    }
2039
2040    /// Get the backups manager of the client.
2041    pub fn backups(&self) -> Backups {
2042        Backups { client: self.client.to_owned() }
2043    }
2044
2045    /// Get the recovery manager of the client.
2046    pub fn recovery(&self) -> Recovery {
2047        Recovery { client: self.client.to_owned() }
2048    }
2049
2050    /// Get the dehydrated-devices manager of the client.
2051    ///
2052    /// A dehydrated device is a virtual device that the homeserver holds on the
2053    /// user's behalf and that can receive end-to-end encrypted to-device events
2054    /// while the user is offline. See the [`dehydrated_devices`] module for the
2055    /// full lifecycle and an example.
2056    pub fn dehydrated_devices(&self) -> dehydrated_devices::DehydratedDevices {
2057        dehydrated_devices::DehydratedDevices { client: self.client.to_owned() }
2058    }
2059
2060    /// Enables the crypto-store cross-process lock.
2061    ///
2062    /// This may be required if there are multiple processes that may do writes
2063    /// to the same crypto store. In that case, it's necessary to create a lock,
2064    /// so that only one process writes to it, otherwise this may cause
2065    /// confusing issues because of stale data contained in in-memory caches.
2066    ///
2067    /// The provided `lock_value` must be a unique identifier for this process.
2068    /// Use [`Client::cross_process_lock_config`] to get the global value, if
2069    /// multi-process is enabled.
2070    pub async fn enable_cross_process_store_lock(&self, lock_value: String) -> Result<(), Error> {
2071        // If the lock has already been created, don't recreate it from scratch.
2072        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        // Gently try to initialize the crypto store generation counter.
2092        //
2093        // If we don't get the lock immediately, then it is already acquired by
2094        // another process, and we'll get to reload next time we acquire the
2095        // lock.
2096        {
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    /// Maybe reload the `OlmMachine` after acquiring the lock for the first
2118    /// time.
2119    ///
2120    /// Returns the current generation number.
2121    #[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 the crypto store generation has changed,
2135            if new_gen {
2136                // (get rid of the reference to the current crypto store first)
2137                drop(olm_machine_guard);
2138                // Recreate the OlmMachine.
2139                self.client.base_client().regenerate_olm(None).await?;
2140            }
2141            Ok(generation_number)
2142        } else {
2143            // XXX: not sure this is reachable. Seems like the OlmMachine should
2144            // always have been initialised by the time we get here. Ideally
2145            // we'd panic, or return an error, but for now I'm just adding some
2146            // logging to check if it happens, and returning the magic number 0.
2147            warn!("Encryption::on_lock_newly_acquired: called before OlmMachine initialised");
2148            Ok(0)
2149        }
2150    }
2151
2152    /// If a lock was created with [`Self::enable_cross_process_store_lock`],
2153    /// spin-waits until the lock is available.
2154    ///
2155    /// May reload the `OlmMachine`, after obtaining the lock but not on the
2156    /// first time.
2157    ///
2158    /// Returns a guard to the lock, if it was obtained.
2159    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    /// If a lock was created with [`Self::enable_cross_process_store_lock`],
2167    /// attempts to lock it once.
2168    ///
2169    /// May reload the `OlmMachine`, after obtaining the lock but not on the
2170    /// first time.
2171    ///
2172    /// Returns a guard to the lock, if it was obtained.
2173    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    /// If a lock was created with [`Self::enable_cross_process_store_lock`],
2185    /// locks the store with the given function, `acquire`.
2186    ///
2187    /// Reloads the `OlmMachine` after obtaining the lock, if the lock is dirty.
2188    ///
2189    /// Returns a guard to the lock if it was obtained.
2190    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    /// Testing purposes only.
2207    #[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    /// Bootstrap encryption and enables event listeners for the E2EE support.
2215    ///
2216    /// Based on the `EncryptionSettings`, this call might:
2217    ///
2218    /// - Bootstrap cross-signing if needed (POST `/device_signing/upload`)
2219    /// - Create a key backup if needed (POST `/room_keys/version`)
2220    /// - Create a secret storage if needed (PUT `/account_data/{type}`)
2221    ///
2222    /// As part of this process, and if needed, the current device keys would be
2223    /// uploaded to the server, new account data would be added, and cross
2224    /// signing keys and signatures might be uploaded.
2225    ///
2226    /// Should be called once we created a [`OlmMachine`], i.e. after logging
2227    /// in.
2228    ///
2229    /// # Arguments
2230    ///
2231    /// - `auth_data` - Some requests may require re-authentication. To prevent
2232    ///   the user from having to re-enter their password (or use other
2233    ///   methods), we can provide the authentication data here. This is
2234    ///   necessary for uploading cross-signing keys. However, please note that
2235    ///   there is a proposal (MSC3967) to remove this requirement, which would
2236    ///   allow for the initial upload of cross-signing keys without
2237    ///   authentication, rendering this parameter obsolete.
2238    pub(crate) async fn spawn_initialization_task(&self, auth_data: Option<AuthData>) {
2239        // It's fine to be async here as we're only getting the lock protecting
2240        // the `OlmMachine`. Since the lock shouldn't be that contested right
2241        // after logging in we won't delay the login or restoration of the
2242        // Client.
2243        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                // Update the current state first, so we don't have to wait for
2256                // the result of network requests
2257                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    /// Waits for end-to-end encryption initialization tasks to finish, if any
2281    /// was running in the background.
2282    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    /// Upload the device keys and initial set of one-time keys to the server.
2293    ///
2294    /// This should only be called when the user logs in for the first time, the
2295    /// method will ensure that other devices see our own device as an
2296    /// end-to-end encryption enabled one.
2297    ///
2298    /// **Warning**: Do not use this method if we're already calling
2299    /// [`Client::send_outgoing_request()`]. This method is intended for
2300    /// explicitly uploading the device keys before starting a sync.
2301    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        // Only update the verification_state if our own devices changed
2319        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                        // We don't know our own identity yet, so we can't tell
2338                        // whether we're verified; it'll be updated after the
2339                        // next keys query.
2340                        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    /// Sets up a handler to rotate room keys when a user leaves a room.
2357    ///
2358    /// Previously, it was sufficient to check if we need to rotate the room key
2359    /// prior to sending a message. However, the history sharing feature
2360    /// ([MSC4268]) breaks this logic:
2361    ///
2362    /// 1. Alice sends a message M1 in room X;
2363    /// 2. Bob invites Charlie, who joins and immediately leaves the room;
2364    /// 3. Alice sends another message M2 in room X.
2365    ///
2366    /// Under the old logic, Alice would not rotate her key after Charlie
2367    /// leaves, resulting in M2 being encrypted with the same session as M1.
2368    /// This would allow Charlie to decrypt M2 if he ever gains access to the
2369    /// event.
2370    ///
2371    /// This handler listens for changes to the room membership, and discards
2372    /// the current room key if the event is not a `join` or `invite` event.
2373    ///
2374    /// [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268
2375    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                // The main client has been dropped.
2380                return;
2381            };
2382            let Some(user_id) = client.user_id() else {
2383                // We aren't logged in, so this shouldn't ever happen.
2384                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                // We can ignore events that did not remove the user, and those that involve us.
2401                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            // Attempt to discard the current room key. This won't do anything
2407            // if we don't have one, but that's fine since we will create a new
2408            // room key whenever we try to send a message.
2409            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    /// Encrypts then send the given content via the `/sendToDevice` end-point
2419    /// using Olm encryption.
2420    ///
2421    /// If there are a lot of recipient devices multiple `/sendToDevice`
2422    /// requests might be sent out.
2423    ///
2424    /// # Returns
2425    ///
2426    /// A list of failures. The list of devices that couldn't get the messages.
2427    #[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        // Will claim one-time-key for users that needs it TODO: For later
2438        // optimisation: This will establish missing olm sessions with all this
2439        // users devices, but we just want for some devices.
2440        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        // Push the withhelds in the failures
2459        withhelds.iter().for_each(|(d, _)| {
2460            failures.push((d.user_id().to_owned(), d.device_id().to_owned()));
2461        });
2462
2463        // TODO: parallelize that? it's already grouping 250 devices per chunk.
2464        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 the sending failed we need to collect the failures to report
2477            // them
2478            if send_result.is_err() {
2479                // Mark the sending as failed
2480                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                                // Cannot happen in this case
2488                            }
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        // Create two clients using the same sqlite database.
2591
2592        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        // When the lock isn't enabled, any attempt at locking won't return a
2620        // guard.
2621        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        // One client can take the lock.
2628        let acquired1 = client1.encryption().spin_lock_store(None).await.unwrap();
2629        assert!(acquired1.is_some());
2630
2631        // Keep the olm machine, so we can see if it's changed later, by
2632        // comparing Arcs.
2633        let initial_olm_machine =
2634            client1.olm_machine().await.clone().expect("must have an olm machine");
2635
2636        // Also enable backup to check that new machine has the same backup
2637        // keys.
2638        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        // The other client can't take the lock too.
2652        let acquired2 = client2.encryption().try_lock_store_once().await.unwrap();
2653        assert!(acquired2.is_none());
2654
2655        // Now have the first client release the lock,
2656        drop(acquired1);
2657
2658        // And re-take it.
2659        let acquired1 = client1.encryption().spin_lock_store(None).await.unwrap();
2660        assert!(acquired1.is_some());
2661
2662        // In that case, the Olm Machine shouldn't change.
2663        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        // Ok, release again.
2667        drop(acquired1);
2668
2669        // Client2 can acquire the lock.
2670        let acquired2 = client2.encryption().spin_lock_store(None).await.unwrap();
2671        assert!(acquired2.is_some());
2672
2673        // And then release it.
2674        drop(acquired2);
2675
2676        // Client1 can acquire it again,
2677        let acquired1 = client1.encryption().spin_lock_store(None).await.unwrap();
2678        assert!(acquired1.is_some());
2679
2680        // But now its olm machine has been invalidated and thus regenerated!
2681        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        // Create two clients using the same sqlite database.
2698
2699        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        // Enabling the lock doesn't update the olm machine.
2722        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            // Simulate that another client hold the lock before.
2727            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        // Taking the lock the first time will update the olm machine.
2758        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        // Re-taking the lock doesn't update the olm machine.
2767        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        // Given a client and a server
2774        let client = no_retry_test_client(None).await;
2775        let server = MockServer::start().await;
2776
2777        // When we subscribe to its verification state
2778        let mut verification_state = client.encryption().verification_state();
2779
2780        // We can get its initial value, and it's Unknown
2781        assert_next_matches_with_timeout!(verification_state, VerificationState::Unknown);
2782
2783        // We set up a mocked request to check this endpoint is not called
2784        // before reading the new state
2785        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        // When the session is initialised and the encryption tasks spawn
2800        set_client_session(&client).await;
2801
2802        // Then we can get an updated value without waiting for any network
2803        // requests, which stays unknown as we don't know our own identity yet
2804        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    // Helper function for the test_devices_to_verify_against_* tests. Make a
2855    // response to a /keys/query request using the given device keys and a
2856    // pre-defined set of cross-signing keys.
2857    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    // The following three tests test that we can detect whether the user has
2909    // other devices that they can verify against under different conditions.
2910    #[async_test]
2911    /// Test that we detect that can't verify against another device if we have
2912    /// no devices.
2913    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    /// Test that we detect that we can verify against another cross-signed
2931    /// regular device.
2932    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    /// Test that we detect that we can't verify against a dehydrated or
2968    /// unsigned device.
2969    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        /// Set up Alice and Bob, where Bob has two devices that Alice knows
3042        /// about.
3043        ///
3044        /// The [`MatrixMockServer`] is returned so that it stays alive for the
3045        /// duration of the test.
3046        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            // Let Alice download Bob's second device.
3058            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        /// The device IDs of the given devices, sorted so that we can assert on
3069        /// them.
3070        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        /// Asking for several device IDs resolves all of them, and only them.
3113        #[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            // Let Alice download Bob's third device.
3122            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        /// A single unknown device must not prevent the known ones from
3165        /// receiving the message.
3166        #[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        /// If `AllDevices` is mixed with explicit device IDs, `AllDevices` wins
3186        /// and the explicit entries are ignored, even if they are unknown to
3187        /// us.
3188        #[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        /// An empty recipient list targets nobody, it is not a synonym for
3211        /// `AllDevices`.
3212        #[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        /// A user we don't know anything about has no devices, and every device
3224        /// explicitly asked for is unknown.
3225        #[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            // `AllDevices` for an unknown user is not an error either, it just
3242            // resolves to nothing.
3243            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}