Skip to main content

matrix_sdk/encryption/recovery/
mod.rs

1// Copyright 2023 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The recovery module
16//!
17//! The recovery module attempts to provide a unified and simplified view over
18//! the secret storage and backup subsystems.
19//!
20//! **Note**: If you are using this module, do not use the [`SecretStorage`] and
21//! [`Backups`] subsystems directly. This module makes assumptions that might be
22//! broken by the direct usage of the respective lower level modules.
23//!
24//! **Note**: The term Recovery used in this submodule is not the same as the
25//! [`Recovery key`] mentioned in the spec. The recovery key from the spec is
26//! solely about backups, while the term recovery in this file includes both the
27//! backups and the secret storage subsystems. The recovery key mentioned in
28//! this file is the secret storage key.
29//!
30//! You should configure your client to bootstrap cross-signing automatically
31//! and may choose to let your client automatically create a backup, if it
32//! doesn't exist, as well:
33//!
34//! ```no_run
35//! use matrix_sdk::{Client, encryption::EncryptionSettings};
36//!
37//! # async {
38//! # let homeserver = "http://example.org";
39//! let client = Client::builder()
40//!     .homeserver_url(homeserver)
41//!     .with_encryption_settings(EncryptionSettings {
42//!         auto_enable_cross_signing: true,
43//!         auto_enable_backups: true,
44//!         ..Default::default()
45//!     })
46//!     .build()
47//!     .await?;
48//! # anyhow::Ok(()) };
49//! ```
50//!
51//! # Examples
52//!
53//! For a newly registered user you will want to enable recovery, either
54//! immediately or before the user logs out.
55//!
56//! ```no_run
57//! # use matrix_sdk::{Client, encryption::recovery::EnableProgress};
58//! # use url::Url;
59//! # async {
60//! # let homeserver = Url::parse("http://example.com")?;
61//! # let client = Client::new(homeserver).await?;
62//! let recovery = client.encryption().recovery();
63//!
64//! // Create a new recovery key, you can use the provided passphrase, or the returned recovery key
65//! // to recover.
66//! let recovery_key = recovery
67//!     .enable()
68//!     .wait_for_backups_to_upload()
69//!     .with_passphrase("my passphrase")
70//!     .await;
71//! # anyhow::Ok(()) };
72//! ```
73//!
74//! If the user logs in with another device, you'll want to let the user recover
75//! its secrets by entering the recovery key or recovery passphrase.
76//!
77//! ```no_run
78//! # use matrix_sdk::{Client, encryption::recovery::EnableProgress};
79//! # use url::Url;
80//! # async {
81//! # let homeserver = Url::parse("http://example.com")?;
82//! # let client = Client::new(homeserver).await?;
83//! let recovery = client.encryption().recovery();
84//!
85//! // Create a new recovery key, you can use the provided passphrase, or the returned recovery key
86//! // to recover.
87//! recovery.recover("my recovery key or passphrase").await;
88//! # anyhow::Ok(()) };
89//! ```
90//!
91//! [`Recovery key`]: https://spec.matrix.org/v1.8/client-server-api/#recovery-key
92
93use futures_core::{Future, Stream};
94use futures_util::StreamExt as _;
95use ruma::{
96    api::client::keys::get_keys,
97    events::{
98        GlobalAccountDataEventType,
99        key_backup::KeyBackupEventContent,
100        secret::{request::SecretName, send::ToDeviceSecretSendEvent},
101        secret_storage::{default_key::SecretStorageDefaultKeyEvent, secret::SecretEventContent},
102    },
103    serde::Raw,
104};
105use serde_json::{json, value::to_raw_value};
106use tracing::{error, info, instrument, warn};
107
108#[cfg(doc)]
109use crate::encryption::{
110    backups::Backups,
111    secret_storage::{SecretStorage, SecretStore},
112};
113use crate::{
114    Client,
115    encryption::{backups::BackupState, secret_storage::SecretStorageError},
116};
117
118pub mod futures;
119mod types;
120pub use self::types::{EnableProgress, RecoveryError, RecoveryState, Result};
121use self::{
122    futures::{Enable, RecoverAndReset, Reset},
123    types::{BackupDisabledContent, SecretStorageDisabledContent},
124};
125use crate::encryption::{AuthData, CrossSigningResetAuthType, CrossSigningResetHandle};
126
127/// The recovery manager for the [`Client`].
128#[derive(Debug)]
129pub struct Recovery {
130    pub(super) client: Client,
131}
132
133impl Recovery {
134    /// The list of known secrets that are contained in secret storage once
135    /// recover is enabled.
136    pub const KNOWN_SECRETS: &[SecretName] = &[
137        SecretName::CrossSigningMasterKey,
138        SecretName::CrossSigningUserSigningKey,
139        SecretName::CrossSigningSelfSigningKey,
140        SecretName::RecoveryKey,
141    ];
142
143    /// Get the current [`RecoveryState`] for this [`Client`].
144    pub fn state(&self) -> RecoveryState {
145        self.client.inner.e2ee.recovery_state.get()
146    }
147
148    /// Get a stream of updates to the [`RecoveryState`].
149    ///
150    /// This method will send out the current state as the first update.
151    ///
152    /// # Examples
153    ///
154    /// ```no_run
155    /// # use matrix_sdk::{Client, encryption::recovery::RecoveryState};
156    /// # use url::Url;
157    /// # async {
158    /// # let homeserver = Url::parse("http://example.com")?;
159    /// # let client = Client::new(homeserver).await?;
160    /// use futures_util::StreamExt;
161    ///
162    /// let recovery = client.encryption().recovery();
163    ///
164    /// let mut state_stream = recovery.state_stream();
165    ///
166    /// while let Some(update) = state_stream.next().await {
167    ///     match update {
168    ///         RecoveryState::Enabled => {
169    ///             println!("Recovery has been enabled");
170    ///         }
171    ///         _ => (),
172    ///     }
173    /// }
174    /// # anyhow::Ok(()) };
175    /// ```
176    pub fn state_stream(&self) -> impl Stream<Item = RecoveryState> + use<> {
177        self.client.inner.e2ee.recovery_state.subscribe_reset()
178    }
179
180    /// Enable secret storage _and_ backups.
181    ///
182    /// This method will create a new secret storage key and a new backup if one
183    /// doesn't already exist. It will then upload all the locally cached
184    /// secrets, including the backup recovery key, to the new secret store.
185    ///
186    /// This method will throw an error if a backup already exists on the
187    /// homeserver but this [`Client`] isn't connected to the existing backup.
188    ///
189    /// # Examples
190    ///
191    /// ```no_run
192    /// # use matrix_sdk::{Client, encryption::recovery::EnableProgress};
193    /// # use url::Url;
194    /// # async {
195    /// # let homeserver = Url::parse("http://example.com")?;
196    /// # let client = Client::new(homeserver).await?;
197    /// use futures_util::StreamExt;
198    ///
199    /// let recovery = client.encryption().recovery();
200    ///
201    /// let enable = recovery
202    ///     .enable()
203    ///     .wait_for_backups_to_upload()
204    ///     .with_passphrase("my passphrase");
205    ///
206    /// let mut progress_stream = enable.subscribe_to_progress();
207    ///
208    /// tokio::spawn(async move {
209    ///     while let Some(update) = progress_stream.next().await {
210    ///         let Ok(update) = update else {
211    ///             panic!("Update to the enable progress lagged")
212    ///         };
213    ///
214    ///         match update {
215    ///             EnableProgress::CreatingBackup => {
216    ///                 println!("Creating a new backup");
217    ///             }
218    ///             EnableProgress::CreatingRecoveryKey => {
219    ///                 println!("Creating a new recovery key");
220    ///             }
221    ///             EnableProgress::Done { .. } => {
222    ///                 println!("Recovery has been enabled");
223    ///                 break;
224    ///             }
225    ///             _ => (),
226    ///         }
227    ///     }
228    /// });
229    ///
230    /// let recovery_key = enable.await?;
231    ///
232    /// # anyhow::Ok(()) };
233    /// ```
234    #[instrument(skip_all)]
235    pub fn enable(&self) -> Enable<'_> {
236        Enable::new(self)
237    }
238
239    /// Create a new backup if one does not exist yet.
240    ///
241    /// This method will throw an error if a backup already exists on the
242    /// homeserver but this [`Client`] isn't connected to the existing backup.
243    ///
244    /// # Examples
245    ///
246    /// ```no_run
247    /// # use matrix_sdk::{Client, encryption::backups::BackupState};
248    /// # use url::Url;
249    /// # async {
250    /// # let homeserver = Url::parse("http://example.com")?;
251    /// # let client = Client::new(homeserver).await?;
252    /// let recovery = client.encryption().recovery();
253    ///
254    /// recovery.enable_backup().await?;
255    ///
256    /// assert_eq!(client.encryption().backups().state(), BackupState::Enabled);
257    ///
258    /// # anyhow::Ok(()) };
259    /// ```
260    #[instrument(skip_all)]
261    pub async fn enable_backup(&self) -> Result<()> {
262        if !self.client.encryption().backups().fetch_exists_on_server().await? {
263            self.mark_backup_as_enabled().await?;
264
265            self.client.encryption().backups().create().await?;
266            self.client.encryption().backups().maybe_trigger_backup();
267
268            Ok(())
269        } else {
270            Err(RecoveryError::BackupExistsOnServer)
271        }
272    }
273
274    /// Disable recovery completely.
275    ///
276    /// This method will do the following steps:
277    ///
278    /// 1. Disable the uploading of room keys to a currently active backup.
279    /// 2. Delete the currently active backup.
280    /// 3. Set the `m.secret_storage.default_key` global account data event to
281    ///    an empty JSON content.
282    /// 4. Set a global account data event so clients won't attempt to
283    ///    automatically re-enable a backup.
284    ///
285    /// # Examples
286    ///
287    /// ```no_run
288    /// # use matrix_sdk::{Client, encryption::recovery::RecoveryState};
289    /// # use url::Url;
290    /// # async {
291    /// # let homeserver = Url::parse("http://example.com")?;
292    /// # let client = Client::new(homeserver).await?;
293    /// let recovery = client.encryption().recovery();
294    ///
295    /// recovery.disable().await?;
296    ///
297    /// assert_eq!(recovery.state(), RecoveryState::Disabled);
298    ///
299    /// # anyhow::Ok(()) };
300    /// ```
301    #[instrument(skip_all)]
302    pub async fn disable(&self) -> Result<()> {
303        self.client.encryption().backups().disable().await?;
304
305        // Why oh why, can't we delete account data events?
306        //
307        // Alright, let's attempt to "delete" the content of our current default
308        // key, for this we first need to check if there is a default key, then
309        // deserialize the content and find out the key ID.
310        //
311        // Then we finally set the event to an empty JSON content.
312        if let Ok(Some(default_event)) =
313            self.client.encryption().secret_storage().fetch_default_key_id().await
314            && let Ok(default_event) = default_event.deserialize()
315        {
316            let key_id = default_event.key_id;
317            let event_type = GlobalAccountDataEventType::SecretStorageKey(key_id);
318
319            self.client
320                .account()
321                .set_account_data_raw(event_type, Raw::new(&json!({})).expect("").cast_unchecked())
322                .await?;
323        }
324
325        // Now let's "delete" the actual `m.secret.storage.default_key` event.
326        self.client.account().set_account_data(SecretStorageDisabledContent {}).await?;
327        // Make sure that we don't re-enable backups automatically.
328        self.client.account().set_account_data(KeyBackupEventContent::new(false)).await?;
329        // (Unstable prefix version of `m.key_backup`)
330        self.client.account().set_account_data(BackupDisabledContent { disabled: true }).await?;
331        // Finally, "delete" all the known secrets we have in the account data.
332        self.delete_all_known_secrets().await?;
333
334        self.update_recovery_state().await?;
335
336        Ok(())
337    }
338
339    /// Reset the recovery key.
340    ///
341    /// This will rotate the secret storage key and re-upload all the secrets to
342    /// the [`SecretStore`].
343    ///
344    /// # Examples
345    ///
346    /// ```no_run
347    /// # use matrix_sdk::{Client, encryption::recovery::RecoveryState};
348    /// # use url::Url;
349    /// # async {
350    /// # let homeserver = Url::parse("http://example.com")?;
351    /// # let client = Client::new(homeserver).await?;
352    /// let recovery = client.encryption().recovery();
353    ///
354    /// let new_recovery_key =
355    ///     recovery.reset_key().with_passphrase("my passphrase").await;
356    /// # anyhow::Ok(()) };
357    /// ```
358    #[instrument(skip_all)]
359    pub fn reset_key(&self) -> Reset<'_> {
360        // TODO: Should this only be possible if we're in the
361        // RecoveryState::Enabled state? Otherwise we'll create a new secret
362        // store but won't be able to upload all the secrets.
363        Reset::new(self)
364    }
365
366    /// Reset the recovery key but first import all the secrets from secret
367    /// storage.
368    ///
369    /// # Examples
370    ///
371    /// ```no_run
372    /// # use matrix_sdk::{Client, encryption::recovery::RecoveryState};
373    /// # use url::Url;
374    /// # async {
375    /// # let homeserver = Url::parse("http://example.com")?;
376    /// # let client = Client::new(homeserver).await?;
377    /// let recovery = client.encryption().recovery();
378    ///
379    /// let new_recovery_key = recovery
380    ///     .recover_and_reset("my old passphrase or key")
381    ///     .with_passphrase("my new passphrase")
382    ///     .await?;
383    /// # anyhow::Ok(()) };
384    /// ```
385    #[instrument(skip_all)]
386    pub fn recover_and_reset<'a>(&'a self, old_key: &'a str) -> RecoverAndReset<'a> {
387        RecoverAndReset::new(self, old_key)
388    }
389
390    /// Completely reset the current user's crypto identity. This method will go
391    /// through the following steps:
392    ///
393    /// 1. Go through the cross-signing key reset flow, which may require
394    ///    authentication
395    /// 2. Disable backing up room keys and delete the active backup
396    /// 3. Disable recovery and delete secret storage
397    /// 4. Finally, re-enable key backups (only if they were already enabled)
398    ///
399    /// Steps 2-4 only happen once the cross-signing reset has been authorized,
400    /// so cancelling or failing the authentication leaves backups and recovery
401    /// untouched.
402    ///
403    /// Disclaimer: failures in this flow will potentially leave the user in an
404    /// inconsistent state but they're expected to just run the reset flow again
405    /// as presumably the reason they started it to begin with was that they no
406    /// longer had access to any of their data.
407    ///
408    /// # Examples
409    ///
410    /// ```no_run
411    /// # use matrix_sdk::{
412    ///     encryption::recovery, encryption::CrossSigningResetAuthType, Client,
413    ///   };
414    /// # use url::Url;
415    /// # async {
416    /// # let homeserver = Url::parse("http://example.com")?;
417    /// # let client = Client::new(homeserver).await?;
418    /// # let user_id = unimplemented!();
419    /// let encryption = client.encryption();
420    ///
421    /// if let Some(handle) = encryption.recovery().reset_identity().await? {
422    ///     match handle.auth_type() {
423    ///         CrossSigningResetAuthType::Uiaa(uiaa) => {
424    ///             let password = "1234".to_owned();
425    ///
426    ///             handle.reset(uiaa.as_password_auth_data(user_id, password)).await?;
427    ///         }
428    ///         CrossSigningResetAuthType::OAuth(oauth) => {
429    ///             println!(
430    ///                 "To reset your end-to-end encryption cross-signing identity, \
431    ///                 you first need to approve it at {}",
432    ///                 oauth.approval_url
433    ///             );
434    ///             handle.reset(oauth.as_auth_data()).await?;
435    ///         }
436    ///     }
437    /// }
438    /// # anyhow::Ok(()) };
439    /// ```
440    pub async fn reset_identity(&self) -> Result<Option<IdentityResetHandle>> {
441        // 1. Reset cross-signing first, it may require authentication. If the
442        // user cancels or fails the authentication we don't want to have
443        // deleted their backup and recovery already.
444        let cross_signing_reset_handle = self.client.encryption().reset_cross_signing().await?;
445
446        if let Some(handle) = cross_signing_reset_handle {
447            // Authentication required, the rest of the reset happens in
448            // [`IdentityResetHandle::reset`] once it succeeds.
449            Ok(Some(IdentityResetHandle {
450                client: self.client.clone(),
451                cross_signing_reset_handle: handle,
452            }))
453        } else {
454            self.reset_backup_and_recovery().await?;
455
456            Ok(None)
457        }
458    }
459
460    /// Carry out the remaining steps of [`Recovery::reset_identity`] after a
461    /// successful cross-signing reset:
462    ///
463    /// 1. Disable backing up room keys and delete the active backup
464    /// 2. Disable recovery and delete secret storage
465    /// 3. Re-enable key backups, but only if they were enabled before
466    ///
467    /// This must only be called once the cross-signing reset has been
468    /// committed. Deleting the backup and recovery any earlier would leave the
469    /// user without either if they cancel or fail the reset's authentication.
470    async fn reset_backup_and_recovery(&self) -> Result<()> {
471        self.client.encryption().backups().disable_and_delete().await?; // 1.
472
473        // 2. (We can't delete account data events)
474        self.client.account().set_account_data(SecretStorageDisabledContent {}).await?;
475        self.update_recovery_state().await?;
476
477        if self.should_auto_enable_backups().await? {
478            self.enable_backup().await?; // 3.
479        }
480
481        Ok(())
482    }
483
484    /// Recover all the secrets from the homeserver.
485    ///
486    /// This method is a convenience method around the
487    /// [`SecretStore::import_secrets()`] method, please read the documentation
488    /// of this method for more information about what happens if you call this
489    /// method.
490    ///
491    /// In short, this method will turn a newly created [`Client`] into a fully
492    /// end-to-end encryption enabled client.
493    ///
494    /// # Examples
495    ///
496    /// ```no_run
497    /// # use matrix_sdk::{Client, encryption::recovery::RecoveryState};
498    /// # use url::Url;
499    /// # async {
500    /// # let homeserver = Url::parse("http://example.com")?;
501    /// # let client = Client::new(homeserver).await?;
502    /// let recovery = client.encryption().recovery();
503    ///
504    /// recovery.recover("my recovery key or passphrase").await;
505    ///
506    /// assert_eq!(recovery.state(), RecoveryState::Enabled);
507    /// # anyhow::Ok(()) };
508    /// ```
509    #[instrument(skip_all)]
510    pub async fn recover(&self, recovery_key: &str) -> Result<()> {
511        let store =
512            self.client.encryption().secret_storage().open_secret_store(recovery_key).await?;
513
514        store.import_secrets().await?;
515        self.update_recovery_state().await?;
516
517        Ok(())
518    }
519
520    /// Recover all the secrets from the homeserver, and, if the key backup
521    /// information is inconsistent, create a new key backup.
522    ///
523    /// Please read the documentation for [`SecretStore::import_secrets()`] for
524    /// more information about the recovery of identity information.
525    ///
526    /// This will create a new key backup if:
527    ///
528    /// - Key backup is enabled and the backup decryption key is missing from
529    ///   Recovery, or
530    /// - Key backup is enabled and the backup decryption key does not match the
531    ///   public key
532    ///
533    /// # Examples
534    ///
535    /// ```no_run
536    /// # use matrix_sdk::{Client, encryption::recovery::RecoveryState};
537    /// # use url::Url;
538    /// # async {
539    /// # let homeserver = Url::parse("http://example.com")?;
540    /// # let client = Client::new(homeserver).await?;
541    /// let recovery = client.encryption().recovery();
542    ///
543    /// recovery.recover_and_fix_backup("my recovery key or passphrase").await;
544    ///
545    /// assert_eq!(recovery.state(), RecoveryState::Enabled);
546    /// # anyhow::Ok(()) };
547    /// ```
548    #[instrument(skip_all)]
549    pub async fn recover_and_fix_backup(&self, recovery_key: &str) -> Result<()> {
550        let store =
551            self.client.encryption().secret_storage().open_secret_store(recovery_key).await?;
552
553        let delete_and_recreate_backup = match store.import_secrets().await {
554            Ok(()) => false,
555            Err(SecretStorageError::InconsistentBackupDecryptionKey) => {
556                warn!(
557                    "Key storage decryption key does not match the current backup - creating a new key backup"
558                );
559                true
560            }
561            Err(SecretStorageError::MissingOrInvalidBackupDecryptionKey) => {
562                warn!("Missing or invalid backup decryption key - creating a new key backup");
563                true
564            }
565            Err(e) => return Err(e.into()),
566        };
567
568        if delete_and_recreate_backup {
569            self.client.encryption().backups().disable_and_delete().await?;
570            self.enable_backup().await?;
571            store.export_secrets().await?;
572        }
573
574        self.update_recovery_state().await?;
575
576        Ok(())
577    }
578
579    /// Is this device the last device the user has?
580    ///
581    /// This method is useful to check if we should recommend to the user that
582    /// they should enable recovery, typically done before logging out.
583    ///
584    /// If the user does not enable recovery before logging out of their last
585    /// device, they will not be able to decrypt historic messages once they
586    /// create a new device.
587    pub async fn is_last_device(&self) -> Result<bool> {
588        let olm_machine = self.client.olm_machine().await;
589        let olm_machine = olm_machine.as_ref().ok_or(crate::Error::NoOlmMachine)?;
590        let user_id = olm_machine.user_id();
591
592        self.client.encryption().ensure_initial_key_query().await?;
593
594        let devices = self.client.encryption().get_user_devices(user_id).await?;
595
596        Ok(devices.devices().count() == 1)
597    }
598
599    /// Did we correctly set up cross-signing and backups?
600    async fn all_known_secrets_available(&self) -> Result<bool> {
601        // Cross-signing state is fine if we have all the private cross-signing
602        // keys, as indicated in the status.
603        let cross_signing_complete = self
604            .client
605            .encryption()
606            .cross_signing_status()
607            .await
608            .map(|status| status.is_complete());
609        if !cross_signing_complete.unwrap_or_default() {
610            return Ok(false);
611        }
612
613        // The backup state is fine if we have backups enabled locally, or if
614        // backups have been marked as disabled.
615        if self.client.encryption().backups().are_enabled().await {
616            Ok(true)
617        } else {
618            self.are_backups_marked_as_disabled().await
619        }
620    }
621
622    async fn should_auto_enable_backups(&self) -> Result<bool> {
623        // If we didn't already enable backups, we don't see a backup version on
624        // the server, and finally if backups have not been marked to be
625        // explicitly disabled, then we can automatically enable them.
626        Ok(self.client.inner.e2ee.encryption_settings.auto_enable_backups
627            && !self.client.encryption().backups().are_enabled().await
628            && !self.client.encryption().backups().fetch_exists_on_server().await?
629            && !self.are_backups_marked_as_disabled().await?)
630    }
631
632    pub(crate) async fn setup(&self) -> Result<()> {
633        info!("Setting up account data listeners and trying to setup recovery");
634
635        self.client.add_event_handler(Self::default_key_event_handler);
636        self.client.add_event_handler(Self::secret_send_event_handler);
637        self.client.inner.e2ee.initialize_recovery_state_update_task(&self.client);
638
639        self.update_recovery_state().await?;
640
641        if self.should_auto_enable_backups().await? {
642            info!("Trying to automatically enable backups");
643
644            if let Err(e) = self.enable_backup().await {
645                warn!("Could not automatically enable backups: {e:?}");
646            }
647        }
648
649        Ok(())
650    }
651
652    /// Delete all the known secrets we are keeping in secret storage.
653    ///
654    /// The exact list of secrets is defined in [`Recovery::KNOWN_SECRETS`] and
655    /// might change over time.
656    ///
657    /// Since account data events can't actually be deleted, due to a missing
658    /// DELETE API, we're replacing the events with an empty
659    /// [`SecretEventContent`].
660    async fn delete_all_known_secrets(&self) -> Result<()> {
661        for secret_name in Self::KNOWN_SECRETS {
662            let event_type = GlobalAccountDataEventType::from(secret_name.to_owned());
663            let content = SecretEventContent::new(Default::default());
664            let secret_content = Raw::from_json(
665                to_raw_value(&content)
666                    .expect("We should be able to serialize a raw empty secret event content"),
667            );
668            self.client.account().set_account_data_raw(event_type, secret_content).await?;
669        }
670
671        Ok(())
672    }
673
674    /// Run a network request to figure whether backups have been disabled at
675    /// the account level.
676    async fn are_backups_marked_as_disabled(&self) -> Result<bool> {
677        if let Some(key_backup_content) =
678            self.client.account().fetch_account_data_static::<KeyBackupEventContent>().await?
679        {
680            Ok(key_backup_content.deserialize().map(|event| !event.enabled).unwrap_or(false))
681        } else {
682            Ok(self
683                .client
684                .account()
685                .fetch_account_data_static::<BackupDisabledContent>()
686                .await?
687                .map(|event| event.deserialize().map(|event| event.disabled).unwrap_or(false))
688                .unwrap_or(false))
689        }
690    }
691
692    async fn mark_backup_as_enabled(&self) -> Result<()> {
693        self.client.account().set_account_data(KeyBackupEventContent::new(true)).await?;
694
695        // Unstable prefix: will be removed when sufficient time has passed for
696        // clients to use the stable prefix.
697        self.client.account().set_account_data(BackupDisabledContent { disabled: false }).await?;
698
699        Ok(())
700    }
701
702    async fn check_recovery_state(&self) -> Result<RecoveryState> {
703        Ok(if self.client.encryption().secret_storage().is_enabled().await? {
704            if self.all_known_secrets_available().await? {
705                RecoveryState::Enabled
706            } else {
707                RecoveryState::Incomplete
708            }
709        } else {
710            RecoveryState::Disabled
711        })
712    }
713
714    async fn update_recovery_state(&self) -> Result<()> {
715        let new_state = self.check_recovery_state().await?;
716        let old_state = self.client.inner.e2ee.recovery_state.set(new_state);
717
718        if new_state != old_state {
719            info!("Recovery state changed from {old_state:?} to {new_state:?}");
720        }
721
722        Ok(())
723    }
724
725    async fn update_recovery_state_no_fail(&self) {
726        if let Err(e) = self.update_recovery_state().await {
727            error!("Couldn't update the recovery state: {e:?}");
728        }
729    }
730
731    #[instrument]
732    async fn secret_send_event_handler(_: ToDeviceSecretSendEvent, client: Client) {
733        client.encryption().recovery().update_recovery_state_no_fail().await;
734    }
735
736    #[instrument]
737    async fn default_key_event_handler(_: SecretStorageDefaultKeyEvent, client: Client) {
738        client.encryption().recovery().update_recovery_state_no_fail().await;
739    }
740
741    /// Listen for changes in the [`BackupState`] and, if necessary, update the
742    /// [`RecoveryState`] accordingly.
743    ///
744    /// This should not be called directly, this method is put into a background
745    /// task which is always listening for updates in the [`BackupState`].
746    pub(crate) fn update_state_after_backup_state_change(
747        client: &Client,
748    ) -> impl Future<Output = ()> + use<> {
749        let mut stream = client.encryption().backups().state_stream();
750        let weak = client.downgrade();
751
752        async move {
753            while let Some(update) = stream.next().await {
754                if let Some(client) = weak.get() {
755                    match update {
756                        Ok(update) => {
757                            // The recovery state only cares about these two
758                            // states, the intermediate states that tell us that
759                            // we're creating a backup are not interesting.
760                            if matches!(update, BackupState::Unknown | BackupState::Enabled) {
761                                client
762                                    .encryption()
763                                    .recovery()
764                                    .update_recovery_state_no_fail()
765                                    .await;
766                            }
767                        }
768                        Err(_) => {
769                            // We missed some updates, let's update our state in
770                            // case something changed.
771                            client.encryption().recovery().update_recovery_state_no_fail().await;
772                        }
773                    }
774                } else {
775                    break;
776                }
777            }
778        }
779    }
780
781    #[instrument(skip_all)]
782    pub(crate) async fn update_state_after_keys_query(&self, response: &get_keys::v3::Response) {
783        if let Some(user_id) = self.client.user_id()
784            && response.master_keys.contains_key(user_id)
785        {
786            // TODO: This is unnecessarily expensive, we could let the crypto
787            // crate notify us that our private keys got erased... But, the
788            // OlmMachine gets recreated and... You know the drill by now...
789            self.update_recovery_state_no_fail().await;
790        }
791    }
792}
793
794/// A helper struct that continues resetting a user's crypto identity after
795/// authentication was required, deleting backups and recovery and re-enabling
796/// backups (if necessary) at the end of it
797#[derive(Debug)]
798pub struct IdentityResetHandle {
799    client: Client,
800    cross_signing_reset_handle: CrossSigningResetHandle,
801}
802
803impl IdentityResetHandle {
804    /// Get the underlying [`CrossSigningResetAuthType`] this identity reset
805    /// process is using.
806    pub fn auth_type(&self) -> &CrossSigningResetAuthType {
807        &self.cross_signing_reset_handle.auth_type
808    }
809
810    /// This method will retry to upload the device keys after the previous try
811    /// failed due to required authentication, then delete backups and recovery
812    /// and re-enable backups if they were enabled before
813    pub async fn reset(&self, auth: AuthData) -> Result<()> {
814        // Only delete the backup and recovery if this call committed the
815        // reset. If it was cancelled, or a concurrent call won the race, no
816        // new identity was uploaded by us and there is nothing to clean up.
817        if self.cross_signing_reset_handle.auth(auth).await? {
818            self.client.encryption().recovery().reset_backup_and_recovery().await?;
819        }
820
821        Ok(())
822    }
823
824    /// Cancel the ongoing identity reset process
825    pub async fn cancel(&self) {
826        self.cross_signing_reset_handle.cancel().await;
827    }
828}
829
830// The http mocking library is not supported for wasm32
831#[cfg(all(test, not(target_family = "wasm")))]
832pub(crate) mod tests {
833    use assert_matches::assert_matches;
834    use matrix_sdk_test::async_test;
835    use ruma::{
836        events::{secret::request::SecretName, secret_storage::key},
837        serde::Base64,
838    };
839    use serde_json::json;
840
841    use super::Recovery;
842    use crate::{
843        encryption::{recovery::types::RecoveryError, secret_storage::SecretStorageError},
844        test_utils::mocks::MatrixMockServer,
845    };
846
847    // If recovery fails due when importing a secret from secret storage, we
848    // should get the `ImportError` variant of `SecretStorageError`. The
849    // following tests test different import failures.
850    #[async_test]
851    async fn test_recover_with_no_cross_signing_key() {
852        let server = MatrixMockServer::new().await;
853        let client = server.client_builder().build().await;
854
855        server
856            .mock_get_secret_storage_key()
857            .ok(
858                client.user_id().unwrap(),
859                &key::SecretStorageKeyEventContent::new(
860                    "abc".into(),
861                    key::SecretStorageEncryptionAlgorithm::V1AesHmacSha2(
862                        key::SecretStorageV1AesHmacSha2Properties::new(
863                            Some(Base64::parse("xv5b6/p3ExEw++wTyfSHEg==").unwrap()),
864                            Some(
865                                Base64::parse("ujBBbXahnTAMkmPUX2/0+VTfUh63pGyVRuBcDMgmJC8=")
866                                    .unwrap(),
867                            ),
868                        ),
869                    ),
870                ),
871            )
872            .mount()
873            .await;
874        server
875            .mock_get_default_secret_storage_key()
876            .ok(client.user_id().unwrap(), "abc")
877            .mount()
878            .await;
879
880        let recovery = Recovery { client };
881
882        let ret =
883            recovery.recover("EsTj 3yST y93F SLpB jJsz eAXc 2XzA ygD3 w69H fGaN TKBj jXEd").await;
884
885        assert_matches!(
886            ret,
887            Err(RecoveryError::SecretStorage(SecretStorageError::ImportError {
888                name: SecretName::CrossSigningMasterKey,
889                error: _
890            }))
891        );
892    }
893
894    #[async_test]
895    async fn test_recover_with_invalid_cross_signing_key() {
896        let server = MatrixMockServer::new().await;
897        let client = server.client_builder().build().await;
898
899        server
900            .mock_get_secret_storage_key()
901            .ok(
902                client.user_id().unwrap(),
903                &key::SecretStorageKeyEventContent::new(
904                    "abc".into(),
905                    key::SecretStorageEncryptionAlgorithm::V1AesHmacSha2(
906                        key::SecretStorageV1AesHmacSha2Properties::new(
907                            Some(Base64::parse("xv5b6/p3ExEw++wTyfSHEg==").unwrap()),
908                            Some(
909                                Base64::parse("ujBBbXahnTAMkmPUX2/0+VTfUh63pGyVRuBcDMgmJC8=")
910                                    .unwrap(),
911                            ),
912                        ),
913                    ),
914                ),
915            )
916            .mount()
917            .await;
918        server
919            .mock_get_default_secret_storage_key()
920            .ok(client.user_id().unwrap(), "abc")
921            .mount()
922            .await;
923        server.mock_get_master_signing_key().ok(client.user_id().unwrap(), json!({})).mount().await;
924
925        let recovery = Recovery { client };
926
927        let ret =
928            recovery.recover("EsTj 3yST y93F SLpB jJsz eAXc 2XzA ygD3 w69H fGaN TKBj jXEd").await;
929
930        assert_matches!(
931            ret,
932            Err(RecoveryError::SecretStorage(SecretStorageError::ImportError {
933                name: SecretName::CrossSigningMasterKey,
934                error: _
935            }))
936        );
937    }
938
939    #[async_test]
940    async fn test_recover_with_undecryptable_cross_signing_key() {
941        let server = MatrixMockServer::new().await;
942        let client = server.client_builder().build().await;
943
944        server
945            .mock_get_secret_storage_key()
946            .ok(
947                client.user_id().unwrap(),
948                &key::SecretStorageKeyEventContent::new(
949                    "abc".into(),
950                    key::SecretStorageEncryptionAlgorithm::V1AesHmacSha2(
951                        key::SecretStorageV1AesHmacSha2Properties::new(
952                            Some(Base64::parse("xv5b6/p3ExEw++wTyfSHEg==").unwrap()),
953                            Some(
954                                Base64::parse("ujBBbXahnTAMkmPUX2/0+VTfUh63pGyVRuBcDMgmJC8=")
955                                    .unwrap(),
956                            ),
957                        ),
958                    ),
959                ),
960            )
961            .mount()
962            .await;
963        server
964            .mock_get_default_secret_storage_key()
965            .ok(client.user_id().unwrap(), "abc")
966            .mount()
967            .await;
968        server
969            .mock_get_master_signing_key()
970            .ok(
971                client.user_id().unwrap(),
972                json!({
973                    "encrypted": {
974                        "abc": {
975                            "iv": "xv5b6/p3ExEw++wTyfSHEg==",
976                            "mac": "ujBBbXahnTAMkmPUX2/0+VTfUh63pGyVRuBcDMgmJC8=",
977                            "ciphertext": "abcd"
978                        }
979                    }
980                }),
981            )
982            .mount()
983            .await;
984
985        let recovery = Recovery { client };
986
987        let ret =
988            recovery.recover("EsTj 3yST y93F SLpB jJsz eAXc 2XzA ygD3 w69H fGaN TKBj jXEd").await;
989
990        assert_matches!(
991            ret,
992            Err(RecoveryError::SecretStorage(SecretStorageError::ImportError {
993                name: SecretName::CrossSigningMasterKey,
994                error: _
995            }))
996        );
997    }
998}