matrix_sdk_crypto_ffi/
lib.rs

1//! Uniffi based bindings for the `matrix-sdk-crypto` crate.
2//!
3//! This crate can be used to introduce E2EE support into an existing Matrix
4//! client or client library in any of the language targets Uniffi supports.
5
6#![warn(missing_docs)]
7#![allow(unused_qualifications)]
8
9mod backup_recovery_key;
10mod dehydrated_devices;
11mod device;
12mod error;
13mod logger;
14mod machine;
15mod responses;
16mod users;
17mod verification;
18
19use std::{
20    collections::{BTreeMap, HashMap},
21    sync::Arc,
22    time::Duration,
23};
24
25use anyhow::Context as _;
26pub use backup_recovery_key::{
27    BackupRecoveryKey, DecodeError, MegolmV1BackupKey, PassphraseInfo, PkDecryptionError,
28};
29pub use device::Device;
30pub use error::{
31    CryptoStoreError, DecryptionError, KeyImportError, SecretImportError, SignatureError,
32};
33use js_int::UInt;
34pub use logger::{set_logger, Logger};
35pub use machine::{KeyRequestPair, OlmMachine, SignatureVerification};
36use matrix_sdk_common::deserialized_responses::{ShieldState as RustShieldState, ShieldStateCode};
37use matrix_sdk_crypto::{
38    olm::{IdentityKeys, InboundGroupSession, SenderData, Session},
39    store::{
40        Changes, CryptoStore, DehydratedDeviceKey as InnerDehydratedDeviceKey, PendingChanges,
41        RoomSettings as RustRoomSettings,
42    },
43    types::{
44        DeviceKey, DeviceKeys, EventEncryptionAlgorithm as RustEventEncryptionAlgorithm, SigningKey,
45    },
46    CollectStrategy, EncryptionSettings as RustEncryptionSettings,
47};
48use matrix_sdk_sqlite::SqliteCryptoStore;
49pub use responses::{
50    BootstrapCrossSigningResult, DeviceLists, KeysImportResult, OutgoingVerificationRequest,
51    Request, RequestType, SignatureUploadRequest, UploadSigningKeysRequest,
52};
53use ruma::{
54    events::room::history_visibility::HistoryVisibility as RustHistoryVisibility,
55    DeviceKeyAlgorithm, DeviceKeyId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId,
56    RoomId, SecondsSinceUnixEpoch, UserId,
57};
58use serde::{Deserialize, Serialize};
59use tokio::runtime::Runtime;
60pub use users::UserIdentity;
61pub use verification::{
62    CancelInfo, ConfirmVerificationResult, QrCode, QrCodeListener, QrCodeState,
63    RequestVerificationResult, Sas, SasListener, SasState, ScanResult, StartSasResult,
64    Verification, VerificationRequest, VerificationRequestListener, VerificationRequestState,
65};
66use vodozemac::{Curve25519PublicKey, Ed25519PublicKey};
67
68use crate::dehydrated_devices::DehydrationError;
69
70/// Struct collecting data that is important to migrate to the rust-sdk
71#[derive(Deserialize, Serialize, uniffi::Record)]
72pub struct MigrationData {
73    /// The pickled version of the Olm Account
74    account: PickledAccount,
75    /// The list of pickleds Olm Sessions.
76    sessions: Vec<PickledSession>,
77    /// The list of Megolm inbound group sessions.
78    inbound_group_sessions: Vec<PickledInboundGroupSession>,
79    /// The Olm pickle key that was used to pickle all the Olm objects.
80    pickle_key: Vec<u8>,
81    /// The backup version that is currently active.
82    backup_version: Option<String>,
83    // The backup recovery key, as a base58 encoded string.
84    backup_recovery_key: Option<String>,
85    /// The private cross signing keys.
86    cross_signing: CrossSigningKeyExport,
87    /// The list of users that the Rust SDK should track.
88    tracked_users: Vec<String>,
89    /// Map of room settings
90    room_settings: HashMap<String, RoomSettings>,
91}
92
93/// Struct collecting data that is important to migrate sessions to the rust-sdk
94#[derive(uniffi::Record)]
95pub struct SessionMigrationData {
96    /// The user id that the data belongs to.
97    user_id: String,
98    /// The device id that the data belongs to.
99    device_id: String,
100    /// The Curve25519 public key of the Account that owns this data.
101    curve25519_key: String,
102    /// The Ed25519 public key of the Account that owns this data.
103    ed25519_key: String,
104    /// The list of pickleds Olm Sessions.
105    sessions: Vec<PickledSession>,
106    /// The list of pickled Megolm inbound group sessions.
107    inbound_group_sessions: Vec<PickledInboundGroupSession>,
108    /// The Olm pickle key that was used to pickle all the Olm objects.
109    pickle_key: Vec<u8>,
110}
111
112/// A pickled version of an `Account`.
113///
114/// Holds all the information that needs to be stored in a database to restore
115/// an account.
116#[derive(Debug, Deserialize, Serialize, uniffi::Record)]
117pub struct PickledAccount {
118    /// The user id of the account owner.
119    pub user_id: String,
120    /// The device ID of the account owner.
121    pub device_id: String,
122    /// The pickled version of the Olm account.
123    pub pickle: String,
124    /// Was the account shared.
125    pub shared: bool,
126    /// The number of uploaded one-time keys we have on the server.
127    pub uploaded_signed_key_count: i64,
128}
129
130/// A pickled version of a `Session`.
131///
132/// Holds all the information that needs to be stored in a database to restore
133/// a Session.
134#[derive(Debug, Deserialize, Serialize, uniffi::Record)]
135pub struct PickledSession {
136    /// The pickle string holding the Olm Session.
137    pub pickle: String,
138    /// The curve25519 key of the other user that we share this session with.
139    pub sender_key: String,
140    /// Was the session created using a fallback key.
141    pub created_using_fallback_key: bool,
142    /// Unix timestamp (in seconds) when the session was created.
143    pub creation_time: u64,
144    /// Unix timestamp (in seconds) when the session was last used.
145    pub last_use_time: u64,
146}
147
148/// A pickled version of an `InboundGroupSession`.
149///
150/// Holds all the information that needs to be stored in a database to restore
151/// an InboundGroupSession.
152#[derive(Debug, Deserialize, Serialize, uniffi::Record)]
153pub struct PickledInboundGroupSession {
154    /// The pickle string holding the InboundGroupSession.
155    pub pickle: String,
156    /// The public curve25519 key of the account that sent us the session
157    pub sender_key: String,
158    /// The public ed25519 key of the account that sent us the session.
159    pub signing_key: HashMap<String, String>,
160    /// The id of the room that the session is used in.
161    pub room_id: String,
162    /// The list of claimed ed25519 that forwarded us this key. Will be empty if
163    /// we directly received this session.
164    pub forwarding_chains: Vec<String>,
165    /// Flag remembering if the session was directly sent to us by the sender
166    /// or if it was imported.
167    pub imported: bool,
168    /// Flag remembering if the session has been backed up.
169    pub backed_up: bool,
170}
171
172/// Error type for the migration process.
173#[derive(Debug, thiserror::Error, uniffi::Error)]
174pub enum MigrationError {
175    /// Generic catch all error variant.
176    #[error("error migrating database: {error_message}")]
177    Generic {
178        /// The error message
179        error_message: String,
180    },
181}
182
183impl From<anyhow::Error> for MigrationError {
184    fn from(e: anyhow::Error) -> MigrationError {
185        MigrationError::Generic { error_message: e.to_string() }
186    }
187}
188
189/// Migrate a libolm based setup to a vodozemac based setup stored in a SQLite
190/// store.
191///
192/// # Arguments
193///
194/// * `data` - The data that should be migrated over to the SQLite store.
195///
196/// * `path` - The path where the SQLite store should be created.
197///
198/// * `passphrase` - The passphrase that should be used to encrypt the data at
199///   rest in the SQLite store. **Warning**, if no passphrase is given, the
200///   store and all its data will remain unencrypted.
201///
202/// * `progress_listener` - A callback that can be used to introspect the
203///   progress of the migration.
204#[matrix_sdk_ffi_macros::export]
205pub fn migrate(
206    data: MigrationData,
207    path: String,
208    passphrase: Option<String>,
209    progress_listener: Box<dyn ProgressListener>,
210) -> Result<(), MigrationError> {
211    let runtime = Runtime::new().context("initializing tokio runtime")?;
212    runtime.block_on(async move {
213        migrate_data(data, &path, passphrase, progress_listener).await?;
214        Ok(())
215    })
216}
217
218async fn migrate_data(
219    mut data: MigrationData,
220    path: &str,
221    passphrase: Option<String>,
222    progress_listener: Box<dyn ProgressListener>,
223) -> anyhow::Result<()> {
224    use matrix_sdk_crypto::{olm::PrivateCrossSigningIdentity, store::BackupDecryptionKey};
225    use vodozemac::olm::Account;
226    use zeroize::Zeroize;
227
228    // The total steps here include all the sessions/inbound group sessions and
229    // additionally some static number of steps:
230    //
231    // 1. opening the store
232    // 2. the Account
233    // 3. the cross signing keys
234    // 4. the tracked users
235    // 5. the final save operation
236    let total_steps = 5 + data.sessions.len() + data.inbound_group_sessions.len();
237    let mut processed_steps = 0;
238    let listener = |progress: usize, total: usize| {
239        progress_listener.on_progress(progress as i32, total as i32)
240    };
241
242    let store = SqliteCryptoStore::open(path, passphrase.as_deref()).await?;
243
244    processed_steps += 1;
245    listener(processed_steps, total_steps);
246
247    let user_id = parse_user_id(&data.account.user_id)?;
248    let device_id: OwnedDeviceId = data.account.device_id.into();
249
250    let account = Account::from_libolm_pickle(&data.account.pickle, &data.pickle_key)?;
251    let pickle = account.pickle();
252    let identity_keys = Arc::new(account.identity_keys());
253    let pickled_account = matrix_sdk_crypto::olm::PickledAccount {
254        user_id: parse_user_id(&data.account.user_id)?,
255        device_id: device_id.clone(),
256        pickle,
257        dehydrated: false, // dehydrated devices are never involved in migration
258        shared: data.account.shared,
259        uploaded_signed_key_count: data.account.uploaded_signed_key_count as u64,
260        creation_local_time: MilliSecondsSinceUnixEpoch::now(),
261        fallback_key_creation_timestamp: Some(MilliSecondsSinceUnixEpoch::now()),
262    };
263    let account = matrix_sdk_crypto::olm::Account::from_pickle(pickled_account)?;
264
265    processed_steps += 1;
266    listener(processed_steps, total_steps);
267
268    let (sessions, inbound_group_sessions) = collect_sessions(
269        processed_steps,
270        total_steps,
271        &listener,
272        &data.pickle_key,
273        user_id.clone(),
274        device_id,
275        identity_keys,
276        data.sessions,
277        data.inbound_group_sessions,
278    )?;
279
280    let backup_decryption_key = data
281        .backup_recovery_key
282        .map(|k| BackupDecryptionKey::from_base58(k.as_str()))
283        .transpose()?;
284
285    let cross_signing = PrivateCrossSigningIdentity::empty((*user_id).into());
286    cross_signing
287        .import_secrets_unchecked(
288            data.cross_signing.master_key.as_deref(),
289            data.cross_signing.self_signing_key.as_deref(),
290            data.cross_signing.user_signing_key.as_deref(),
291        )
292        .await?;
293
294    data.cross_signing.master_key.zeroize();
295    data.cross_signing.self_signing_key.zeroize();
296    data.cross_signing.user_signing_key.zeroize();
297
298    processed_steps += 1;
299    listener(processed_steps, total_steps);
300
301    let tracked_users: Vec<_> = data
302        .tracked_users
303        .into_iter()
304        .filter_map(|s| parse_user_id(&s).ok().map(|u| (u, true)))
305        .collect();
306
307    let tracked_users: Vec<_> = tracked_users.iter().map(|(u, d)| (&**u, *d)).collect();
308    store.save_tracked_users(tracked_users.as_slice()).await?;
309
310    processed_steps += 1;
311    listener(processed_steps, total_steps);
312
313    let mut room_settings = HashMap::new();
314    for (room_id, settings) in data.room_settings {
315        let room_id = RoomId::parse(room_id)?;
316        room_settings.insert(room_id, settings.into());
317    }
318
319    store.save_pending_changes(PendingChanges { account: Some(account) }).await?;
320
321    let changes = Changes {
322        private_identity: Some(cross_signing),
323        sessions,
324        inbound_group_sessions,
325        backup_decryption_key,
326        backup_version: data.backup_version,
327        room_settings,
328        ..Default::default()
329    };
330
331    save_changes(processed_steps, total_steps, &listener, changes, &store).await
332}
333
334async fn save_changes(
335    mut processed_steps: usize,
336    total_steps: usize,
337    listener: &dyn Fn(usize, usize),
338    changes: Changes,
339    store: &SqliteCryptoStore,
340) -> anyhow::Result<()> {
341    store.save_changes(changes).await?;
342
343    processed_steps += 1;
344    listener(processed_steps, total_steps);
345
346    Ok(())
347}
348
349/// Migrate sessions and group sessions of a libolm based setup to a vodozemac
350/// based setup stored in a SQLite store.
351///
352/// This method allows you to migrate a subset of the data, it should only be
353/// used after the [`migrate()`] method has been already used.
354///
355/// # Arguments
356///
357/// * `data` - The data that should be migrated over to the SQLite store.
358///
359/// * `path` - The path where the SQLite store should be created.
360///
361/// * `passphrase` - The passphrase that should be used to encrypt the data at
362///   rest in the SQLite store. **Warning**, if no passphrase is given, the
363///   store and all its data will remain unencrypted.
364///
365/// * `progress_listener` - A callback that can be used to introspect the
366///   progress of the migration.
367#[matrix_sdk_ffi_macros::export]
368pub fn migrate_sessions(
369    data: SessionMigrationData,
370    path: String,
371    passphrase: Option<String>,
372    progress_listener: Box<dyn ProgressListener>,
373) -> Result<(), MigrationError> {
374    let runtime = Runtime::new().context("initializing tokio runtime")?;
375    runtime.block_on(migrate_session_data(data, &path, passphrase, progress_listener))?;
376    Ok(())
377}
378
379async fn migrate_session_data(
380    data: SessionMigrationData,
381    path: &str,
382    passphrase: Option<String>,
383    progress_listener: Box<dyn ProgressListener>,
384) -> anyhow::Result<()> {
385    let store = SqliteCryptoStore::open(path, passphrase.as_deref()).await?;
386
387    let listener = |progress: usize, total: usize| {
388        progress_listener.on_progress(progress as i32, total as i32)
389    };
390
391    let total_steps = 1 + data.sessions.len() + data.inbound_group_sessions.len();
392    let processed_steps = 0;
393
394    let user_id = UserId::parse(data.user_id)?;
395    let device_id: OwnedDeviceId = data.device_id.into();
396
397    let identity_keys = IdentityKeys {
398        ed25519: Ed25519PublicKey::from_base64(&data.ed25519_key)?,
399        curve25519: Curve25519PublicKey::from_base64(&data.curve25519_key)?,
400    }
401    .into();
402
403    let (sessions, inbound_group_sessions) = collect_sessions(
404        processed_steps,
405        total_steps,
406        &listener,
407        &data.pickle_key,
408        user_id,
409        device_id,
410        identity_keys,
411        data.sessions,
412        data.inbound_group_sessions,
413    )?;
414
415    let changes = Changes { sessions, inbound_group_sessions, ..Default::default() };
416    save_changes(processed_steps, total_steps, &listener, changes, &store).await
417}
418
419#[allow(clippy::too_many_arguments)]
420fn collect_sessions(
421    mut processed_steps: usize,
422    total_steps: usize,
423    listener: &dyn Fn(usize, usize),
424    pickle_key: &[u8],
425    user_id: OwnedUserId,
426    device_id: OwnedDeviceId,
427    identity_keys: Arc<IdentityKeys>,
428    session_pickles: Vec<PickledSession>,
429    group_session_pickles: Vec<PickledInboundGroupSession>,
430) -> anyhow::Result<(Vec<Session>, Vec<InboundGroupSession>)> {
431    let mut sessions = Vec::new();
432
433    // Create a DeviceKeys struct with enough information to get a working
434    // Session, but we will won't actually use the Sessions (and we'll clear
435    // the session cache after migration) so we don't need to worry about
436    // signatures.
437    let device_keys = DeviceKeys::new(
438        user_id,
439        device_id.clone(),
440        Default::default(),
441        BTreeMap::from([
442            (
443                DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, &device_id),
444                DeviceKey::Ed25519(identity_keys.ed25519),
445            ),
446            (
447                DeviceKeyId::from_parts(DeviceKeyAlgorithm::Curve25519, &device_id),
448                DeviceKey::Curve25519(identity_keys.curve25519),
449            ),
450        ]),
451        Default::default(),
452    );
453
454    for session_pickle in session_pickles {
455        let pickle =
456            vodozemac::olm::Session::from_libolm_pickle(&session_pickle.pickle, pickle_key)?
457                .pickle();
458
459        let creation_time = SecondsSinceUnixEpoch(
460            UInt::new(session_pickle.creation_time).context("invalid creation timestamp")?,
461        );
462        let last_use_time = SecondsSinceUnixEpoch(
463            UInt::new(session_pickle.last_use_time).context("invalid last use timestamp")?,
464        );
465
466        let pickle = matrix_sdk_crypto::olm::PickledSession {
467            pickle,
468            sender_key: Curve25519PublicKey::from_base64(&session_pickle.sender_key)?,
469            created_using_fallback_key: session_pickle.created_using_fallback_key,
470            creation_time,
471            last_use_time,
472        };
473
474        let session = Session::from_pickle(device_keys.clone(), pickle)?;
475
476        sessions.push(session);
477        processed_steps += 1;
478        listener(processed_steps, total_steps);
479    }
480
481    let mut inbound_group_sessions = Vec::new();
482
483    for session in group_session_pickles {
484        let pickle = vodozemac::megolm::InboundGroupSession::from_libolm_pickle(
485            &session.pickle,
486            pickle_key,
487        )?
488        .pickle();
489
490        let sender_key = Curve25519PublicKey::from_base64(&session.sender_key)?;
491
492        let pickle = matrix_sdk_crypto::olm::PickledInboundGroupSession {
493            pickle,
494            sender_key,
495            signing_key: session
496                .signing_key
497                .into_iter()
498                .map(|(k, v)| {
499                    let algorithm = DeviceKeyAlgorithm::from(k);
500                    let key = SigningKey::from_parts(&algorithm, v)?;
501
502                    Ok((algorithm, key))
503                })
504                .collect::<anyhow::Result<_>>()?,
505            sender_data: SenderData::legacy(),
506            room_id: RoomId::parse(session.room_id)?,
507            imported: session.imported,
508            backed_up: session.backed_up,
509            history_visibility: None,
510            shared_history: false,
511            algorithm: RustEventEncryptionAlgorithm::MegolmV1AesSha2,
512        };
513
514        let session = matrix_sdk_crypto::olm::InboundGroupSession::from_pickle(pickle)?;
515
516        inbound_group_sessions.push(session);
517        processed_steps += 1;
518        listener(processed_steps, total_steps);
519    }
520
521    Ok((sessions, inbound_group_sessions))
522}
523
524/// Migrate room settings, including room algorithm and whether to block
525/// untrusted devices from legacy store to Sqlite store.
526///
527/// Note that this method should only be used if a client has already migrated
528/// account data via [migrate](#method.migrate) method, which did not include
529/// room settings. For a brand new migration, the [migrate](#method.migrate)
530/// method will take care of room settings automatically, if provided.
531///
532/// # Arguments
533///
534/// * `room_settings` - Map of room settings
535///
536/// * `path` - The path where the Sqlite store should be created.
537///
538/// * `passphrase` - The passphrase that should be used to encrypt the data at
539///   rest in the Sqlite store. **Warning**, if no passphrase is given, the
540///   store and all its data will remain unencrypted.
541#[matrix_sdk_ffi_macros::export]
542pub fn migrate_room_settings(
543    room_settings: HashMap<String, RoomSettings>,
544    path: String,
545    passphrase: Option<String>,
546) -> Result<(), MigrationError> {
547    let runtime = Runtime::new().context("initializing tokio runtime")?;
548    runtime.block_on(async move {
549        let store = SqliteCryptoStore::open(path, passphrase.as_deref())
550            .await
551            .context("opening sqlite crypto store")?;
552
553        let mut rust_settings = HashMap::new();
554        for (room_id, settings) in room_settings {
555            let room_id = RoomId::parse(room_id).context("parsing room ID")?;
556            rust_settings.insert(room_id, settings.into());
557        }
558
559        let changes = Changes { room_settings: rust_settings, ..Default::default() };
560        store.save_changes(changes).await.context("saving changes")?;
561
562        Ok(())
563    })
564}
565
566/// Callback that will be passed over the FFI to report progress
567#[matrix_sdk_ffi_macros::export(callback_interface)]
568pub trait ProgressListener {
569    /// The callback that should be called on the Rust side
570    ///
571    /// # Arguments
572    ///
573    /// * `progress` - The current number of items that have been handled
574    ///
575    /// * `total` - The total number of items that will be handled
576    fn on_progress(&self, progress: i32, total: i32);
577}
578
579impl<T: Fn(i32, i32)> ProgressListener for T {
580    fn on_progress(&self, progress: i32, total: i32) {
581        self(progress, total)
582    }
583}
584
585/// An encryption algorithm to be used to encrypt messages sent to a room.
586#[derive(Debug, Deserialize, Serialize, PartialEq, uniffi::Enum)]
587pub enum EventEncryptionAlgorithm {
588    /// Olm version 1 using Curve25519, AES-256, and SHA-256.
589    OlmV1Curve25519AesSha2,
590    /// Megolm version 1 using AES-256 and SHA-256.
591    MegolmV1AesSha2,
592}
593
594impl From<EventEncryptionAlgorithm> for RustEventEncryptionAlgorithm {
595    fn from(a: EventEncryptionAlgorithm) -> Self {
596        match a {
597            EventEncryptionAlgorithm::OlmV1Curve25519AesSha2 => Self::OlmV1Curve25519AesSha2,
598            EventEncryptionAlgorithm::MegolmV1AesSha2 => Self::MegolmV1AesSha2,
599        }
600    }
601}
602
603impl TryFrom<RustEventEncryptionAlgorithm> for EventEncryptionAlgorithm {
604    type Error = serde_json::Error;
605
606    fn try_from(value: RustEventEncryptionAlgorithm) -> Result<Self, Self::Error> {
607        match value {
608            RustEventEncryptionAlgorithm::OlmV1Curve25519AesSha2 => {
609                Ok(Self::OlmV1Curve25519AesSha2)
610            }
611            RustEventEncryptionAlgorithm::MegolmV1AesSha2 => Ok(Self::MegolmV1AesSha2),
612            _ => Err(serde::de::Error::custom(format!("Unsupported algorithm {value}"))),
613        }
614    }
615}
616
617/// Who can see a room's history.
618#[derive(uniffi::Enum)]
619pub enum HistoryVisibility {
620    /// Previous events are accessible to newly joined members from the point
621    /// they were invited onwards.
622    ///
623    /// Events stop being accessible when the member's state changes to
624    /// something other than *invite* or *join*.
625    Invited,
626
627    /// Previous events are accessible to newly joined members from the point
628    /// they joined the room onwards.
629    /// Events stop being accessible when the member's state changes to
630    /// something other than *join*.
631    Joined,
632
633    /// Previous events are always accessible to newly joined members.
634    ///
635    /// All events in the room are accessible, even those sent when the member
636    /// was not a part of the room.
637    Shared,
638
639    /// All events while this is the `HistoryVisibility` value may be shared by
640    /// any participating homeserver with anyone, regardless of whether they
641    /// have ever joined the room.
642    WorldReadable,
643}
644
645impl From<HistoryVisibility> for RustHistoryVisibility {
646    fn from(h: HistoryVisibility) -> Self {
647        match h {
648            HistoryVisibility::Invited => Self::Invited,
649            HistoryVisibility::Joined => Self::Joined,
650            HistoryVisibility::Shared => Self::Shared,
651            HistoryVisibility::WorldReadable => Self::Shared,
652        }
653    }
654}
655
656/// Settings that should be used when a room key is shared.
657///
658/// These settings control which algorithm the room key should use, how long a
659/// room key should be used and some other important information that determines
660/// the lifetime of a room key.
661#[derive(uniffi::Record)]
662pub struct EncryptionSettings {
663    /// The encryption algorithm that should be used in the room.
664    pub algorithm: EventEncryptionAlgorithm,
665    /// How long can the room key be used before it should be rotated. Time in
666    /// seconds.
667    pub rotation_period: u64,
668    /// How many messages should be sent before the room key should be rotated.
669    pub rotation_period_msgs: u64,
670    /// The current history visibility of the room. The visibility will be
671    /// tracked by the room key and the key will be rotated if the visibility
672    /// changes.
673    pub history_visibility: HistoryVisibility,
674    /// Should untrusted devices receive the room key, or should they be
675    /// excluded from the conversation.
676    pub only_allow_trusted_devices: bool,
677    /// Should fail to send when a verified user has unverified devices, or when
678    /// a previously verified user replaces their identity.
679    pub error_on_verified_user_problem: bool,
680}
681
682impl From<EncryptionSettings> for RustEncryptionSettings {
683    fn from(v: EncryptionSettings) -> Self {
684        let sharing_strategy = if v.only_allow_trusted_devices {
685            CollectStrategy::OnlyTrustedDevices
686        } else if v.error_on_verified_user_problem {
687            CollectStrategy::ErrorOnVerifiedUserProblem
688        } else {
689            CollectStrategy::AllDevices
690        };
691
692        RustEncryptionSettings {
693            algorithm: v.algorithm.into(),
694            rotation_period: Duration::from_secs(v.rotation_period),
695            rotation_period_msgs: v.rotation_period_msgs,
696            history_visibility: v.history_visibility.into(),
697            sharing_strategy,
698        }
699    }
700}
701
702/// An event that was successfully decrypted.
703#[derive(uniffi::Record)]
704pub struct DecryptedEvent {
705    /// The decrypted version of the event.
706    pub clear_event: String,
707    /// The claimed curve25519 key of the sender.
708    pub sender_curve25519_key: String,
709    /// The claimed ed25519 key of the sender.
710    pub claimed_ed25519_key: Option<String>,
711    /// The curve25519 chain of the senders that forwarded the Megolm decryption
712    /// key to us. Is empty if the key came directly from the sender of the
713    /// event.
714    pub forwarding_curve25519_chain: Vec<String>,
715    /// The shield state (color and message to display to user) for the event,
716    /// representing the event's authenticity. Computed from the properties of
717    /// the sender user identity and their Olm device.
718    ///
719    /// Note that this is computed at time of decryption, so the value reflects
720    /// the computed event authenticity at that time. Authenticity-related
721    /// properties can change later on, such as when a user identity is
722    /// subsequently verified or a device is deleted.
723    pub shield_state: ShieldState,
724}
725
726/// Take a look at [`matrix_sdk_common::deserialized_responses::ShieldState`]
727/// for more info.
728#[allow(missing_docs)]
729#[derive(uniffi::Enum)]
730pub enum ShieldColor {
731    Red,
732    Grey,
733    None,
734}
735
736/// Take a look at [`matrix_sdk_common::deserialized_responses::ShieldState`]
737/// for more info.
738#[derive(uniffi::Record)]
739#[allow(missing_docs)]
740pub struct ShieldState {
741    color: ShieldColor,
742    code: Option<ShieldStateCode>,
743    message: Option<String>,
744}
745
746impl From<RustShieldState> for ShieldState {
747    fn from(value: RustShieldState) -> Self {
748        match value {
749            RustShieldState::Red { code, message } => Self {
750                color: ShieldColor::Red,
751                code: Some(code),
752                message: Some(message.to_owned()),
753            },
754            RustShieldState::Grey { code, message } => Self {
755                color: ShieldColor::Grey,
756                code: Some(code),
757                message: Some(message.to_owned()),
758            },
759            RustShieldState::None => Self { color: ShieldColor::None, code: None, message: None },
760        }
761    }
762}
763
764/// Struct representing the state of our private cross signing keys, it shows
765/// which private cross signing keys we have locally stored.
766#[derive(Debug, Clone, uniffi::Record)]
767pub struct CrossSigningStatus {
768    /// Do we have the master key.
769    pub has_master: bool,
770    /// Do we have the self signing key, this one is necessary to sign our own
771    /// devices.
772    pub has_self_signing: bool,
773    /// Do we have the user signing key, this one is necessary to sign other
774    /// users.
775    pub has_user_signing: bool,
776}
777
778/// A struct containing private cross signing keys that can be backed up or
779/// uploaded to the secret store.
780#[derive(Deserialize, Serialize, uniffi::Record)]
781pub struct CrossSigningKeyExport {
782    /// The seed of the master key encoded as unpadded base64.
783    pub master_key: Option<String>,
784    /// The seed of the self signing key encoded as unpadded base64.
785    pub self_signing_key: Option<String>,
786    /// The seed of the user signing key encoded as unpadded base64.
787    pub user_signing_key: Option<String>,
788}
789
790/// Struct holding the number of room keys we have.
791#[derive(uniffi::Record)]
792pub struct RoomKeyCounts {
793    /// The total number of room keys.
794    pub total: i64,
795    /// The number of backed up room keys.
796    pub backed_up: i64,
797}
798
799/// Backup keys and information we load from the store.
800#[derive(uniffi::Object)]
801pub struct BackupKeys {
802    /// The recovery key as a base64 encoded string.
803    recovery_key: Arc<BackupRecoveryKey>,
804    /// The version that is used with the recovery key.
805    backup_version: String,
806}
807
808#[matrix_sdk_ffi_macros::export]
809impl BackupKeys {
810    /// Get the recovery key that we're holding on to.
811    pub fn recovery_key(&self) -> Arc<BackupRecoveryKey> {
812        self.recovery_key.clone()
813    }
814
815    /// Get the backups version that we're holding on to.
816    pub fn backup_version(&self) -> String {
817        self.backup_version.to_owned()
818    }
819}
820
821impl TryFrom<matrix_sdk_crypto::store::BackupKeys> for BackupKeys {
822    type Error = ();
823
824    fn try_from(keys: matrix_sdk_crypto::store::BackupKeys) -> Result<Self, Self::Error> {
825        Ok(Self {
826            recovery_key: BackupRecoveryKey {
827                inner: keys.decryption_key.ok_or(())?,
828                passphrase_info: None,
829            }
830            .into(),
831            backup_version: keys.backup_version.ok_or(())?,
832        })
833    }
834}
835
836/// Dehydrated device key
837#[derive(uniffi::Record, Clone)]
838pub struct DehydratedDeviceKey {
839    pub(crate) inner: Vec<u8>,
840}
841
842impl DehydratedDeviceKey {
843    /// Generates a new random pickle key.
844    pub fn new() -> Result<Self, DehydrationError> {
845        let inner = InnerDehydratedDeviceKey::new()?;
846        Ok(inner.into())
847    }
848
849    /// Creates a new dehydration pickle key from the given slice.
850    ///
851    /// Fail if the slice length is not 32.
852    pub fn from_slice(slice: &[u8]) -> Result<Self, DehydrationError> {
853        let inner = InnerDehydratedDeviceKey::from_slice(slice)?;
854        Ok(inner.into())
855    }
856
857    /// Export the [`DehydratedDeviceKey`] as a base64 encoded string.
858    pub fn to_base64(&self) -> String {
859        let inner = InnerDehydratedDeviceKey::from_slice(&self.inner).unwrap();
860        inner.to_base64()
861    }
862}
863impl From<InnerDehydratedDeviceKey> for DehydratedDeviceKey {
864    fn from(pickle_key: InnerDehydratedDeviceKey) -> Self {
865        DehydratedDeviceKey { inner: pickle_key.into() }
866    }
867}
868
869impl From<matrix_sdk_crypto::store::RoomKeyCounts> for RoomKeyCounts {
870    fn from(count: matrix_sdk_crypto::store::RoomKeyCounts) -> Self {
871        Self { total: count.total as i64, backed_up: count.backed_up as i64 }
872    }
873}
874
875impl From<matrix_sdk_crypto::CrossSigningKeyExport> for CrossSigningKeyExport {
876    fn from(e: matrix_sdk_crypto::CrossSigningKeyExport) -> Self {
877        Self {
878            master_key: e.master_key.clone(),
879            self_signing_key: e.self_signing_key.clone(),
880            user_signing_key: e.user_signing_key.clone(),
881        }
882    }
883}
884
885impl From<CrossSigningKeyExport> for matrix_sdk_crypto::CrossSigningKeyExport {
886    fn from(e: CrossSigningKeyExport) -> Self {
887        matrix_sdk_crypto::CrossSigningKeyExport {
888            master_key: e.master_key,
889            self_signing_key: e.self_signing_key,
890            user_signing_key: e.user_signing_key,
891        }
892    }
893}
894
895impl From<matrix_sdk_crypto::CrossSigningStatus> for CrossSigningStatus {
896    fn from(s: matrix_sdk_crypto::CrossSigningStatus) -> Self {
897        Self {
898            has_master: s.has_master,
899            has_self_signing: s.has_self_signing,
900            has_user_signing: s.has_user_signing,
901        }
902    }
903}
904
905/// Room encryption settings which are modified by state events or user options
906#[derive(Debug, PartialEq, Deserialize, Serialize, uniffi::Record)]
907pub struct RoomSettings {
908    /// The encryption algorithm that should be used in the room.
909    pub algorithm: EventEncryptionAlgorithm,
910    /// Should untrusted devices receive the room key, or should they be
911    /// excluded from the conversation.
912    pub only_allow_trusted_devices: bool,
913}
914
915impl TryFrom<RustRoomSettings> for RoomSettings {
916    type Error = serde_json::Error;
917
918    fn try_from(value: RustRoomSettings) -> Result<Self, Self::Error> {
919        let algorithm = value.algorithm.try_into()?;
920        Ok(Self { algorithm, only_allow_trusted_devices: value.only_allow_trusted_devices })
921    }
922}
923
924impl From<RoomSettings> for RustRoomSettings {
925    fn from(value: RoomSettings) -> Self {
926        Self {
927            algorithm: value.algorithm.into(),
928            only_allow_trusted_devices: value.only_allow_trusted_devices,
929            ..RustRoomSettings::default()
930        }
931    }
932}
933
934fn parse_user_id(user_id: &str) -> Result<OwnedUserId, CryptoStoreError> {
935    ruma::UserId::parse(user_id).map_err(|e| CryptoStoreError::InvalidUserId(user_id.to_owned(), e))
936}
937
938#[matrix_sdk_ffi_macros::export]
939fn version_info() -> VersionInfo {
940    VersionInfo {
941        version: matrix_sdk_crypto::VERSION.to_owned(),
942        vodozemac_version: matrix_sdk_crypto::vodozemac::VERSION.to_owned(),
943        git_description: env!("VERGEN_GIT_DESCRIBE").to_owned(),
944        git_sha: env!("VERGEN_GIT_SHA").to_owned(),
945    }
946}
947
948/// Build-time information about important crates that are used.
949#[derive(uniffi::Record)]
950pub struct VersionInfo {
951    /// The version of the matrix-sdk-crypto crate.
952    pub version: String,
953    /// The version of the vodozemac crate.
954    pub vodozemac_version: String,
955    /// The Git commit hash of the crate's source tree at build time.
956    pub git_sha: String,
957    /// The build-time output of the `git describe` command of the source tree
958    /// of crate.
959    pub git_description: String,
960}
961
962#[matrix_sdk_ffi_macros::export]
963fn version() -> String {
964    matrix_sdk_crypto::VERSION.to_owned()
965}
966
967#[matrix_sdk_ffi_macros::export]
968fn vodozemac_version() -> String {
969    vodozemac::VERSION.to_owned()
970}
971
972/// The encryption component of PkEncryption support.
973///
974/// This struct can be created using a [`Curve25519PublicKey`] corresponding to
975/// a `PkDecryption` object, allowing messages to be encrypted for the
976/// associated decryption object.
977#[derive(uniffi::Object)]
978pub struct PkEncryption {
979    inner: matrix_sdk_crypto::vodozemac::pk_encryption::PkEncryption,
980}
981
982#[matrix_sdk_ffi_macros::export]
983impl PkEncryption {
984    /// Create a new [`PkEncryption`] object from a `Curve25519PublicKey`
985    /// encoded as Base64.
986    ///
987    /// The public key should come from an existing `PkDecryption` object.
988    /// Returns a `DecodeError` if the Curve25519 key could not be decoded
989    /// correctly.
990    #[uniffi::constructor]
991    pub fn from_base64(key: &str) -> Result<Arc<Self>, DecodeError> {
992        let key = vodozemac::Curve25519PublicKey::from_base64(key)
993            .map_err(matrix_sdk_crypto::backups::DecodeError::PublicKey)?;
994        let inner = vodozemac::pk_encryption::PkEncryption::from_key(key);
995
996        Ok(Self { inner }.into())
997    }
998
999    /// Encrypt a message using this [`PkEncryption`] object.
1000    pub fn encrypt(&self, plaintext: &str) -> PkMessage {
1001        use vodozemac::base64_encode;
1002
1003        let message = self.inner.encrypt(plaintext.as_ref());
1004
1005        let vodozemac::pk_encryption::Message { ciphertext, mac, ephemeral_key } = message;
1006
1007        PkMessage {
1008            ciphertext: base64_encode(ciphertext),
1009            mac: base64_encode(mac),
1010            ephemeral_key: ephemeral_key.to_base64(),
1011        }
1012    }
1013}
1014
1015/// A message that was encrypted using a [`PkEncryption`] object.
1016#[derive(uniffi::Record)]
1017pub struct PkMessage {
1018    /// The ciphertext of the message.
1019    pub ciphertext: String,
1020    /// The message authentication code of the message.
1021    ///
1022    /// *Warning*: This does not authenticate the ciphertext.
1023    pub mac: String,
1024    /// The ephemeral Curve25519 key of the message which was used to derive the
1025    /// individual message key.
1026    pub ephemeral_key: String,
1027}
1028
1029uniffi::setup_scaffolding!();
1030
1031#[cfg(test)]
1032mod tests {
1033    use anyhow::Result;
1034    use serde_json::{json, Value};
1035    use tempfile::tempdir;
1036
1037    use super::MigrationData;
1038    use crate::{migrate, EventEncryptionAlgorithm, OlmMachine, RoomSettings};
1039
1040    #[test]
1041    fn android_migration() -> Result<()> {
1042        let data: Value = json!({
1043            "account":{
1044               "user_id":"@ganfra146:matrix.org",
1045               "device_id":"DEWRCMENGS",
1046               "pickle":"FFGTGho89T3Xgd56l+EedOPV37s09RR8aYnS9305qPKF66LG+ly29YpCibjJOvkwm0dZwN9A2bOH/z7WscriqwZn/p0GE6YSNwLzffCy5iROzYzpYzFe0HtiyJmCQWCezvLc5lHV8YsfD00C1pKGX2R9M1wwp3/n4/3VjtTyPsdnmtwAPu4WdcPSkisCaQ3a6JaSKqv8zYzUjnpzgcpXHvPUR5d5+TzXgrVz3BeCOe8NEOWIW6xYUxFtGteYP0BczOkkJ22t7Css0tSMSrYgCll4zZUGNrd6D9b/z7KwcDnb978epsZ16DcZ/aaTxPdM5uDIkHgF/qHWerfxcaqsqs4EQfJdSgOTeqhjHBw1k0uWF2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kP5n+OKKNm2vJTkQFFwF9eOtGy9fNBtS4qo4jvOUJnnAPsrPbGMbBYd1dMC3daHLEwvIKCAVBn7q1Z2c4zAD5eEoY0EwZj/j8x8lGQ8TswFT81ZotW7ZBDai/YtV8mkGfuaWJRI5yHc/bV7GWLF+yrMji/jicBF5jy2UoqwxseqjgTut49FRgBH3h1qwnfYbXD3FvQljyAAgBCiZV726pFRG+sZv0FjDbq0iCKILVSEUDZgmQ",
1047               "shared":true,
1048               "uploaded_signed_key_count":50
1049            },
1050            "sessions":[
1051               {
1052                  "pickle":"cryZlFaQv0hwWe6tTgv75RExFKGnC8tMHBXJYMHOw4s+SdrKUYAMUdGcYD7QukrPklEOy7fJho9YGK/jV04QdA8JABiOfD+ngJTR4V8eZdmDuG08+Q5EL79V81hQwU2fKndP0y/9nAXPUIADYq0Zrg4EsOnXz7aE+hAeBAm0IBog1s8RYUvynZ15uwjbd/OTLP+gpqpX33DwVg2leiBkQetiUSpOpZCuQ8CcZwIA0MoGCqvaT7h76VHX9JxJx+2fCMhsJMx1nhd99WJH1W9ge5CtdbC4KUP92OSxIrPOnMrNcOPJPp/paZP+HFNQ3PDL+z8pGKXmCnrXGSbd7iPHurPYESrVkBzr",
1053                  "sender_key":"WJ6Ce7U67a6jqkHYHd8o0+5H4bqdi9hInZdk0+swuXs",
1054                  "created_using_fallback_key":false,
1055                  "creation_time": 1649425011424u64,
1056                  "last_use_time": 1649425011424u64
1057               },
1058               {
1059                  "pickle":"cryZlFaQv0hwWe6tTgv75RExFKGnC8tMHBXJYMHOw4t2W/lowyrV6SXVZp+uG59im0AAfNSKjhjZuiOpQlX7MS+AOJkCNvyujJ2g3KSjLZ94IkoHxkBDHLWSjwaLPu40rfOzJPDpm0XZsR6bQrsxKOmXLGEw2qw5jOTouzMVL2gvuuTix97nSYSU8j3XvTMRUoh0AF/tUpRLcvEFZeGrdUYmTMlyTv4na+FVUalUZ+jrk8t1/sM99JNq3SY1IBSjrBq/0rCOHieiippz0sw2fe2b87id4rqj1g3R9w2MWTWEdOz3ugjMGYF1YDBQZA1tJZ/hmgppk2AU2xKQXE2X3DgSC6fC66D4",
1060                  "sender_key":"RzRROfmHNlBfzxnNCUYBfn/5oZNQ11XYjDg59hS+mV0",
1061                  "created_using_fallback_key":false,
1062                  "creation_time": 1649425011503u64,
1063                  "last_use_time": 1649425011503u64
1064               },
1065               {
1066                  "pickle":"cryZlFaQv0hwWe6tTgv75RExFKGnC8tMHBXJYMHOw4titbL3SS12PYHpcBPJc6hXnOnZXqrjtjYOD545fck+3utEo8cqqwWubc9tsvxGW3tOWPttLBdAW30Vn8V1M8ebqVCNVWEAb1GKjV4ni8xG7G9SlEcCjLjnF4lJpddSZkqVMFoN0ITr9aSz/eJwXpc3HLreUFXwc8LuQp7krQ4Vt1e5EE/klduqsdurZf5V14RHsmWz2lKjt7nVgtIz/dhtF5F/sGJdg8kCGaHIMSbGAPuPPpa4/Laicb/5otrYt4pg4W4KdFpSGJIcvUQNjXaOZMx3cu/RPJIOyNhx7whG1QiYAUBqAJvr",
1067                  "sender_key":"IXSZugAHig1v8MowE1jxi2wDDDfuZBeJynHlegJVwUc",
1068                  "created_using_fallback_key":false,
1069                  "creation_time": 1649425011566u64,
1070                  "last_use_time": 1649425011566u64
1071               },
1072               {
1073                  "pickle":"SmkDiFZjNukiarQ7XHQo25FILHsuhNOnxy56cMSQU/Y71jaGbJes4YrvN4Dfy4RSONfejEDXDkbW2JudlHHRP/rWEmnfJiGbK6ArbrG2puqIZgOecPnOUgPfCisr49p1Gmf36dPaO5lm/ZSrngfSoxahoeJJE/CcJN98sYM15XytRk2LBwc+CyYDqr4V1qxfsBt6tzJ4+tsAZeRdD0UtipQgysgH56o8N7nKTCkaZz5lfpYCl3FEgwXpLJ0MGQvtQmbORFvOLqR1jZ/EbmNGKiqDDIYsqG0sf78ii1jqfpLDBXLuYDccsg",
1074                  "sender_key":"EB9SC4jVAydKhM6/GcwMc9biKwVNywqW3TerNTrtb1M",
1075                  "created_using_fallback_key":false,
1076                  "creation_time": 1649542063182u64,
1077                  "last_use_time": 1649542063182u64
1078               }
1079            ],
1080            "inbound_group_sessions":[
1081               {
1082                  "pickle":"KoA0sxDNQ7lz0vylU9zlmar0VCVQRMCfRrIfTh1bdMhlAgy8/D2ToT+oKRaKy1HiW6H862bzdpgxprlseSjmip9OfLbIuyd2YZcEinwc2666oEI/hpk4oTlE61uE1M+ThfdFf41yGCmaAP7mhjwF234ZrZ6i/F/qx42TLQ8Unc30wDJaJgyheO5eW85SD/0g0cdg2WnEKrx2/wl7Vg/YijT3JMDZ+OsdfJfSZtxBNjlG+PQ/9D31qb1eHfaovc8vFZh5QLfAFg/5rBrF1PhRsC7xOAZbUNdrTbvypNfMM4mznf84C2SzZRSMeAfg5v/YticM3Keg4eHuEj1WO9DrmRXYl6b/pITdf1xuk5euVT0pyxJpXmq41AoAZKAo1l94HGy1LG1RpruD1uQPhiponh5PGHSOf43Q",
1083                  "sender_key":"vJfH7wiYmGos3C8U1XcJ//YWSmkueAYqrmUA6/ukfAM",
1084                  "signing_key":{
1085                     "ed25519":"JGgPQRuYj3ScMdPS+A0P+k/1qS9Hr3qeKXLscI+hS78"
1086                  },
1087                  "room_id":"!AZkqtjvtwPAuyNOXEt:matrix.org",
1088                  "forwarding_chains":[
1089                  ],
1090                  "imported":true,
1091                  "backed_up":true
1092               },
1093               {
1094                  "pickle":"9RF6GBu9CvjZZx2hxIlw2gMdKs36LFhXhLTHAPrLSjT2OTbeE/jK263+iiFdSpF7Cblp/lXzljPKJN6sL8JGzoT7ssYh56nI0kKsp7/y88z+tTOH/5NYYTmZzHYw6yy4Cmaxh0pdHDs+RQpSSIe9jhF/EJJna5jcKYXxDY52m8H4LECQzVuDlYfblCr9zoYWhQrVhiRDGy7eLhk4X6Rp0Yoek4YUKcCQArDfZ/Vf43qfHUpOJgRpm5Oyj42HA/j4xZBb5U0Fmo6YHRPt0/KuWrDfpgJSGiN0zza7641IfADg8f3WdhlPAWMyri7k4vOZMBjlwFNcMpc0wM2TaTmbi2zqXEKZy9Oh/eJqBapFx0oNWaQ1VQ++iXxGUbZhwy7x2vd6UkqUTwYeym+aP23ee3TCtnNWN0aC",
1095                  "sender_key":"EB9SC4jVAydKhM6/GcwMc9biKwVNywqW3TerNTrtb1M",
1096                  "signing_key":{
1097                     "ed25519":"1NXa5GyJ+p2ruAClEque+TL1VktrBzMW4dZFNfNGrvc"
1098                  },
1099                  "room_id":"!CWLUCoEWXSFyTCOtfL:matrix.org",
1100                  "forwarding_chains":[],
1101                  "imported":true,
1102                  "backed_up":true
1103               }
1104            ],
1105            "pickle_key": [17, 36, 120, 74, 95, 78, 56, 36, 62, 123, 5, 105, 74,
1106                           111, 70, 48, 51, 101, 66, 86, 116, 14, 114, 85, 85,
1107                           92, 44, 71, 89, 99, 55, 74],
1108            "backup_version":"3",
1109            "backup_recovery_key":"EsTHScmRV5oT1WBhe2mj2Gn3odeYantZ4NEk7L51p6L8hrmB",
1110            "cross_signing":{
1111               "master_key":"trnK/dBv/M2x2zZt8lnORHQqmFHWvjYE6rdlAONRUPY",
1112               "self_signing_key":"SJhsj9jXC4hxhqS/1B3RZ65zWMHuF+1fUjWHrzVRh6w",
1113               "user_signing_key":"LPYrV11T9Prm4ZIUxrq2a8Y/F64R1+NaGNyo6GlXjGg"
1114            },
1115            "tracked_users":[
1116               "@ganfra146:matrix.org",
1117               "@this-is-me:matrix.org",
1118               "@Amandine:matrix.org",
1119               "@ganfra:matrix.org",
1120               "NotAUser%ID"
1121            ],
1122            "room_settings": {
1123                "!AZkqtjvtwPAuyNOXEt:matrix.org": {
1124                    "algorithm": "OlmV1Curve25519AesSha2",
1125                    "only_allow_trusted_devices": true
1126                },
1127                "!CWLUCoEWXSFyTCOtfL:matrix.org": {
1128                    "algorithm": "MegolmV1AesSha2",
1129                    "only_allow_trusted_devices": false
1130                },
1131            }
1132        });
1133
1134        let migration_data: MigrationData = serde_json::from_value(data)?;
1135
1136        let dir = tempdir()?;
1137        let path = dir
1138            .path()
1139            .to_str()
1140            .expect("Creating a string from the tempdir path should not fail")
1141            .to_owned();
1142
1143        migrate(migration_data, path.clone(), None, Box::new(|_, _| {}))?;
1144
1145        let machine = OlmMachine::new(
1146            "@ganfra146:matrix.org".to_owned(),
1147            "DEWRCMENGS".to_owned(),
1148            path,
1149            None,
1150        )?;
1151
1152        assert_eq!(
1153            machine.identity_keys()["ed25519"],
1154            "JGgPQRuYj3ScMdPS+A0P+k/1qS9Hr3qeKXLscI+hS78"
1155        );
1156
1157        let room_keys =
1158            machine.runtime.block_on(machine.inner.store().export_room_keys(|_| true))?;
1159        assert_eq!(room_keys.len(), 2);
1160
1161        let cross_signing_status = machine.cross_signing_status();
1162        assert!(cross_signing_status.has_master);
1163        assert!(cross_signing_status.has_user_signing);
1164        assert!(cross_signing_status.has_self_signing);
1165
1166        let backup_keys = machine.get_backup_keys()?;
1167        assert!(backup_keys.is_some());
1168
1169        let settings1 = machine.get_room_settings("!AZkqtjvtwPAuyNOXEt:matrix.org".into())?;
1170        assert_eq!(
1171            Some(RoomSettings {
1172                algorithm: EventEncryptionAlgorithm::OlmV1Curve25519AesSha2,
1173                only_allow_trusted_devices: true
1174            }),
1175            settings1
1176        );
1177
1178        let settings2 = machine.get_room_settings("!CWLUCoEWXSFyTCOtfL:matrix.org".into())?;
1179        assert_eq!(
1180            Some(RoomSettings {
1181                algorithm: EventEncryptionAlgorithm::MegolmV1AesSha2,
1182                only_allow_trusted_devices: false
1183            }),
1184            settings2
1185        );
1186
1187        let settings3 = machine.get_room_settings("!XYZ:matrix.org".into())?;
1188        assert!(settings3.is_none());
1189
1190        assert!(machine.is_user_tracked("@ganfra146:matrix.org".into()).unwrap());
1191        assert!(machine.is_user_tracked("@Amandine:matrix.org".into()).unwrap());
1192        assert!(machine.is_user_tracked("@this-is-me:matrix.org".into()).unwrap());
1193        assert!(machine.is_user_tracked("@ganfra:matrix.org".into()).unwrap());
1194
1195        Ok(())
1196    }
1197}