Skip to main content

matrix_sdk_crypto/backups/
mod.rs

1// Copyright 2021, 2022 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//! Server-side backup support for room keys
16//!
17//! This module largely implements support for server-side backups using the
18//! `m.megolm_backup.v1.curve25519-aes-sha2` backup algorithm.
19//!
20//! Due to various flaws in this backup algorithm it is **not** recommended to
21//! use this module or any of its functionality. The module is only provided for
22//! backwards compatibility.
23//!
24//! [spec]: https://spec.matrix.org/unstable/client-server-api/#server-side-key-backups
25
26use std::{
27    collections::{BTreeMap, BTreeSet},
28    sync::Arc,
29};
30
31use ruma::{
32    DeviceId, DeviceKeyAlgorithm, OwnedDeviceId, OwnedRoomId, OwnedTransactionId, RoomId,
33    TransactionId, api::client::backup::RoomKeyBackup, serde::Raw,
34};
35use tokio::sync::RwLock;
36use tracing::{debug, info, instrument, trace, warn};
37
38use crate::{
39    CryptoStoreError, Device, RoomKeyImportResult, SignatureError,
40    olm::{BackedUpRoomKey, ExportedRoomKey, InboundGroupSession, SignedJsonObject},
41    store::{
42        Store,
43        types::{BackupDecryptionKey, BackupKeys, Changes, RoomKeyCounts},
44    },
45    types::{MegolmV1AuthData, RoomKeyBackupInfo, Signatures, requests::KeysBackupRequest},
46};
47
48mod keys;
49
50pub use keys::{DecodeError, DecryptionError, MegolmV1BackupKey};
51
52/// A state machine that handles backing up room keys.
53///
54/// The state machine can be activated using the
55/// [`BackupMachine::enable_backup_v1`] method. After the state machine has been
56/// enabled a request that will upload encrypted room keys can be generated
57/// using the [`BackupMachine::backup`] method.
58#[derive(Debug, Clone)]
59pub struct BackupMachine {
60    store: Store,
61    backup_key: Arc<RwLock<Option<MegolmV1BackupKey>>>,
62    pending_backup: Arc<RwLock<Option<PendingBackup>>>,
63}
64
65type SenderKey = String;
66type SessionId = String;
67
68#[derive(Debug, Clone)]
69struct PendingBackup {
70    request_id: OwnedTransactionId,
71    request: KeysBackupRequest,
72    sessions: BTreeMap<OwnedRoomId, BTreeMap<SenderKey, BTreeSet<SessionId>>>,
73}
74
75/// The result of a signature verification of a signed JSON object.
76#[derive(Clone, Debug, Default, PartialEq, Eq)]
77pub struct SignatureVerification {
78    /// The result of the signature verification using the public key of our own
79    /// device.
80    pub device_signature: SignatureState,
81    /// The result of the signature verification using the public key of our own
82    /// user identity.
83    pub user_identity_signature: SignatureState,
84    /// The result of the signature verification using public keys of other
85    /// devices we own.
86    pub other_signatures: BTreeMap<OwnedDeviceId, SignatureState>,
87}
88
89impl SignatureVerification {
90    /// Is the result considered to be trusted?
91    ///
92    /// This tells us if the result has a valid signature from any of the
93    /// following:
94    ///
95    /// * Our own device
96    /// * Our own user identity, provided the identity is trusted as well
97    /// * Any of our own devices, provided the device is trusted as well
98    pub fn trusted(&self) -> bool {
99        self.device_signature.trusted()
100            || self.user_identity_signature.trusted()
101            || self.other_signatures.values().any(|s| s.trusted())
102    }
103}
104
105/// The result of a signature check.
106#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
107#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
108pub enum SignatureState {
109    /// The signature is missing.
110    #[default]
111    Missing,
112    /// The signature is invalid.
113    Invalid,
114    /// The signature is valid but the device or user identity that created the
115    /// signature is not trusted.
116    ValidButNotTrusted,
117    /// The signature is valid and the device or user identity that created the
118    /// signature is trusted.
119    ValidAndTrusted,
120}
121
122impl SignatureState {
123    /// Is the state considered to be trusted?
124    pub fn trusted(self) -> bool {
125        self == SignatureState::ValidAndTrusted
126    }
127
128    /// Did we find a valid signature?
129    pub fn signed(self) -> bool {
130        self == SignatureState::ValidButNotTrusted && self == SignatureState::ValidAndTrusted
131    }
132}
133
134impl BackupMachine {
135    const BACKUP_BATCH_SIZE: usize = 100;
136
137    pub(crate) fn new(store: Store, backup_key: Option<MegolmV1BackupKey>) -> Self {
138        Self {
139            store,
140            backup_key: RwLock::new(backup_key).into(),
141            pending_backup: RwLock::new(None).into(),
142        }
143    }
144
145    /// Are we able to back up room keys to the server?
146    pub async fn enabled(&self) -> bool {
147        self.backup_key.read().await.as_ref().is_some_and(|b| b.backup_version().is_some())
148    }
149
150    /// Check if our own device has signed the given signed JSON payload.
151    fn check_own_device_signature(
152        &self,
153        signatures: &Signatures,
154        auth_data: &str,
155    ) -> SignatureState {
156        match self.store.static_account().has_signed_raw(signatures, auth_data) {
157            Ok(_) => SignatureState::ValidAndTrusted,
158            Err(e) => match e {
159                SignatureError::NoSignatureFound => SignatureState::Missing,
160                _ => SignatureState::Invalid,
161            },
162        }
163    }
164
165    /// Check if our own cross-signing user identity has signed the given signed
166    /// JSON payload.
167    async fn check_own_identity_signature(
168        &self,
169        signatures: &Signatures,
170        auth_data: &str,
171    ) -> Result<SignatureState, CryptoStoreError> {
172        let user_id = &self.store.static_account().user_id;
173        let identity = self.store.get_identity(user_id).await?;
174
175        let ret = if let Some(identity) = identity.and_then(|i| i.own()) {
176            match identity.master_key().has_signed_raw(signatures, auth_data) {
177                Ok(_) => {
178                    if identity.is_verified() {
179                        SignatureState::ValidAndTrusted
180                    } else {
181                        SignatureState::ValidButNotTrusted
182                    }
183                }
184                Err(e) => match e {
185                    SignatureError::NoSignatureFound => SignatureState::Missing,
186                    _ => SignatureState::Invalid,
187                },
188            }
189        } else {
190            SignatureState::Missing
191        };
192
193        Ok(ret)
194    }
195
196    /// Check if the signed JSON payload `auth_data` has been signed by the
197    /// `device`.
198    fn backup_signed_by_device(
199        &self,
200        device: Device,
201        signatures: &Signatures,
202        auth_data: &str,
203    ) -> SignatureState {
204        if device.has_signed_raw(signatures, auth_data).is_ok() {
205            if device.is_verified() {
206                SignatureState::ValidAndTrusted
207            } else {
208                SignatureState::ValidButNotTrusted
209            }
210        } else {
211            SignatureState::Invalid
212        }
213    }
214
215    /// Check if the signed JSON payload `auth_data` has been signed by any of
216    /// our devices.
217    async fn test_device_signatures(
218        &self,
219        signatures: &Signatures,
220        auth_data: &str,
221        compute_all_signatures: bool,
222    ) -> Result<BTreeMap<OwnedDeviceId, SignatureState>, CryptoStoreError> {
223        let mut result = BTreeMap::new();
224
225        if let Some(user_signatures) = signatures.get(&self.store.static_account().user_id) {
226            for device_key_id in user_signatures.keys() {
227                if device_key_id.algorithm() == DeviceKeyAlgorithm::Ed25519 {
228                    let device_id = device_key_id.key_name();
229
230                    // No need to check our own device here, we're doing that using
231                    // the check_own_device_signature().
232                    if device_id == self.store.static_account().device_id {
233                        continue;
234                    }
235
236                    let state = self
237                        .test_ed25519_device_signature(device_id, signatures, auth_data)
238                        .await?;
239
240                    result.insert(device_id.to_owned(), state);
241
242                    // Abort the loop if we found a trusted and valid signature,
243                    // unless we should check all of them.
244                    if state.trusted() && !compute_all_signatures {
245                        break;
246                    }
247                }
248            }
249        }
250
251        Ok(result)
252    }
253
254    async fn test_ed25519_device_signature(
255        &self,
256        device_id: &DeviceId,
257        signatures: &Signatures,
258        auth_data: &str,
259    ) -> Result<SignatureState, CryptoStoreError> {
260        // We might iterate over some non-device signatures as well, but in this
261        // case there's no corresponding device and we get `Ok(None)` here, so
262        // things still work out.
263        let device = self.store.get_device(self.store.user_id(), device_id).await?;
264        trace!(?device_id, "Checking backup auth data for device");
265
266        if let Some(device) = device {
267            Ok(self.backup_signed_by_device(device, signatures, auth_data))
268        } else {
269            trace!(?device_id, "Device not found, can't check signature");
270            Ok(SignatureState::Missing)
271        }
272    }
273
274    async fn verify_auth_data_v1(
275        &self,
276        auth_data: MegolmV1AuthData,
277        compute_all_signatures: bool,
278    ) -> Result<SignatureVerification, CryptoStoreError> {
279        let serialized_auth_data = match auth_data.to_canonical_json() {
280            Ok(s) => s,
281            Err(e) => {
282                warn!(error =? e, "Error while verifying backup, can't canonicalize auth data");
283                return Ok(Default::default());
284            }
285        };
286
287        // Check if there's a signature from our own device.
288        let device_signature =
289            self.check_own_device_signature(&auth_data.signatures, &serialized_auth_data);
290        // Check if there's a signature from our own user identity.
291        let user_identity_signature =
292            self.check_own_identity_signature(&auth_data.signatures, &serialized_auth_data).await?;
293
294        // Collect all the other signatures if there isn't already a valid one,
295        // or if we're told to collect all of them anyways.
296        let other_signatures = if !(device_signature.trusted() || user_identity_signature.trusted())
297            || compute_all_signatures
298        {
299            self.test_device_signatures(
300                &auth_data.signatures,
301                &serialized_auth_data,
302                compute_all_signatures,
303            )
304            .await?
305        } else {
306            Default::default()
307        };
308
309        Ok(SignatureVerification { device_signature, user_identity_signature, other_signatures })
310    }
311
312    /// Verify some backup info that we downloaded from the server.
313    ///
314    /// # Arguments
315    ///
316    /// * `backup_info`: The backup info that should be verified. Should be
317    ///   fetched from the server using the [`/room_keys/version`] endpoint.
318    ///
319    /// * `compute_all_signatures`: *Useful for debugging only*. If this
320    ///   parameter is `true`, the internal machinery will compute the trust
321    ///   state for all signatures before returning, instead of short-circuiting
322    ///   on the first trusted signature. Has no impact on whether the backup
323    ///   will be considered verified.
324    ///
325    /// [`/room_keys/version`]: https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3room_keysversion
326    pub async fn verify_backup(
327        &self,
328        backup_info: RoomKeyBackupInfo,
329        compute_all_signatures: bool,
330    ) -> Result<SignatureVerification, CryptoStoreError> {
331        trace!(?backup_info, "Verifying backup auth data");
332
333        if let RoomKeyBackupInfo::MegolmBackupV1Curve25519AesSha2(data) = backup_info {
334            self.verify_auth_data_v1(data, compute_all_signatures).await
335        } else {
336            Ok(Default::default())
337        }
338    }
339
340    /// Sign a [`RoomKeyBackupInfo`] using the device's identity key and, if
341    /// available, the cross-signing master key.
342    ///
343    /// # Arguments
344    ///
345    /// * `backup_info`: The backup version that should be verified. Should be
346    ///   created from the [`BackupDecryptionKey`] using the
347    ///   [`BackupDecryptionKey::to_backup_info()`] method.
348    pub async fn sign_backup(
349        &self,
350        backup_info: &mut RoomKeyBackupInfo,
351    ) -> Result<(), SignatureError> {
352        if let RoomKeyBackupInfo::MegolmBackupV1Curve25519AesSha2(data) = backup_info {
353            let canonical_json = data.to_canonical_json()?;
354
355            let private_identity = self.store.private_identity();
356            let identity = private_identity.lock().await;
357
358            if let Some(key_id) = identity.master_key_id().await
359                && let Ok(signature) = identity.sign(&canonical_json).await
360            {
361                data.signatures.add_signature(self.store.user_id().to_owned(), key_id, signature);
362            }
363
364            let cache = self.store.cache().await?;
365            let account = cache.account().await?;
366            let key_id = account.signing_key_id();
367            let signature = account.sign(&canonical_json);
368            data.signatures.add_signature(self.store.user_id().to_owned(), key_id, signature);
369
370            Ok(())
371        } else {
372            Err(SignatureError::UnsupportedAlgorithm)
373        }
374    }
375
376    /// Activate the given backup key to be used to encrypt and backup room
377    /// keys.
378    ///
379    /// This will use the [`m.megolm_backup.v1.curve25519-aes-sha2`] algorithm
380    /// to encrypt the room keys.
381    ///
382    /// [`m.megolm_backup.v1.curve25519-aes-sha2`]:
383    /// https://spec.matrix.org/unstable/client-server-api/#backup-algorithm-mmegolm_backupv1curve25519-aes-sha2
384    pub async fn enable_backup_v1(&self, key: MegolmV1BackupKey) -> Result<(), CryptoStoreError> {
385        if key.backup_version().is_some() {
386            *self.backup_key.write().await = Some(key.clone());
387            info!(backup_key = ?key, "Activated a backup");
388        } else {
389            warn!(backup_key = ?key, "Tried to activate a backup without having the backup key uploaded");
390        }
391
392        Ok(())
393    }
394
395    /// Get the number of backed up room keys and the total number of room keys.
396    pub async fn room_key_counts(&self) -> Result<RoomKeyCounts, CryptoStoreError> {
397        let backup_version = self.backup_key.read().await.as_ref().and_then(|k| k.backup_version());
398        self.store.inbound_group_session_counts(backup_version.as_deref()).await
399    }
400
401    /// Disable and reset our backup state.
402    ///
403    /// This will remove any pending backup request, remove the backup key and
404    /// reset the backup state of each room key we have.
405    #[instrument(skip(self))]
406    pub async fn disable_backup(&self) -> Result<(), CryptoStoreError> {
407        debug!("Disabling key backup and resetting backup state for room keys");
408
409        self.backup_key.write().await.take();
410        self.pending_backup.write().await.take();
411
412        self.store.reset_backup_state().await?;
413
414        debug!("Done disabling backup");
415
416        Ok(())
417    }
418
419    /// Provide the `backup_version` of the current `backup_key`, or None if
420    /// there is no current key, or the key is not used with any backup
421    /// version.
422    pub async fn backup_version(&self) -> Option<String> {
423        self.backup_key.read().await.as_ref().and_then(|k| k.backup_version())
424    }
425
426    /// Store the backup decryption key in the crypto store.
427    ///
428    /// This is useful if the client wants to support gossiping of the backup
429    /// key.
430    pub async fn save_decryption_key(
431        &self,
432        backup_decryption_key: Option<BackupDecryptionKey>,
433        version: Option<String>,
434    ) -> Result<(), CryptoStoreError> {
435        let changes =
436            Changes { backup_decryption_key, backup_version: version, ..Default::default() };
437        self.store.save_changes(changes).await
438    }
439
440    /// Get the backup keys we have saved in our crypto store.
441    pub async fn get_backup_keys(&self) -> Result<BackupKeys, CryptoStoreError> {
442        self.store.load_backup_keys().await
443    }
444
445    /// Encrypt a batch of room keys and return a request that needs to be sent
446    /// out to backup the room keys.
447    pub async fn backup(
448        &self,
449    ) -> Result<Option<(OwnedTransactionId, KeysBackupRequest)>, CryptoStoreError> {
450        let mut request = self.pending_backup.write().await;
451
452        if let Some(request) = &*request {
453            trace!("Backing up, returning an existing request");
454
455            Ok(Some((request.request_id.clone(), request.request.clone())))
456        } else {
457            trace!("Backing up, creating a new request");
458
459            let new_request = self.backup_helper().await?;
460            *request = new_request.clone();
461
462            Ok(new_request.map(|r| (r.request_id, r.request)))
463        }
464    }
465
466    pub(crate) async fn mark_request_as_sent(
467        &self,
468        request_id: &TransactionId,
469    ) -> Result<(), CryptoStoreError> {
470        let mut request = self.pending_backup.write().await;
471        if let Some(r) = &*request {
472            if r.request_id == request_id {
473                let room_and_session_ids: Vec<(&RoomId, &str)> = r
474                    .sessions
475                    .iter()
476                    .flat_map(|(room_id, sender_key_to_session_ids)| {
477                        std::iter::repeat(room_id).zip(sender_key_to_session_ids.values().flatten())
478                    })
479                    .map(|(room_id, session_id)| (room_id.as_ref(), session_id.as_str()))
480                    .collect();
481
482                trace!(request_id = ?r.request_id, keys = ?r.sessions, "Marking room keys as backed up");
483
484                self.store
485                    .mark_inbound_group_sessions_as_backed_up(
486                        &r.request.version,
487                        &room_and_session_ids,
488                    )
489                    .await?;
490
491                trace!(
492                    request_id = ?r.request_id,
493                    keys = ?r.sessions,
494                    "Marked room keys as backed up"
495                );
496
497                *request = None;
498            } else {
499                warn!(
500                    expected = ?r.request_id,
501                    got = ?request_id,
502                    "Tried to mark a pending backup as sent but the request id didn't match"
503                );
504            }
505        } else {
506            warn!(
507                ?request_id,
508                "Tried to mark a pending backup as sent but there isn't a backup pending"
509            );
510        }
511
512        Ok(())
513    }
514
515    async fn backup_helper(&self) -> Result<Option<PendingBackup>, CryptoStoreError> {
516        let Some(backup_key) = &*self.backup_key.read().await else {
517            warn!("Trying to backup room keys but no backup key was found");
518            return Ok(None);
519        };
520
521        let Some(version) = backup_key.backup_version() else {
522            warn!("Trying to backup room keys but the backup key wasn't uploaded");
523            return Ok(None);
524        };
525
526        let sessions =
527            self.store.inbound_group_sessions_for_backup(&version, Self::BACKUP_BATCH_SIZE).await?;
528
529        if sessions.is_empty() {
530            trace!(?backup_key, "No room keys need to be backed up");
531            return Ok(None);
532        }
533
534        let key_count = sessions.len();
535        let (backup, session_record) = Self::backup_keys(sessions, backup_key).await?;
536
537        info!(
538            key_count = key_count,
539            keys = ?session_record,
540            ?backup_key,
541            "Successfully created a room keys backup request"
542        );
543
544        let request = PendingBackup {
545            request_id: TransactionId::new(),
546            request: KeysBackupRequest { version, rooms: backup },
547            sessions: session_record,
548        };
549
550        Ok(Some(request))
551    }
552
553    /// Backup all the non-backed up room keys we know about
554    async fn backup_keys(
555        sessions: Vec<InboundGroupSession>,
556        backup_key: &MegolmV1BackupKey,
557    ) -> Result<
558        (
559            BTreeMap<OwnedRoomId, RoomKeyBackup>,
560            BTreeMap<OwnedRoomId, BTreeMap<SenderKey, BTreeSet<SessionId>>>,
561        ),
562        vodozemac::pk_encryption::Error,
563    > {
564        let mut backup: BTreeMap<OwnedRoomId, RoomKeyBackup> = BTreeMap::new();
565        let mut session_record: BTreeMap<OwnedRoomId, BTreeMap<SenderKey, BTreeSet<SessionId>>> =
566            BTreeMap::new();
567
568        for session in sessions {
569            let room_id = session.room_id().to_owned();
570            let session_id = session.session_id().to_owned();
571            let sender_key = session.sender_key().to_owned();
572            let session = backup_key.encrypt(session).await?;
573
574            session_record
575                .entry(room_id.to_owned())
576                .or_default()
577                .entry(sender_key.to_base64())
578                .or_default()
579                .insert(session_id.clone());
580
581            let session = Raw::new(&session).expect("Can't serialize a backed up room key");
582
583            backup
584                .entry(room_id)
585                .or_insert_with(|| RoomKeyBackup::new(BTreeMap::new()))
586                .sessions
587                .insert(session_id, session);
588        }
589
590        Ok((backup, session_record))
591    }
592
593    /// Import the given room keys into our store.
594    ///
595    /// # Arguments
596    ///
597    /// * `room_keys` - A list of previously exported keys that should be
598    ///   imported into our store. If we already have a better version of a key
599    ///   the key will *not* be imported.
600    ///
601    /// Returns a [`RoomKeyImportResult`] containing information about room keys
602    /// which were imported.
603    #[deprecated(note = "Use the OlmMachine::store::import_room_keys method instead")]
604    pub async fn import_backed_up_room_keys(
605        &self,
606        room_keys: BTreeMap<OwnedRoomId, BTreeMap<String, BackedUpRoomKey>>,
607        progress_listener: impl Fn(usize, usize),
608    ) -> Result<RoomKeyImportResult, CryptoStoreError> {
609        let mut decrypted_room_keys = vec![];
610
611        for (room_id, room_keys) in room_keys {
612            for (session_id, room_key) in room_keys {
613                let room_key = ExportedRoomKey::from_backed_up_room_key(
614                    room_id.to_owned(),
615                    session_id,
616                    room_key,
617                );
618
619                decrypted_room_keys.push(room_key);
620            }
621        }
622
623        // FIXME: This method is a bit flawed: we have no real idea which backup version
624        //   these keys came from. For example, we might have reset the backup
625        //   since the keys were downloaded. For now, let's assume they came from
626        //   the "current" backup version.
627        let backup_version = self.backup_version().await;
628
629        self.store
630            .import_room_keys(decrypted_room_keys, backup_version.as_deref(), progress_listener)
631            .await
632    }
633}
634
635#[cfg(test)]
636mod tests {
637    use std::collections::BTreeMap;
638
639    use assert_matches2::assert_let;
640    use matrix_sdk_test::async_test;
641    use ruma::{CanonicalJsonValue, DeviceId, RoomId, UserId, device_id, room_id, user_id};
642    use serde_json::json;
643
644    use super::BackupMachine;
645    use crate::{
646        OlmError, OlmMachine, OlmMachineBuilder,
647        olm::BackedUpRoomKey,
648        store::{
649            CryptoStore, MemoryStore,
650            types::{BackupDecryptionKey, Changes},
651        },
652        types::RoomKeyBackupInfo,
653    };
654
655    fn room_key() -> BackedUpRoomKey {
656        let json = json!({
657            "algorithm": "m.megolm.v1.aes-sha2",
658            "sender_key": "DeHIg4gwhClxzFYcmNntPNF9YtsdZbmMy8+3kzCMXHA",
659            "session_key": "AQAAAABvWMNZjKFtebYIePKieQguozuoLgzeY6wKcyJjLJcJtQgy1dPqTBD12U+XrYLrRHn\
660                            lKmxoozlhFqJl456+9hlHCL+yq+6ScFuBHtJepnY1l2bdLb4T0JMDkNsNErkiLiLnD6yp3J\
661                            DSjIhkdHxmup/huygrmroq6/L5TaThEoqvW4DPIuO14btKudsS34FF82pwjKS4p6Mlch+0e\
662                            fHAblQV",
663            "sender_claimed_keys":{},
664            "forwarding_curve25519_key_chain":[]
665        });
666
667        serde_json::from_value(json)
668            .expect("We should be able to deserialize our backed up room key")
669    }
670
671    fn alice_id() -> &'static UserId {
672        user_id!("@alice:example.org")
673    }
674
675    fn alice_device_id() -> &'static DeviceId {
676        device_id!("JLAFKJWSCS")
677    }
678
679    fn room_id() -> &'static RoomId {
680        room_id!("!test:localhost")
681    }
682
683    fn room_id2() -> &'static RoomId {
684        room_id!("!test2:localhost")
685    }
686
687    async fn backup_flow(machine: OlmMachine) -> Result<(), OlmError> {
688        let backup_machine = machine.backup_machine();
689        let backup_version = current_backup_version(backup_machine).await;
690
691        let counts =
692            backup_machine.store.inbound_group_session_counts(backup_version.as_deref()).await?;
693
694        assert_eq!(counts.total, 0, "Initially no keys exist");
695        assert_eq!(counts.backed_up, 0, "Initially no backed up keys exist");
696
697        machine.create_outbound_group_session_with_defaults_test_helper(room_id()).await?;
698        machine.create_outbound_group_session_with_defaults_test_helper(room_id2()).await?;
699
700        let counts =
701            backup_machine.store.inbound_group_session_counts(backup_version.as_deref()).await?;
702        assert_eq!(counts.total, 2, "Two room keys need to exist in the store");
703        assert_eq!(counts.backed_up, 0, "No room keys have been backed up yet");
704
705        let decryption_key = BackupDecryptionKey::new();
706        let backup_key = decryption_key.megolm_v1_public_key();
707        backup_key.set_version("1".to_owned());
708
709        backup_machine.enable_backup_v1(backup_key).await?;
710
711        let (request_id, _) =
712            backup_machine.backup().await?.expect("Created a backup request successfully");
713        assert_eq!(
714            Some(&request_id),
715            backup_machine.backup().await?.as_ref().map(|(request_id, _)| request_id),
716            "Calling backup again without uploading creates the same backup request"
717        );
718
719        backup_machine.mark_request_as_sent(&request_id).await?;
720        let backup_version = current_backup_version(backup_machine).await;
721
722        let counts =
723            backup_machine.store.inbound_group_session_counts(backup_version.as_deref()).await?;
724        assert_eq!(counts.total, 2);
725        assert_eq!(counts.backed_up, 2, "All room keys have been backed up");
726
727        assert!(
728            backup_machine.backup().await?.is_none(),
729            "No room keys need to be backed up, no request needs to be created"
730        );
731
732        backup_machine.disable_backup().await?;
733        let backup_version = current_backup_version(backup_machine).await;
734
735        let counts =
736            backup_machine.store.inbound_group_session_counts(backup_version.as_deref()).await?;
737        assert_eq!(counts.total, 2);
738        assert_eq!(
739            counts.backed_up, 0,
740            "Disabling the backup resets the backup flag on the room keys"
741        );
742
743        Ok(())
744    }
745
746    async fn current_backup_version(backup_machine: &BackupMachine) -> Option<String> {
747        backup_machine.backup_key.read().await.as_ref().and_then(|k| k.backup_version())
748    }
749
750    #[async_test]
751    async fn test_memory_store_backups() -> Result<(), OlmError> {
752        let machine = OlmMachine::new(alice_id(), alice_device_id()).await;
753
754        backup_flow(machine).await
755    }
756
757    #[async_test]
758    async fn test_verify_auth_data() -> Result<(), OlmError> {
759        let machine = OlmMachine::new(alice_id(), alice_device_id()).await;
760        let backup_machine = machine.backup_machine();
761
762        let auth_data = json!({
763            "public_key":"XjhWTCjW7l59pbfx9tlCBQolfnIQWARoKOzjTOPSlWM",
764        });
765
766        let backup_version = json!({
767            "algorithm": "m.megolm_backup.v1.curve25519-aes-sha2",
768            "auth_data": auth_data,
769        });
770
771        let canonical_json: CanonicalJsonValue =
772            auth_data.clone().try_into().expect("Canonicalizing should always work");
773        let serialized = canonical_json.to_string();
774
775        let backup_version: RoomKeyBackupInfo = serde_json::from_value(backup_version).unwrap();
776
777        let state = backup_machine
778            .verify_backup(backup_version, false)
779            .await
780            .expect("Verifying should work");
781        assert!(!state.trusted());
782        assert!(!state.device_signature.trusted());
783        assert!(!state.user_identity_signature.trusted());
784        assert!(!state.other_signatures.values().any(|s| s.trusted()));
785
786        let signatures = machine.sign(&serialized).await?;
787
788        let backup_version = json!({
789            "algorithm": "m.megolm_backup.v1.curve25519-aes-sha2",
790            "auth_data": {
791                "public_key":"XjhWTCjW7l59pbfx9tlCBQolfnIQWARoKOzjTOPSlWM",
792                "signatures": signatures,
793            }
794        });
795        let backup_version: RoomKeyBackupInfo = serde_json::from_value(backup_version).unwrap();
796
797        let state = backup_machine
798            .verify_backup(backup_version, false)
799            .await
800            .expect("Verifying should work");
801
802        assert!(state.trusted());
803        assert!(state.device_signature.trusted());
804        assert!(!state.user_identity_signature.trusted());
805        assert!(!state.other_signatures.values().any(|s| s.trusted()));
806
807        machine
808            .bootstrap_cross_signing(true)
809            .await
810            .expect("Bootstrapping a new identity always works");
811
812        let signatures = machine.sign(&serialized).await?;
813
814        let backup_version = json!({
815            "algorithm": "m.megolm_backup.v1.curve25519-aes-sha2",
816            "auth_data": {
817                "public_key":"XjhWTCjW7l59pbfx9tlCBQolfnIQWARoKOzjTOPSlWM",
818                "signatures": signatures,
819            }
820        });
821        let backup_version: RoomKeyBackupInfo = serde_json::from_value(backup_version).unwrap();
822
823        let state = backup_machine
824            .verify_backup(backup_version, false)
825            .await
826            .expect("Verifying should work");
827
828        assert!(state.trusted());
829        assert!(state.device_signature.trusted());
830        assert!(state.user_identity_signature.trusted());
831        assert!(!state.other_signatures.values().any(|s| s.trusted()));
832
833        Ok(())
834    }
835
836    #[async_test]
837    async fn test_import_backed_up_room_keys() {
838        let machine = OlmMachine::new(alice_id(), alice_device_id()).await;
839        let backup_machine = machine.backup_machine();
840
841        // We set up a backup key, so that we can test `backup_machine.backup()` later.
842        let decryption_key = BackupDecryptionKey::new();
843        let backup_key = decryption_key.megolm_v1_public_key();
844        backup_key.set_version("1".to_owned());
845        backup_machine.enable_backup_v1(backup_key).await.expect("Couldn't enable backup");
846
847        let room_id = room_id!("!DovneieKSTkdHKpIXy:morpheus.localhost");
848        let session_id = "gM8i47Xhu0q52xLfgUXzanCMpLinoyVyH7R58cBuVBU";
849        let room_key = room_key();
850
851        let room_keys: BTreeMap<_, BTreeMap<_, _>> = BTreeMap::from([(
852            room_id.to_owned(),
853            BTreeMap::from([(session_id.to_owned(), room_key)]),
854        )]);
855
856        let session = machine.store().get_inbound_group_session(room_id, session_id).await.unwrap();
857
858        assert!(session.is_none(), "Initially we should not have the session in the store");
859
860        #[allow(deprecated)]
861        backup_machine
862            .import_backed_up_room_keys(room_keys, |_, _| {})
863            .await
864            .expect("We should be able to import a room key");
865
866        // Now check that the session was correctly imported, and that it is marked as
867        // backed up
868        let session = machine.store().get_inbound_group_session(room_id, session_id).await.unwrap();
869        assert_let!(Some(session) = session);
870        assert!(
871            session.backed_up(),
872            "If a session was imported from a backup, it should be considered to be backed up"
873        );
874        assert!(session.has_been_imported());
875
876        // Also check that it is not returned by a backup request.
877        let backup_request =
878            backup_machine.backup().await.expect("We should be able to create a backup request");
879        assert!(
880            backup_request.is_none(),
881            "If a session was imported from backup, it should not be backed up again."
882        );
883    }
884
885    #[async_test]
886    async fn test_sign_backup_info() {
887        let machine = OlmMachine::new(alice_id(), alice_device_id()).await;
888        let backup_machine = machine.backup_machine();
889
890        let decryption_key = BackupDecryptionKey::new();
891        let mut backup_info = decryption_key.to_backup_info();
892
893        let result = backup_machine.verify_backup(backup_info.to_owned(), false).await.unwrap();
894
895        assert!(!result.trusted());
896
897        backup_machine.sign_backup(&mut backup_info).await.unwrap();
898
899        let result = backup_machine.verify_backup(backup_info, false).await.unwrap();
900
901        assert!(result.trusted());
902    }
903
904    #[async_test]
905    async fn test_fix_backup_key_mismatch() {
906        let store = MemoryStore::new();
907
908        let backup_decryption_key = BackupDecryptionKey::new();
909
910        store
911            .save_changes(Changes {
912                backup_decryption_key: Some(backup_decryption_key.clone()),
913                backup_version: Some("1".to_owned()),
914                ..Default::default()
915            })
916            .await
917            .unwrap();
918
919        // Create the machine using `with_store` and without a call to enable_backup_v1,
920        // like regenerate_olm would do
921        let alice = OlmMachineBuilder::new(alice_id(), alice_device_id())
922            .with_crypto_store(store)
923            .build()
924            .await
925            .unwrap();
926
927        let binding = alice.backup_machine().backup_key.read().await;
928        let machine_backup_key = binding.as_ref().unwrap();
929
930        assert_eq!(
931            machine_backup_key.to_base64(),
932            backup_decryption_key.megolm_v1_public_key().to_base64(),
933            "The OlmMachine loaded the wrong backup key."
934        );
935    }
936}