matrix_sdk_crypto/
dehydrated_devices.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//! Submodule for device dehydration support.
16//!
17//! Dehydrated devices intend to solve the use-case where users might want to
18//! frequently delete their device, in which case other users won't be able to
19//! send end-to-end encrypted messages to them as no device exists to receive
20//! and decrypt them.
21//!
22//! A dehydrated device is a kind-of omnipresent virtual device that lives on
23//! the homeserver. A dehydrated device acts as a normal device from the
24//! point of view of other devices. It uploads device and one-time keys to
25//! the homeserver which other devices can download and start 1-to-1 encrypted
26//! sessions with the device just like with any other device.
27//!
28//! The one important difference is that the private parts of the uploaded
29//! device and one-time keys are encrypted and uploaded to the homeserver as
30//! well.
31//!
32//! Once the user creates a new real device, the real device can download the
33//! private keys of the dehydrated device from the homeserver, decrypt them and
34//! download all the encrypted to-device events the dehydrated device has
35//! received. This process is called rehydration.
36//!
37//! After the rehydration process is completed, the user's real device should
38//! create a new dehydrated device.
39
40// TODO: Once a device has been rehydrated it might need to download and decrypt
41// a lot of to-device events. This process might take some time and we should
42// support resuming it.
43
44use std::sync::Arc;
45
46use ruma::{
47    api::client::dehydrated_device::{put_dehydrated_device, DehydratedDeviceData},
48    assign,
49    events::AnyToDeviceEvent,
50    serde::Raw,
51    DeviceId,
52};
53use thiserror::Error;
54use tracing::{instrument, trace};
55use vodozemac::{DehydratedDeviceError, LibolmPickleError};
56
57use crate::{
58    store::{
59        types::{Changes, DehydratedDeviceKey, RoomKeyInfo},
60        CryptoStoreWrapper, MemoryStore, Store,
61    },
62    verification::VerificationMachine,
63    Account, CryptoStoreError, DecryptionSettings, EncryptionSyncChanges, OlmError, OlmMachine,
64    SignatureError,
65};
66
67/// Error type for device dehydration issues.
68#[derive(Debug, Error)]
69pub enum DehydrationError {
70    /// The legacy dehydrated device could not be unpickled.
71    #[error(transparent)]
72    LegacyPickle(#[from] LibolmPickleError),
73
74    /// The dehydrated device could not be unpickled.
75    #[error(transparent)]
76    Pickle(#[from] DehydratedDeviceError),
77
78    /// The pickle key has an invalid length
79    #[error("The pickle key has an invalid length, expected 32 bytes, got {0}")]
80    PickleKeyLength(usize),
81
82    /// The dehydrated device could not be signed by our user identity,
83    /// we're missing the self-signing key.
84    #[error("The self-signing key is missing, can't create a dehydrated device")]
85    MissingSigningKey(#[from] SignatureError),
86
87    /// We could not deserialize the dehydrated device data.
88    #[error(transparent)]
89    Json(#[from] serde_json::Error),
90
91    /// The store ran into an error.
92    #[error(transparent)]
93    Store(#[from] CryptoStoreError),
94}
95
96/// Struct collecting methods to create and rehydrate dehydrated devices.
97#[derive(Debug)]
98pub struct DehydratedDevices {
99    pub(crate) inner: OlmMachine,
100}
101
102impl DehydratedDevices {
103    /// Create a new [`DehydratedDevice`] which can be uploaded to the server.
104    pub async fn create(&self) -> Result<DehydratedDevice, DehydrationError> {
105        let user_id = self.inner.user_id();
106        let user_identity = self.inner.store().private_identity();
107
108        let account = Account::new_dehydrated(user_id);
109        let store =
110            Arc::new(CryptoStoreWrapper::new(user_id, account.device_id(), MemoryStore::new()));
111
112        let verification_machine = VerificationMachine::new(
113            account.static_data().clone(),
114            user_identity.clone(),
115            store.clone(),
116        );
117
118        let store =
119            Store::new(account.static_data().clone(), user_identity, store, verification_machine);
120        store
121            .save_pending_changes(crate::store::types::PendingChanges { account: Some(account) })
122            .await?;
123
124        Ok(DehydratedDevice { store })
125    }
126
127    /// Rehydrate the dehydrated device.
128    ///
129    /// Once rehydrated, to-device events can be pushed into the
130    /// [`RehydratedDevice`] to collect the room keys the device has
131    /// received.
132    ///
133    /// For more info see the example for the
134    /// [`RehydratedDevice::receive_events()`] method.
135    ///
136    /// # Arguments
137    ///
138    /// * `pickle_key` - The encryption key that was used to encrypt the private
139    ///   parts of the identity keys, and one-time keys of the device.
140    ///
141    /// * `device_id` - The unique identifier of the device.
142    ///
143    /// * `device_data` - The encrypted data of the device, containing the
144    ///   private keys of the device.
145    pub async fn rehydrate(
146        &self,
147        pickle_key: &DehydratedDeviceKey,
148        device_id: &DeviceId,
149        device_data: Raw<DehydratedDeviceData>,
150    ) -> Result<RehydratedDevice, DehydrationError> {
151        let rehydrated =
152            self.inner.rehydrate(pickle_key.inner.as_ref(), device_id, device_data).await?;
153
154        Ok(RehydratedDevice { rehydrated, original: self.inner.to_owned() })
155    }
156
157    /// Get the cached dehydrated device pickle key if any.
158    ///
159    /// None if the key was not previously cached (via
160    /// [`DehydratedDevices::save_dehydrated_device_pickle_key`]).
161    ///
162    /// Should be used to periodically rotate the dehydrated device to avoid
163    /// one-time keys exhaustion and accumulation of to_device messages.
164    pub async fn get_dehydrated_device_pickle_key(
165        &self,
166    ) -> Result<Option<DehydratedDeviceKey>, DehydrationError> {
167        Ok(self.inner.store().load_dehydrated_device_pickle_key().await?)
168    }
169
170    /// Store the dehydrated device pickle key in the crypto store.
171    ///
172    /// This is useful if the client wants to periodically rotate dehydrated
173    /// devices to avoid one-time keys exhaustion and accumulated to_device
174    /// problems.
175    pub async fn save_dehydrated_device_pickle_key(
176        &self,
177        dehydrated_device_pickle_key: &DehydratedDeviceKey,
178    ) -> Result<(), DehydrationError> {
179        let changes = Changes {
180            dehydrated_device_pickle_key: Some(dehydrated_device_pickle_key.clone()),
181            ..Default::default()
182        };
183        Ok(self.inner.store().save_changes(changes).await?)
184    }
185
186    /// Deletes the previously stored dehydrated device pickle key.
187    pub async fn delete_dehydrated_device_pickle_key(&self) -> Result<(), DehydrationError> {
188        Ok(self.inner.store().delete_dehydrated_device_pickle_key().await?)
189    }
190}
191
192/// A rehydraded device.
193///
194/// This device can now receive to-device events to decrypt and gather room keys
195/// which were sent to the dehydrated device.
196#[derive(Debug)]
197pub struct RehydratedDevice {
198    rehydrated: OlmMachine,
199    original: OlmMachine,
200}
201
202impl RehydratedDevice {
203    /// Feed to-device events the device was supposed to receive into the
204    /// [`RehydratedDevice`].
205    ///
206    /// Most to-device events we feed into the [`RehydratedDevice`] will contain
207    /// room keys, the rehydrated device will pass these room keys into our
208    /// own [`OlmMachine`] which will persist them and make the room keys
209    /// available for use using the usual
210    /// [`OlmMachine::decrypt_room_event()`] method.
211    ///
212    /// Once the homeserver returns a response without any to-device events, we
213    /// can safely delete the current dehydrated device and create a new one.
214    ///
215    /// # Examples
216    ///
217    /// ```no_run
218    /// # use anyhow::Result;
219    /// # use matrix_sdk_crypto::{
220    ///     DecryptionSettings, OlmMachine, TrustRequirement, store::types::DehydratedDeviceKey
221    /// };
222    /// # use ruma::{api::client::dehydrated_device, DeviceId};
223    /// # async fn example() -> Result<()> {
224    /// # let machine: OlmMachine = unimplemented!();
225    /// async fn get_dehydrated_device() -> Result<dehydrated_device::get_dehydrated_device::unstable::Response> {
226    ///     todo!("Download the dehydrated device");
227    /// }
228    ///
229    /// async fn get_events(
230    ///     device_id: &DeviceId,
231    ///     since_token: Option<&str>
232    /// ) -> Result<dehydrated_device::get_events::unstable::Response> {
233    ///     todo!("Download the to-device events of the dehydrated device");
234    /// }
235    /// // Get the cached dehydrated key (got it after verification/recovery)
236    /// let pickle_key = machine
237    ///     .dehydrated_devices().get_dehydrated_device_pickle_key().await?.unwrap();
238    ///
239    /// // Fetch the dehydrated device from the server.
240    /// let response = get_dehydrated_device().await?;
241    /// let device_id = response.device_id;
242    ///
243    /// // Rehydrate the device.
244    /// let rehydrated = machine
245    ///     .dehydrated_devices()
246    ///     .rehydrate(&pickle_key, &device_id, response.device_data)
247    ///     .await?;
248    ///
249    /// let mut since_token = None;
250    /// let mut imported_room_keys = 0;
251    /// let decryption_settings = DecryptionSettings {
252    ///     sender_device_trust_requirement: TrustRequirement::Untrusted
253    /// };
254    ///
255    /// loop {
256    ///     let response =
257    ///         get_events(&device_id, since_token).await?;
258    ///
259    ///     if response.events.is_empty() {
260    ///         break;
261    ///     }
262    ///
263    ///     since_token = response.next_batch.as_deref();
264    ///     imported_room_keys += rehydrated.receive_events(response.events, &decryption_settings).await?.len();
265    /// }
266    ///
267    /// println!("Successfully imported {imported_room_keys} from the dehydrated device.");
268    /// # Ok(())
269    /// # }
270    /// ```
271    #[instrument(
272        skip_all,
273        fields(
274            user_id = ?self.original.user_id(),
275            rehydrated_device_id = ?self.rehydrated.device_id(),
276            original_device_id = ?self.original.device_id()
277        )
278    )]
279    pub async fn receive_events(
280        &self,
281        events: Vec<Raw<AnyToDeviceEvent>>,
282        decryption_settings: &DecryptionSettings,
283    ) -> Result<Vec<RoomKeyInfo>, OlmError> {
284        trace!("Receiving events for a rehydrated Device");
285
286        let sync_changes = EncryptionSyncChanges {
287            to_device_events: events,
288            next_batch_token: None,
289            one_time_keys_counts: &Default::default(),
290            changed_devices: &Default::default(),
291            unused_fallback_keys: None,
292        };
293
294        // Let us first give the events to the rehydrated device, this will decrypt any
295        // encrypted to-device events and fetch out the room keys.
296        let mut rehydrated_transaction = self.rehydrated.store().transaction().await;
297
298        let (_, changes) = self
299            .rehydrated
300            .preprocess_sync_changes(&mut rehydrated_transaction, sync_changes, decryption_settings)
301            .await?;
302
303        // Now take the room keys and persist them in our original `OlmMachine`.
304        let room_keys = &changes.inbound_group_sessions;
305        let updates = room_keys.iter().map(Into::into).collect();
306
307        trace!(room_key_count = room_keys.len(), "Collected room keys from the rehydrated device");
308
309        self.original.store().save_inbound_group_sessions(room_keys).await?;
310
311        rehydrated_transaction.commit().await?;
312        self.rehydrated.store().save_changes(changes).await?;
313
314        Ok(updates)
315    }
316}
317
318/// A dehydrated device that can uploaded to the homeserver.
319///
320/// To upload the dehydrated device take a look at the
321/// [`DehydratedDevice::keys_for_upload()`] method.
322#[derive(Debug)]
323pub struct DehydratedDevice {
324    store: Store,
325}
326
327impl DehydratedDevice {
328    /// Get the request to upload the dehydrated device.
329    ///
330    /// # Arguments
331    ///
332    /// * `initial_device_display_name` - The human-readable name this device
333    ///   should have.
334    /// * `pickle_key` - The encryption key that should be used to encrypt the
335    ///   private parts of the identity keys, and one-time keys of the device.
336    ///
337    /// # Examples
338    ///
339    /// ```no_run
340    /// # use matrix_sdk_crypto::OlmMachine;    /// #
341    /// use matrix_sdk_crypto::store::types::DehydratedDeviceKey;
342    ///
343    /// async fn example() -> anyhow::Result<()> {
344    /// # let machine: OlmMachine = unimplemented!();
345    /// // Create a new random key
346    /// let pickle_key = DehydratedDeviceKey::new()?;
347    ///
348    /// // Create the dehydrated device.
349    /// let device = machine.dehydrated_devices().create().await?;
350    ///
351    /// // Create the request that should upload the device.
352    /// let request = device
353    ///     .keys_for_upload("Dehydrated device".to_owned(), &pickle_key)
354    ///     .await?;
355    ///
356    /// // Save the key if you want to later one rotate the dehydrated device
357    /// machine.dehydrated_devices().save_dehydrated_device_pickle_key(&pickle_key).await.unwrap();
358    ///
359    /// // Send the request out using your HTTP client.
360    /// // client.send(request).await?;
361    /// # Ok(())
362    /// # }
363    /// ```
364    #[instrument(
365        skip_all, fields(
366            user_id = ?self.store.static_account().user_id,
367            device_id = ?self.store.static_account().device_id,
368            identity_keys = ?self.store.static_account().identity_keys,
369        )
370    )]
371    pub async fn keys_for_upload(
372        &self,
373        initial_device_display_name: String,
374        pickle_key: &DehydratedDeviceKey,
375    ) -> Result<put_dehydrated_device::unstable::Request, DehydrationError> {
376        let mut transaction = self.store.transaction().await;
377
378        let account = transaction.account().await?;
379        account.generate_fallback_key_if_needed();
380
381        let (device_keys, one_time_keys, fallback_keys) = account.keys_for_upload();
382
383        let mut device_keys = device_keys
384            .expect("We should always try to upload device keys for a dehydrated device.");
385
386        self.store.private_identity().lock().await.sign_device_keys(&mut device_keys).await?;
387
388        trace!("Creating an upload request for a dehydrated device");
389
390        let device_id = self.store.static_account().device_id.clone();
391        let device_data = account.dehydrate(pickle_key.inner.as_ref());
392        let initial_device_display_name = Some(initial_device_display_name);
393
394        transaction.commit().await?;
395
396        Ok(
397            assign!(put_dehydrated_device::unstable::Request::new(device_id, device_data, device_keys.to_raw()), {
398                one_time_keys, fallback_keys, initial_device_display_name
399            }),
400        )
401    }
402}
403
404#[cfg(test)]
405mod tests {
406    use std::{collections::BTreeMap, iter};
407
408    use js_option::JsOption;
409    use matrix_sdk_test::async_test;
410    use ruma::{
411        api::client::{
412            dehydrated_device::put_dehydrated_device,
413            keys::get_keys::v3::Response as KeysQueryResponse,
414        },
415        assign,
416        encryption::DeviceKeys,
417        events::AnyToDeviceEvent,
418        room_id,
419        serde::Raw,
420        user_id, DeviceId, RoomId, TransactionId, UserId,
421    };
422
423    use crate::{
424        dehydrated_devices::DehydratedDevice,
425        machine::{
426            test_helpers::{create_session, get_prepared_machine_test_helper},
427            tests::to_device_requests_to_content,
428        },
429        olm::OutboundGroupSession,
430        store::types::DehydratedDeviceKey,
431        types::{events::ToDeviceEvent, DeviceKeys as DeviceKeysType},
432        utilities::json_convert,
433        DecryptionSettings, EncryptionSettings, OlmMachine, TrustRequirement,
434    };
435
436    fn pickle_key() -> DehydratedDeviceKey {
437        DehydratedDeviceKey::from_bytes(&[0u8; 32])
438    }
439
440    fn user_id() -> &'static UserId {
441        user_id!("@alice:localhost")
442    }
443
444    async fn get_olm_machine() -> OlmMachine {
445        let (olm_machine, _) = get_prepared_machine_test_helper(user_id(), false).await;
446        olm_machine.bootstrap_cross_signing(false).await.unwrap();
447
448        olm_machine
449    }
450
451    // Insert some device keys into a [`OlmMachine`] making the [`Device`] available
452    // to the [`OlmMachine`].
453    async fn receive_device_keys(
454        olm_machine: &OlmMachine,
455        user_id: &UserId,
456        device_id: &DeviceId,
457        device_keys: Raw<DeviceKeys>,
458    ) {
459        let device_keys = BTreeMap::from([(device_id.to_owned(), device_keys)]);
460
461        let keys_query_response = assign!(
462            KeysQueryResponse::new(), {
463                device_keys: BTreeMap::from([(user_id.to_owned(), device_keys)]),
464            }
465        );
466
467        olm_machine
468            .mark_request_as_sent(&TransactionId::new(), &keys_query_response)
469            .await
470            .unwrap();
471    }
472
473    async fn send_room_key(
474        machine: &OlmMachine,
475        room_id: &RoomId,
476        recipient: &UserId,
477    ) -> (Raw<AnyToDeviceEvent>, OutboundGroupSession) {
478        let to_device_requests = machine
479            .share_room_key(room_id, iter::once(recipient), EncryptionSettings::default())
480            .await
481            .unwrap();
482
483        let event = ToDeviceEvent::new(
484            user_id().to_owned(),
485            to_device_requests_to_content(to_device_requests),
486        );
487
488        let session =
489            machine.inner.group_session_manager.get_outbound_group_session(room_id).expect(
490                "An outbound group session should have been created when the room key was shared",
491            );
492
493        (
494            json_convert(&event)
495                .expect("We should be able to convert the to-device event into it's Raw variatn"),
496            session,
497        )
498    }
499
500    #[async_test]
501    async fn test_dehydrated_device_creation() {
502        let olm_machine = get_olm_machine().await;
503
504        let dehydrated_device = olm_machine.dehydrated_devices().create().await.unwrap();
505
506        let request = dehydrated_device
507            .keys_for_upload("Foo".to_owned(), &pickle_key())
508            .await
509            .expect("We should be able to create a request to upload a dehydrated device");
510
511        assert!(
512            !request.one_time_keys.is_empty(),
513            "The dehydrated device creation request should contain some one-time keys"
514        );
515
516        assert!(
517            !request.fallback_keys.is_empty(),
518            "The dehydrated device creation request should contain some fallback keys"
519        );
520
521        let device_keys: DeviceKeysType = request.device_keys.deserialize_as().unwrap();
522        assert_eq!(
523            device_keys.dehydrated,
524            JsOption::Some(true),
525            "The device keys of the dehydrated device should be marked as dehydrated."
526        );
527    }
528
529    #[async_test]
530    async fn test_dehydrated_device_rehydration() {
531        let room_id = room_id!("!test:example.org");
532        let alice = get_olm_machine().await;
533
534        let dehydrated_device = alice.dehydrated_devices().create().await.unwrap();
535
536        let mut request = dehydrated_device
537            .keys_for_upload("Foo".to_owned(), &pickle_key())
538            .await
539            .expect("We should be able to create a request to upload a dehydrated device");
540
541        let (key_id, one_time_key) = request
542            .one_time_keys
543            .pop_first()
544            .expect("The dehydrated device creation request should contain a one-time key");
545
546        // Ensure that we know about the public keys of the dehydrated device.
547        receive_device_keys(&alice, user_id(), &request.device_id, request.device_keys).await;
548        // Create a 1-to-1 Olm session with the dehydrated device.
549        create_session(&alice, user_id(), &request.device_id, key_id, one_time_key).await;
550
551        // Send a room key to the dehydrated device.
552        let (event, group_session) = send_room_key(&alice, room_id, user_id()).await;
553
554        // Let's now create a new `OlmMachine` which doesn't know about the room key.
555        let bob = get_olm_machine().await;
556
557        let room_key = bob
558            .store()
559            .get_inbound_group_session(room_id, group_session.session_id())
560            .await
561            .unwrap();
562
563        assert!(
564            room_key.is_none(),
565            "We should not have access to the room key that was only sent to the dehydrated device"
566        );
567
568        // Rehydrate the device.
569        let rehydrated = bob
570            .dehydrated_devices()
571            .rehydrate(&pickle_key(), &request.device_id, request.device_data)
572            .await
573            .expect("We should be able to rehydrate the device");
574
575        assert_eq!(rehydrated.rehydrated.device_id(), request.device_id);
576        assert_eq!(rehydrated.original.device_id(), alice.device_id());
577
578        let decryption_settings =
579            DecryptionSettings { sender_device_trust_requirement: TrustRequirement::Untrusted };
580
581        // Push the to-device event containing the room key into the rehydrated device.
582        let ret = rehydrated
583            .receive_events(vec![event], &decryption_settings)
584            .await
585            .expect("We should be able to push to-device events into the rehydrated device");
586
587        assert_eq!(ret.len(), 1, "The rehydrated device should have imported a room key");
588
589        // The `OlmMachine` now does know about the room key since the rehydrated device
590        // shared it with us.
591        let room_key = bob
592            .store()
593            .get_inbound_group_session(room_id, group_session.session_id())
594            .await
595            .unwrap()
596            .expect("We should now have access to the room key, since the rehydrated device imported it for us");
597
598        assert_eq!(
599            room_key.session_id(),
600            group_session.session_id(),
601            "The session ids of the imported room key and the outbound group session should match"
602        );
603    }
604
605    #[async_test]
606    async fn test_dehydrated_device_pickle_key_cache() {
607        let alice = get_olm_machine().await;
608
609        let dehydrated_manager = alice.dehydrated_devices();
610
611        let stored_key = dehydrated_manager.get_dehydrated_device_pickle_key().await.unwrap();
612        assert!(stored_key.is_none());
613
614        let pickle_key = DehydratedDeviceKey::new().unwrap();
615
616        dehydrated_manager.save_dehydrated_device_pickle_key(&pickle_key).await.unwrap();
617
618        let stored_key =
619            dehydrated_manager.get_dehydrated_device_pickle_key().await.unwrap().unwrap();
620        assert_eq!(stored_key.to_base64(), pickle_key.to_base64());
621
622        let dehydrated_device = dehydrated_manager.create().await.unwrap();
623
624        let request = dehydrated_device
625            .keys_for_upload("Foo".to_owned(), &stored_key)
626            .await
627            .expect("We should be able to create a request to upload a dehydrated device");
628
629        // Rehydrate the device.
630        dehydrated_manager
631            .rehydrate(&stored_key, &request.device_id, request.device_data)
632            .await
633            .expect("We should be able to rehydrate the device");
634
635        dehydrated_manager
636            .delete_dehydrated_device_pickle_key()
637            .await
638            .expect("Should be able to delete the dehydrated device key");
639
640        let stored_key = dehydrated_manager.get_dehydrated_device_pickle_key().await.unwrap();
641        assert!(stored_key.is_none());
642    }
643
644    /// Test that we can rehydrate an older version of dehydrated device
645    #[async_test]
646    async fn test_legacy_dehydrated_device_rehydration() {
647        let room_id = room_id!("!test:example.org");
648        let alice = get_olm_machine().await;
649
650        let dehydrated_device = alice.dehydrated_devices().create().await.unwrap();
651        let mut request =
652            legacy_dehydrated_device_keys_for_upload(&dehydrated_device, &pickle_key()).await;
653
654        let (key_id, one_time_key) = request
655            .one_time_keys
656            .pop_first()
657            .expect("The dehydrated device creation request should contain a one-time key");
658
659        let device_id = request.device_id;
660
661        // Ensure that we know about the public keys of the dehydrated device.
662        receive_device_keys(&alice, user_id(), &device_id, request.device_keys).await;
663        // Create a 1-to-1 Olm session with the dehydrated device.
664        create_session(&alice, user_id(), &device_id, key_id, one_time_key).await;
665
666        // Send a room key to the dehydrated device.
667        let (event, group_session) = send_room_key(&alice, room_id, user_id()).await;
668
669        // Let's now create a new `OlmMachine` which doesn't know about the room key.
670        let bob = get_olm_machine().await;
671
672        let room_key = bob
673            .store()
674            .get_inbound_group_session(room_id, group_session.session_id())
675            .await
676            .unwrap();
677
678        assert!(
679            room_key.is_none(),
680            "We should not have access to the room key that was only sent to the dehydrated device"
681        );
682
683        // Rehydrate the device.
684        let rehydrated = bob
685            .dehydrated_devices()
686            .rehydrate(&pickle_key(), &device_id, request.device_data)
687            .await
688            .expect("We should be able to rehydrate the device");
689
690        assert_eq!(rehydrated.rehydrated.device_id(), &device_id);
691        assert_eq!(rehydrated.original.device_id(), alice.device_id());
692
693        let decryption_settings =
694            DecryptionSettings { sender_device_trust_requirement: TrustRequirement::Untrusted };
695
696        // Push the to-device event containing the room key into the rehydrated device.
697        let ret = rehydrated
698            .receive_events(vec![event], &decryption_settings)
699            .await
700            .expect("We should be able to push to-device events into the rehydrated device");
701
702        assert_eq!(ret.len(), 1, "The rehydrated device should have imported a room key");
703
704        // The `OlmMachine` now does know about the room key since the rehydrated device
705        // shared it with us.
706        let room_key = bob
707            .store()
708            .get_inbound_group_session(room_id, group_session.session_id())
709            .await
710            .unwrap()
711            .expect("We should now have access to the room key, since the rehydrated device imported it for us");
712
713        assert_eq!(
714            room_key.session_id(),
715            group_session.session_id(),
716            "The session ids of the imported room key and the outbound group session should match"
717        );
718    }
719
720    /// Duplicates the behaviour of [`DehydratedDevice::keys_for_upload`],
721    /// except that it calls [`Account::legacy_dehydrate`] instead of
722    /// [`Account::dehydrate`].
723    async fn legacy_dehydrated_device_keys_for_upload(
724        dehydrated_device: &DehydratedDevice,
725        pickle_key: &DehydratedDeviceKey,
726    ) -> put_dehydrated_device::unstable::Request {
727        let mut transaction = dehydrated_device.store.transaction().await;
728        let account = transaction.account().await.unwrap();
729        account.generate_fallback_key_if_needed();
730
731        let (device_keys, one_time_keys, fallback_keys) = account.keys_for_upload();
732        let mut device_keys = device_keys.unwrap();
733        dehydrated_device
734            .store
735            .private_identity()
736            .lock()
737            .await
738            .sign_device_keys(&mut device_keys)
739            .await
740            .expect("Should be able to cross-sign a device");
741
742        let device_id = account.device_id().to_owned();
743        let device_data = account.legacy_dehydrate(pickle_key.inner.as_ref());
744        transaction.commit().await.unwrap();
745
746        assign!(put_dehydrated_device::unstable::Request::new(device_id, device_data, device_keys.to_raw()), {
747            one_time_keys, fallback_keys
748        })
749    }
750}