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