Skip to main content

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