Skip to main content

matrix_sdk_crypto/machine/
mod.rs

1// Copyright 2020, 2026 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#[cfg(feature = "experimental-encrypted-state-events")]
16use std::borrow::Borrow;
17use std::{
18    collections::{BTreeMap, HashMap, HashSet},
19    sync::Arc,
20    time::Duration,
21};
22
23use itertools::Itertools;
24#[cfg(feature = "experimental-send-custom-to-device")]
25use matrix_sdk_common::deserialized_responses::WithheldCode;
26use matrix_sdk_common::{
27    BoxFuture,
28    deserialized_responses::{
29        AlgorithmInfo, DecryptedRoomEvent, DeviceLinkProblem, EncryptionInfo, ForwarderInfo,
30        ProcessedToDeviceEvent, ToDeviceUnableToDecryptInfo, ToDeviceUnableToDecryptReason,
31        UnableToDecryptInfo, UnableToDecryptReason, UnsignedDecryptionResult,
32        UnsignedEventLocation, VerificationLevel, VerificationState,
33    },
34    locks::RwLock as StdRwLock,
35    timer,
36};
37#[cfg(feature = "experimental-encrypted-state-events")]
38use ruma::events::{AnyStateEventContent, StateEventContent};
39use ruma::{
40    DeviceId, DeviceKeyAlgorithm, MilliSecondsSinceUnixEpoch, OneTimeKeyAlgorithm, OwnedDeviceId,
41    OwnedDeviceKeyId, OwnedTransactionId, OwnedUserId, RoomId, TransactionId, UInt, UserId,
42    api::client::{
43        dehydrated_device::DehydratedDeviceData,
44        keys::{
45            claim_keys::v3::Request as KeysClaimRequest,
46            get_keys::v3::Response as KeysQueryResponse,
47            upload_keys::v3::{Request as UploadKeysRequest, Response as UploadKeysResponse},
48            upload_signatures::v3::Request as UploadSignaturesRequest,
49        },
50        sync::sync_events::DeviceLists,
51    },
52    assign,
53    events::{
54        AnyMessageLikeEvent, AnyMessageLikeEventContent, AnyTimelineEvent, AnyToDeviceEvent,
55        MessageLikeEventContent, secret::request::SecretName,
56    },
57    serde::{JsonObject, Raw},
58};
59use serde::Serialize;
60use serde_json::{Value, value::to_raw_value};
61use tokio::sync::Mutex;
62use tracing::{
63    Span, debug, enabled, error,
64    field::{debug, display},
65    info, instrument, trace, warn,
66};
67use vodozemac::{Curve25519PublicKey, Ed25519Signature, megolm::DecryptionError};
68
69#[cfg(feature = "experimental-push-secrets")]
70use crate::error::SecretPushError;
71#[cfg(feature = "experimental-send-custom-to-device")]
72use crate::session_manager::split_devices_for_share_strategy;
73#[cfg(feature = "experimental-x509-identity-verification")]
74use crate::x509::{RawX509Signer, RawX509Verifier, X509Signer, X509Verifier};
75use crate::{
76    CollectStrategy, CryptoStoreError, DecryptionSettings, DeviceData, LocalTrust,
77    OwnUserIdentityData, RoomEventDecryptionResult, SignatureError, TrustRequirement,
78    backups::{BackupMachine, MegolmV1BackupKey},
79    dehydrated_devices::{DehydratedDevices, DehydrationError},
80    error::{EventError, MegolmError, MegolmResult, OlmError, OlmResult, SetRoomSettingsError},
81    gossiping::GossipMachine,
82    identities::{Device, IdentityManager, UserDevices, user::UserIdentity},
83    olm::{
84        Account, CrossSigningStatus, EncryptionSettings, IdentityKeys, InboundGroupSession,
85        KnownSenderData, OlmDecryptionInfo, PrivateCrossSigningIdentity, SenderData,
86        SenderDataFinder, SessionType, StaticAccountData,
87    },
88    session_manager::{GroupSessionManager, SessionManager},
89    store::{
90        CryptoStoreWrapper, DynCryptoStore, IntoCryptoStore, MemoryStore, Result as StoreResult,
91        SecretImportError, Store, StoreTransaction,
92        caches::StoreCache,
93        types::{
94            Changes, CrossSigningKeyExport, DeviceChanges, IdentityChanges, PendingChanges,
95            RoomKeyInfo, RoomSettings, StoredRoomKeyBundleData,
96        },
97    },
98    types::{
99        EventEncryptionAlgorithm, Signatures,
100        events::{
101            ToDeviceEvent, ToDeviceEvents,
102            olm_v1::{AnyDecryptedOlmEvent, DecryptedRoomKeyBundleEvent, DecryptedRoomKeyEvent},
103            room::encrypted::{
104                EncryptedEvent, EncryptedToDeviceEvent, RoomEncryptedEventContent,
105                RoomEventEncryptionScheme, SupportedEventEncryptionSchemes,
106                ToDeviceEncryptedEventContent,
107            },
108            room_key::{MegolmV1AesSha2Content, RoomKeyContent},
109            room_key_bundle::RoomKeyBundleContent,
110            room_key_withheld::{
111                MegolmV1AesSha2WithheldContent, RoomKeyWithheldContent, RoomKeyWithheldEvent,
112            },
113        },
114        requests::{
115            AnyIncomingResponse, KeysQueryRequest, OutgoingRequest, ToDeviceRequest,
116            UploadSigningKeysRequest,
117        },
118    },
119    utilities::timestamp_to_iso8601,
120    verification::{Verification, VerificationMachine, VerificationRequest},
121};
122
123#[derive(Debug, Serialize)]
124/// The result of encrypting a room event.
125pub struct RawEncryptionResult {
126    /// The encrypted event content.
127    pub content: Raw<RoomEncryptedEventContent>,
128    /// Information about the encryption that was performed.
129    pub encryption_info: EncryptionInfo,
130}
131
132/// A builder object to help creating an [`OlmMachine`] instance.
133pub struct OlmMachineBuilder {
134    /// The unique id of the user that owns the machine to be built.
135    user_id: OwnedUserId,
136
137    /// The unique id of the device that owns the machine to be built.
138    device_id: OwnedDeviceId,
139
140    /// `CryptoStore` implementation. If not populated, a [`MemoryStore`] will
141    /// be created.
142    store: Option<Arc<DynCryptoStore>>,
143
144    /// Optional override for the vodozemac `Account` that will be used for this
145    /// OlmMachine.
146    custom_account: Option<vodozemac::olm::Account>,
147
148    /// Optional X509 verifier to be used for verifying people's identities.
149    #[cfg(feature = "experimental-x509-identity-verification")]
150    x509_verifier: Option<X509Verifier>,
151
152    /// Optional X509 signer to be used for signing our own identity.
153    #[cfg(feature = "experimental-x509-identity-verification")]
154    x509_signer: Option<X509Signer>,
155}
156
157impl OlmMachineBuilder {
158    /// Create a new `OlmMachineBuilder` which will create an [`OlmMachine`]
159    /// belonging to the given user id / device id.
160    pub fn new(user_id: &UserId, device_id: &DeviceId) -> Self {
161        Self {
162            user_id: user_id.to_owned(),
163            device_id: device_id.to_owned(),
164            store: None,
165            custom_account: None,
166            #[cfg(feature = "experimental-x509-identity-verification")]
167            x509_verifier: None,
168            #[cfg(feature = "experimental-x509-identity-verification")]
169            x509_signer: None,
170        }
171    }
172
173    /// Set the [`CryptoStore`] implementation that will be used to store the
174    /// encryption keys.
175    ///
176    /// If this is not populated before [`OlmMachineBuilder::build`] is called,
177    /// a new [`MemoryStore`] will be created.
178    ///
179    /// [`CryptoStore`]: crate::store::CryptoStore
180    pub fn with_crypto_store(mut self, store: impl IntoCryptoStore) -> Self {
181        self.store = Some(store.into_crypto_store());
182        self
183    }
184
185    /// Set a custom [`vodozemac::olm::Account`] to be used for the identity and
186    /// one-time keys of this [`OlmMachine`]. If this is not set before
187    /// [`OlmMachineBuilder::build`] is called, a new default one or one from
188    /// the store will be used.
189    ///
190    /// If an account is provided and one already exists in the store for this
191    /// [`UserId`]/[`DeviceId`] combination, an error will be raised. This is
192    /// useful if one wishes to create identity keys before knowing the
193    /// user/device IDs, e.g., to use the identity key as the device ID.
194    pub fn with_custom_account(mut self, custom_account: Option<vodozemac::olm::Account>) -> Self {
195        self.custom_account = custom_account;
196        self
197    }
198
199    /// Specify a [`RawX509Verifier`] which the `OlmMachine` should use to
200    /// verify people's identities.
201    #[cfg(feature = "experimental-x509-identity-verification")]
202    pub fn with_x509_verifier(mut self, x509_verifier: Option<Arc<dyn RawX509Verifier>>) -> Self {
203        self.x509_verifier = x509_verifier.map(X509Verifier::new);
204        self
205    }
206
207    /// Specify a [`RawX509Signer`] which the `OlmMachine` should use to sign
208    /// our own identity.
209    #[cfg(feature = "experimental-x509-identity-verification")]
210    pub fn with_x509_signer(mut self, x509_signer: Option<Arc<dyn RawX509Signer>>) -> Self {
211        self.x509_signer = x509_signer.map(X509Signer::new);
212        self
213    }
214
215    /// Construct a new [`OlmMachine`] from this builder.
216    ///
217    /// If a store was given via [`OlmMachineBuilder::with_crypto_store`], and
218    /// the store already contains encryption keys for the given user/device
219    /// pair, those will be re-used. Otherwise new device keys will be created
220    /// and stored.
221    pub async fn build(self) -> Result<OlmMachine, CryptoStoreError> {
222        OlmMachine::from_builder(self).await
223    }
224}
225
226impl std::fmt::Debug for OlmMachineBuilder {
227    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228        f.debug_struct("OlmMachineBuilder")
229            .field("user_id", &self.user_id)
230            .field("device_id", &self.device_id)
231            .finish_non_exhaustive()
232    }
233}
234
235/// State machine implementation of the Olm/Megolm encryption protocol used for
236/// Matrix end to end encryption.
237#[derive(Clone)]
238pub struct OlmMachine {
239    pub(crate) inner: Arc<OlmMachineInner>,
240}
241
242pub struct OlmMachineInner {
243    /// The unique user id that owns this account.
244    user_id: OwnedUserId,
245    /// The unique device ID of the device that holds this account.
246    device_id: OwnedDeviceId,
247    /// The private part of our cross signing identity. Used to sign devices and
248    /// other users, might be missing if some other device bootstrapped cross
249    /// signing or cross signing isn't bootstrapped at all.
250    user_identity: Arc<Mutex<PrivateCrossSigningIdentity>>,
251    /// Store for the encryption keys. Persists all the encryption keys so a
252    /// client can resume the session without the need to create new keys.
253    store: Store,
254    /// A state machine that handles Olm sessions creation.
255    session_manager: SessionManager,
256    /// A state machine that keeps track of our outbound group sessions.
257    pub(crate) group_session_manager: GroupSessionManager,
258    /// A state machine that is responsible to handle and keep track of SAS
259    /// verification flows.
260    verification_machine: VerificationMachine,
261    /// The state machine that is responsible to handle outgoing and incoming
262    /// key requests.
263    pub(crate) key_request_machine: GossipMachine,
264    /// State machine handling public user identities and devices, keeping track
265    /// of when a key query needs to be done and handling one.
266    identity_manager: IdentityManager,
267    /// A state machine that handles creating room key backups.
268    backup_machine: BackupMachine,
269}
270
271#[cfg(not(tarpaulin_include))]
272impl std::fmt::Debug for OlmMachine {
273    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
274        f.debug_struct("OlmMachine")
275            .field("user_id", &self.user_id())
276            .field("device_id", &self.device_id())
277            .finish()
278    }
279}
280
281impl OlmMachine {
282    const CURRENT_GENERATION_STORE_KEY: &'static str = "generation-counter";
283    const HAS_MIGRATED_VERIFICATION_LATCH: &'static str = "HAS_MIGRATED_VERIFICATION_LATCH";
284
285    /// Create a new memory based OlmMachine.
286    ///
287    /// The created machine will keep the encryption keys only in memory and
288    /// once the object is dropped the keys will be lost.
289    ///
290    /// # Arguments
291    ///
292    /// - `user_id` - The unique id of the user that owns this machine.
293    /// - `device_id` - The unique id of the device that owns this machine.
294    pub async fn new(user_id: &UserId, device_id: &DeviceId) -> Self {
295        OlmMachineBuilder::new(user_id, device_id)
296            .build()
297            .await
298            .expect("Reading and writing to the memory store always succeeds")
299    }
300
301    pub(crate) async fn rehydrate(
302        &self,
303        pickle_key: &[u8; 32],
304        device_id: &DeviceId,
305        device_data: Raw<DehydratedDeviceData>,
306    ) -> Result<OlmMachine, DehydrationError> {
307        let account = Account::rehydrate(pickle_key, self.user_id(), device_id, device_data)?;
308        let static_account = account.static_data().clone();
309
310        let store =
311            Arc::new(CryptoStoreWrapper::new(self.user_id(), device_id, MemoryStore::new()));
312        let device = DeviceData::from_account(&account);
313        store.save_pending_changes(PendingChanges { account: Some(account) }).await?;
314        store
315            .save_changes(Changes {
316                devices: DeviceChanges { new: vec![device], ..Default::default() },
317                ..Default::default()
318            })
319            .await?;
320
321        let (verification_machine, store, identity_manager) = Self::new_helper_prelude(
322            store,
323            static_account,
324            self.store().private_identity(),
325            #[cfg(feature = "experimental-x509-identity-verification")]
326            self.store().x509_verifier().cloned(),
327            #[cfg(feature = "experimental-x509-identity-verification")]
328            self.store().x509_signer().cloned(),
329        );
330
331        Ok(Self::new_helper(
332            device_id,
333            store,
334            verification_machine,
335            identity_manager,
336            self.store().private_identity(),
337            None,
338        ))
339    }
340
341    fn new_helper_prelude(
342        store_wrapper: Arc<CryptoStoreWrapper>,
343        account: StaticAccountData,
344        user_identity: Arc<Mutex<PrivateCrossSigningIdentity>>,
345        #[cfg(feature = "experimental-x509-identity-verification")] x509_verifier: Option<
346            X509Verifier,
347        >,
348        #[cfg(feature = "experimental-x509-identity-verification")] x509_signer: Option<X509Signer>,
349    ) -> (VerificationMachine, Store, IdentityManager) {
350        let verification_machine =
351            VerificationMachine::new(account.clone(), user_identity.clone(), store_wrapper.clone());
352
353        let store = Store::new_with_x509(
354            account,
355            user_identity,
356            store_wrapper,
357            verification_machine.clone(),
358            #[cfg(feature = "experimental-x509-identity-verification")]
359            x509_verifier,
360            #[cfg(feature = "experimental-x509-identity-verification")]
361            x509_signer,
362        );
363
364        let identity_manager = IdentityManager::new(store.clone());
365
366        (verification_machine, store, identity_manager)
367    }
368
369    fn new_helper(
370        device_id: &DeviceId,
371        store: Store,
372        verification_machine: VerificationMachine,
373        identity_manager: IdentityManager,
374        user_identity: Arc<Mutex<PrivateCrossSigningIdentity>>,
375        maybe_backup_key: Option<MegolmV1BackupKey>,
376    ) -> Self {
377        let group_session_manager = GroupSessionManager::new(store.clone());
378
379        let users_for_key_claim = Arc::new(StdRwLock::new(BTreeMap::new()));
380        let key_request_machine = GossipMachine::new(
381            store.clone(),
382            identity_manager.clone(),
383            group_session_manager.session_cache(),
384            users_for_key_claim.clone(),
385        );
386
387        let session_manager =
388            SessionManager::new(users_for_key_claim, key_request_machine.clone(), store.clone());
389
390        let backup_machine = BackupMachine::new(store.clone(), maybe_backup_key);
391
392        let inner = Arc::new(OlmMachineInner {
393            user_id: store.user_id().to_owned(),
394            device_id: device_id.to_owned(),
395            user_identity,
396            store,
397            session_manager,
398            group_session_manager,
399            verification_machine,
400            key_request_machine,
401            identity_manager,
402            backup_machine,
403        });
404
405        Self { inner }
406    }
407
408    #[instrument(skip(builder), fields(user_id, device_id, ed25519_key, curve25519_key))]
409    pub(crate) async fn from_builder(builder: OlmMachineBuilder) -> StoreResult<Self> {
410        let OlmMachineBuilder {
411            user_id,
412            device_id,
413            store,
414            custom_account,
415            #[cfg(feature = "experimental-x509-identity-verification")]
416            x509_verifier,
417            #[cfg(feature = "experimental-x509-identity-verification")]
418            x509_signer,
419        } = builder;
420
421        Span::current()
422            .record("user_id", display(&user_id))
423            .record("device_id", display(&device_id));
424
425        let store = store.unwrap_or_else(|| MemoryStore::new().into_crypto_store());
426
427        let static_account = match store.load_account().await? {
428            Some(account) => {
429                if user_id != account.user_id()
430                    || device_id != account.device_id()
431                    || custom_account.is_some()
432                {
433                    return Err(CryptoStoreError::MismatchedAccount {
434                        expected: (account.user_id().to_owned(), account.device_id().to_owned()),
435                        got: (user_id.to_owned(), device_id.to_owned()),
436                    });
437                }
438
439                Span::current()
440                    .record("ed25519_key", display(account.identity_keys().ed25519))
441                    .record("curve25519_key", display(account.identity_keys().curve25519));
442                debug!("Restored an Olm account");
443
444                account.static_data().clone()
445            }
446
447            None => {
448                let account = if let Some(account) = custom_account {
449                    Account::new_helper(account, &user_id, &device_id)
450                } else {
451                    Account::with_device_id(&user_id, &device_id)
452                };
453
454                let static_account = account.static_data().clone();
455
456                Span::current()
457                    .record("ed25519_key", display(account.identity_keys().ed25519))
458                    .record("curve25519_key", display(account.identity_keys().curve25519));
459
460                let device = DeviceData::from_account(&account);
461
462                // We just created this device from our own Olm `Account`. Since
463                // we are the owners of the private keys of this device we can
464                // safely mark the device as verified.
465                device.set_trust_state(LocalTrust::Verified);
466
467                let changes = Changes {
468                    devices: DeviceChanges { new: vec![device], ..Default::default() },
469                    ..Default::default()
470                };
471                store.save_changes(changes).await?;
472                store.save_pending_changes(PendingChanges { account: Some(account) }).await?;
473
474                debug!("Created a new Olm account");
475
476                static_account
477            }
478        };
479
480        let identity = match store.load_identity().await? {
481            Some(i) => {
482                let master_key = i
483                    .master_public_key()
484                    .await
485                    .and_then(|m| m.get_first_key().map(|m| m.to_owned()));
486                debug!(?master_key, "Restored the cross signing identity");
487                i
488            }
489            None => {
490                debug!("Creating an empty cross signing identity stub");
491                PrivateCrossSigningIdentity::empty(&user_id)
492            }
493        };
494
495        // FIXME: This is a workaround for `regenerate_olm` clearing the backup
496        // state. Ideally, backups should not get automatically enabled since
497        // the `OlmMachine` doesn't get enough info from the homeserver for this
498        // to work reliably.
499        let saved_keys = store.load_backup_keys().await?;
500        let maybe_backup_key = saved_keys.decryption_key.and_then(|k| {
501            if let Some(version) = saved_keys.backup_version {
502                let megolm_v1_backup_key = k.megolm_v1_public_key();
503                megolm_v1_backup_key.set_version(version);
504                Some(megolm_v1_backup_key)
505            } else {
506                None
507            }
508        });
509
510        let identity = Arc::new(Mutex::new(identity));
511        let store = Arc::new(CryptoStoreWrapper::new(&user_id, &device_id, store));
512
513        let (verification_machine, store, identity_manager) = Self::new_helper_prelude(
514            store,
515            static_account,
516            identity.clone(),
517            #[cfg(feature = "experimental-x509-identity-verification")]
518            x509_verifier,
519            #[cfg(feature = "experimental-x509-identity-verification")]
520            x509_signer,
521        );
522
523        // FIXME: We might want in the future a more generic high-level data
524        // migration mechanism (at the store wrapper layer).
525        Self::migration_post_verified_latch_support(&store, &identity_manager).await?;
526
527        Ok(Self::new_helper(
528            &device_id,
529            store,
530            verification_machine,
531            identity_manager,
532            identity,
533            maybe_backup_key,
534        ))
535    }
536
537    // The sdk now support verified identity change detection. This introduces a
538    // new local flag (`verified_latch` on `OtherUserIdentityData`). In order to
539    // ensure that this flag is up-to-date and for the sake of simplicity we
540    // force a re-download of tracked users by marking them as dirty.
541    //
542    // pub(crate) visibility for testing.
543    pub(crate) async fn migration_post_verified_latch_support(
544        store: &Store,
545        identity_manager: &IdentityManager,
546    ) -> Result<(), CryptoStoreError> {
547        let maybe_migrate_for_identity_verified_latch =
548            store.get_custom_value(Self::HAS_MIGRATED_VERIFICATION_LATCH).await?.is_none();
549
550        if maybe_migrate_for_identity_verified_latch {
551            identity_manager.mark_all_tracked_users_as_dirty(store.cache().await?).await?;
552
553            store.set_custom_value(Self::HAS_MIGRATED_VERIFICATION_LATCH, vec![0]).await?
554        }
555        Ok(())
556    }
557
558    /// Get the crypto store associated with this `OlmMachine` instance.
559    pub fn store(&self) -> &Store {
560        &self.inner.store
561    }
562
563    /// The unique user id that owns this `OlmMachine` instance.
564    pub fn user_id(&self) -> &UserId {
565        &self.inner.user_id
566    }
567
568    /// The unique device ID that identifies this `OlmMachine`.
569    pub fn device_id(&self) -> &DeviceId {
570        &self.inner.device_id
571    }
572
573    /// The time at which the `Account` backing this `OlmMachine` was created.
574    ///
575    /// An [`Account`] is created when an `OlmMachine` is first instantiated
576    /// against a given [`Store`], at which point it creates identity keys etc.
577    /// This method returns the timestamp, according to the local clock, at
578    /// which that happened.
579    pub fn device_creation_time(&self) -> MilliSecondsSinceUnixEpoch {
580        self.inner.store.static_account().creation_local_time()
581    }
582
583    /// Get the public parts of our Olm identity keys.
584    pub fn identity_keys(&self) -> IdentityKeys {
585        let account = self.inner.store.static_account();
586        account.identity_keys()
587    }
588
589    /// Get the display name of our own device
590    pub async fn display_name(&self) -> StoreResult<Option<String>> {
591        self.store().device_display_name().await
592    }
593
594    /// Get the list of "tracked users".
595    ///
596    /// See [`update_tracked_users`](#method.update_tracked_users) for more
597    /// information.
598    pub async fn tracked_users(&self) -> StoreResult<HashSet<OwnedUserId>> {
599        let cache = self.store().cache().await?;
600        Ok(self.inner.identity_manager.key_query_manager.synced(&cache).await?.tracked_users())
601    }
602
603    /// Enable or disable room key requests.
604    ///
605    /// Room key requests allow the device to request room keys that it might
606    /// have missed in the original share using `m.room_key_request` events.
607    ///
608    /// See also [`OlmMachine::set_room_key_forwarding_enabled`] and
609    /// [`OlmMachine::are_room_key_requests_enabled`].
610    #[cfg(feature = "automatic-room-key-forwarding")]
611    pub fn set_room_key_requests_enabled(&self, enable: bool) {
612        self.inner.key_request_machine.set_room_key_requests_enabled(enable)
613    }
614
615    /// Query whether we should send outgoing `m.room_key_request`s on
616    /// decryption failure.
617    ///
618    /// See also [`OlmMachine::set_room_key_requests_enabled`].
619    pub fn are_room_key_requests_enabled(&self) -> bool {
620        self.inner.key_request_machine.are_room_key_requests_enabled()
621    }
622
623    /// Enable or disable room key forwarding.
624    ///
625    /// If room key forwarding is enabled, we will automatically reply to
626    /// incoming `m.room_key_request` messages from verified devices by
627    /// forwarding the requested key (if we have it).
628    ///
629    /// See also [`OlmMachine::set_room_key_requests_enabled`] and
630    /// [`OlmMachine::is_room_key_forwarding_enabled`].
631    #[cfg(feature = "automatic-room-key-forwarding")]
632    pub fn set_room_key_forwarding_enabled(&self, enable: bool) {
633        self.inner.key_request_machine.set_room_key_forwarding_enabled(enable)
634    }
635
636    /// Is room key forwarding enabled?
637    ///
638    /// See also [`OlmMachine::set_room_key_forwarding_enabled`].
639    pub fn is_room_key_forwarding_enabled(&self) -> bool {
640        self.inner.key_request_machine.is_room_key_forwarding_enabled()
641    }
642
643    /// Get the outgoing requests that need to be sent out.
644    ///
645    /// This returns a list of [`OutgoingRequest`]. Those requests need to be
646    /// sent out to the server and the responses need to be passed back to the
647    /// state machine using [`mark_request_as_sent`].
648    ///
649    /// [`mark_request_as_sent`]: #method.mark_request_as_sent
650    pub async fn outgoing_requests(&self) -> StoreResult<Vec<OutgoingRequest>> {
651        let mut requests = Vec::new();
652
653        {
654            let store_cache = self.inner.store.cache().await?;
655            let account = store_cache.account().await?;
656            if let Some(r) = self.keys_for_upload(&account).await.map(|r| OutgoingRequest {
657                request_id: TransactionId::new(),
658                request: Arc::new(r.into()),
659            }) {
660                requests.push(r);
661            }
662        }
663
664        for request in self
665            .inner
666            .identity_manager
667            .users_for_key_query()
668            .await?
669            .into_iter()
670            .map(|(request_id, r)| OutgoingRequest { request_id, request: Arc::new(r.into()) })
671        {
672            requests.push(request);
673        }
674
675        requests.append(&mut self.inner.verification_machine.outgoing_messages());
676        requests.append(&mut self.inner.key_request_machine.outgoing_to_device_requests().await?);
677
678        #[cfg(feature = "experimental-x509-identity-verification")]
679        if let Some(signature_upload_request) =
680            self.inner.identity_manager.get_x509_signature_upload_request().await
681        {
682            requests.push(signature_upload_request);
683        }
684
685        Ok(requests)
686    }
687
688    /// Generate an "out-of-band" key query request for the given set of users.
689    ///
690    /// This can be useful if we need the results from [`get_identity`] or
691    /// [`get_user_devices`] to be as up-to-date as possible.
692    ///
693    /// Note that this request won't be awaited by other calls waiting for a
694    /// user's or device's keys, since this is an out-of-band query.
695    ///
696    /// # Arguments
697    ///
698    /// - `users` - list of users whose keys should be queried
699    ///
700    /// # Returns
701    ///
702    /// A request to be sent out to the server. Once sent, the response should
703    /// be passed back to the state machine using [`mark_request_as_sent`].
704    ///
705    /// [`mark_request_as_sent`]: OlmMachine::mark_request_as_sent
706    /// [`get_identity`]: OlmMachine::get_identity
707    /// [`get_user_devices`]: OlmMachine::get_user_devices
708    pub fn query_keys_for_users<'a>(
709        &self,
710        users: impl IntoIterator<Item = &'a UserId>,
711    ) -> (OwnedTransactionId, KeysQueryRequest) {
712        self.inner.identity_manager.build_key_query_for_users(users)
713    }
714
715    /// Mark the request with the given request id as sent.
716    ///
717    /// # Arguments
718    ///
719    /// - `request_id` - The unique id of the request that was sent out. This is
720    ///   needed to couple the response with the now sent out request.
721    ///
722    /// - `response` - The response that was received from the server after the
723    ///   outgoing request was sent out.
724    pub async fn mark_request_as_sent<'a>(
725        &self,
726        request_id: &TransactionId,
727        response: impl Into<AnyIncomingResponse<'a>>,
728    ) -> OlmResult<()> {
729        match response.into() {
730            AnyIncomingResponse::KeysUpload(response) => {
731                Box::pin(self.receive_keys_upload_response(response)).await?;
732            }
733            AnyIncomingResponse::KeysQuery(response) => {
734                Box::pin(self.receive_keys_query_response(request_id, response)).await?;
735            }
736            AnyIncomingResponse::KeysClaim(response) => {
737                Box::pin(
738                    self.inner.session_manager.receive_keys_claim_response(request_id, response),
739                )
740                .await?;
741            }
742            AnyIncomingResponse::ToDevice(_) => {
743                Box::pin(self.mark_to_device_request_as_sent(request_id)).await?;
744            }
745            AnyIncomingResponse::SigningKeysUpload(_) => {
746                Box::pin(self.receive_cross_signing_upload_response()).await?;
747            }
748            AnyIncomingResponse::SignatureUpload(_) => {
749                self.inner.verification_machine.mark_request_as_sent(request_id);
750                self.inner.key_request_machine.mark_outgoing_request_as_sent(request_id).await?;
751                #[cfg(feature = "experimental-x509-identity-verification")]
752                self.inner.identity_manager.mark_x509_signature_request_as_sent(request_id).await;
753            }
754            AnyIncomingResponse::RoomMessage(_) => {
755                self.inner.verification_machine.mark_request_as_sent(request_id);
756            }
757            AnyIncomingResponse::KeysBackup(_) => {
758                Box::pin(self.inner.backup_machine.mark_request_as_sent(request_id)).await?;
759            }
760        }
761
762        Ok(())
763    }
764
765    /// Mark the cross signing identity as shared.
766    async fn receive_cross_signing_upload_response(&self) -> StoreResult<()> {
767        let identity = self.inner.user_identity.lock().await;
768        identity.mark_as_shared();
769
770        let changes = Changes { private_identity: Some(identity.clone()), ..Default::default() };
771
772        self.store().save_changes(changes).await
773    }
774
775    /// Create a new cross signing identity and get the upload request to push
776    /// the new public keys to the server.
777    ///
778    /// **Warning**: if called with `reset`, this will delete any existing cross
779    /// signing keys that might exist on the server and thus will reset the
780    /// trust between all the devices.
781    ///
782    /// # Returns
783    ///
784    /// A triple of requests which should be sent out to the server, in the
785    /// order they appear in the return tuple.
786    ///
787    /// The first request's response, if present, should be passed back to the
788    /// state machine using [`mark_request_as_sent`].
789    ///
790    /// These requests may require user interactive auth.
791    ///
792    /// [`mark_request_as_sent`]: #method.mark_request_as_sent
793    pub async fn bootstrap_cross_signing(
794        &self,
795        reset: bool,
796    ) -> Result<CrossSigningBootstrapRequests, BootstrapCrossSigningError> {
797        // Don't hold the lock, otherwise we might deadlock in
798        // `bootstrap_cross_signing()` on `account` if a sync task is already
799        // running (which locks `account`), or we will deadlock in
800        // `upload_device_keys()` which locks private identity again.
801        let identity = self.inner.user_identity.lock().await.clone();
802
803        let mut requests = if reset || identity.is_empty().await {
804            let handle = self.reset_cross_signing().await?;
805            let upload_signing_keys_req = handle.upload_signing_keys_req().clone();
806            let upload_signatures_req = handle.commit().await?;
807
808            CrossSigningBootstrapRequests {
809                upload_signing_keys_req,
810                upload_keys_req: None,
811                upload_signatures_req,
812            }
813        } else {
814            info!("Trying to upload the existing cross signing identity");
815            let upload_signing_keys_req = identity.as_upload_request().await;
816
817            // TODO remove this expect.
818            let upload_signatures_req = identity
819                .sign_account(self.inner.store.static_account())
820                .await
821                .expect("Can't sign device keys");
822
823            CrossSigningBootstrapRequests {
824                upload_signing_keys_req,
825                upload_keys_req: None,
826                upload_signatures_req,
827            }
828        };
829
830        // If there are any _device_ keys to upload (i.e. the account isn't
831        // shared), upload them before we upload the signatures, since the
832        // signatures may reference keys to be uploaded.
833        requests.upload_keys_req =
834            self.upload_device_keys().await?.map(|(_, request)| OutgoingRequest::from(request));
835
836        Ok(requests)
837    }
838
839    /// Generate a new cross signing identity and return a handle that can be
840    /// used to commit it to the store once the new keys have been uploaded
841    /// to the server.
842    ///
843    /// See [`UncommittedCrossSigningReset`] for more information.
844    pub async fn reset_cross_signing(
845        &self,
846    ) -> Result<UncommittedCrossSigningReset, BootstrapCrossSigningError> {
847        info!("Creating new cross signing identity");
848
849        let (identity, upload_signing_keys_req, upload_signatures_req) = {
850            let cache = self.inner.store.cache().await?;
851            let account = cache.account().await?;
852            account
853                .bootstrap_cross_signing(
854                    #[cfg(feature = "experimental-x509-identity-verification")]
855                    self.inner.store.x509_signer().map(|s| s.raw()),
856                )
857                .await?
858        };
859
860        let public = identity
861            .to_public_identity()
862            .await
863            .expect("Couldn't create a public version of the identity from a new private identity");
864
865        Ok(UncommittedCrossSigningReset {
866            identity,
867            public,
868            upload_signing_keys_req,
869            upload_signatures_req,
870            olm_machine: self.clone(),
871        })
872    }
873
874    /// Upload the device keys for this [`OlmMachine`].
875    ///
876    /// **Warning**: Do not use this method if
877    /// [`OlmMachine::outgoing_requests()`] is already in use. This method is
878    /// intended for explicitly uploading the device keys before starting a sync
879    /// and before using [`OlmMachine::outgoing_requests()`].
880    ///
881    /// # Returns
882    ///
883    /// A tuple containing a transaction ID and a request if the device keys
884    /// need to be uploaded. Otherwise, returns `None`.
885    pub async fn upload_device_keys(
886        &self,
887    ) -> StoreResult<Option<(OwnedTransactionId, UploadKeysRequest)>> {
888        let cache = self.store().cache().await?;
889        let account = cache.account().await?;
890
891        Ok(self.keys_for_upload(&account).await.map(|request| (TransactionId::new(), request)))
892    }
893
894    /// Receive a successful `/keys/upload` response.
895    ///
896    /// # Arguments
897    ///
898    /// - `response` - The response of the `/keys/upload` request that the
899    ///   client performed.
900    async fn receive_keys_upload_response(&self, response: &UploadKeysResponse) -> OlmResult<()> {
901        self.inner
902            .store
903            .with_transaction(async |tr| {
904                let account = tr.account().await?;
905                account.receive_keys_upload_response(response)?;
906                Ok(())
907            })
908            .await
909    }
910
911    /// Get a key claiming request for the user/device pairs that we are missing
912    /// Olm sessions for.
913    ///
914    /// Returns None if no key claiming request needs to be sent out.
915    ///
916    /// Sessions need to be established between devices so group sessions for a
917    /// room can be shared with them.
918    ///
919    /// This should be called every time a group session needs to be shared as
920    /// well as between sync calls. After a sync some devices may request room
921    /// keys without us having a valid Olm session with them, making it
922    /// impossible to server the room key request, thus it's necessary to check
923    /// for missing sessions between sync as well.
924    ///
925    /// **Note**: Care should be taken that only one such request at a time is
926    /// in flight, e.g. using a lock.
927    ///
928    /// The response of a successful key claiming requests needs to be passed to
929    /// the `OlmMachine` with the [`mark_request_as_sent`].
930    ///
931    /// # Arguments
932    ///
933    /// `users` - The list of users that we should check if we lack a session
934    /// with one of their devices. This can be an empty iterator when calling
935    /// this method between sync requests.
936    ///
937    /// [`mark_request_as_sent`]: #method.mark_request_as_sent
938    #[instrument(skip_all)]
939    pub async fn get_missing_sessions(
940        &self,
941        users: impl Iterator<Item = &UserId>,
942    ) -> StoreResult<Option<(OwnedTransactionId, KeysClaimRequest)>> {
943        self.inner.session_manager.get_missing_sessions(users).await
944    }
945
946    /// Receive a successful `/keys/query` response.
947    ///
948    /// Returns a list of newly discovered devices and devices that changed.
949    ///
950    /// # Arguments
951    ///
952    /// - `response` - The response of the `/keys/query` request that the client
953    ///   performed.
954    async fn receive_keys_query_response(
955        &self,
956        request_id: &TransactionId,
957        response: &KeysQueryResponse,
958    ) -> OlmResult<(DeviceChanges, IdentityChanges)> {
959        self.inner.identity_manager.receive_keys_query_response(request_id, response).await
960    }
961
962    /// Get a request to upload E2EE keys to the server.
963    ///
964    /// Returns None if no keys need to be uploaded.
965    ///
966    /// The response of a successful key upload requests needs to be passed to
967    /// the [`OlmMachine`] with the [`receive_keys_upload_response`].
968    ///
969    /// [`receive_keys_upload_response`]: #method.receive_keys_upload_response
970    async fn keys_for_upload(&self, account: &Account) -> Option<UploadKeysRequest> {
971        let (mut device_keys, one_time_keys, fallback_keys) = account.keys_for_upload();
972
973        // When uploading the device keys, if all private cross-signing keys are
974        // available locally, sign the device using these cross-signing keys.
975        // This will mark the device as verified if the user identity (i.e., the
976        // cross-signing keys) is also marked as verified.
977        //
978        // This approach eliminates the need to upload signatures in a separate
979        // request, ensuring that other users/devices will never encounter this
980        // device without a signature from their user identity. Consequently,
981        // they will never see the device as unverified.
982        if let Some(device_keys) = &mut device_keys {
983            let private_identity = self.store().private_identity();
984            let guard = private_identity.lock().await;
985
986            if guard.status().await.is_complete() {
987                guard.sign_device_keys(device_keys).await.expect(
988                    "We should be able to sign our device keys since we confirmed that we \
989                     have a complete set of private cross-signing keys",
990                );
991            }
992        }
993
994        if device_keys.is_none() && one_time_keys.is_empty() && fallback_keys.is_empty() {
995            None
996        } else {
997            let device_keys = device_keys.map(|d| d.to_raw());
998
999            Some(assign!(UploadKeysRequest::new(), {
1000                device_keys, one_time_keys, fallback_keys
1001            }))
1002        }
1003    }
1004
1005    /// Decrypt and handle a to-device event.
1006    ///
1007    /// If decryption (or checking the sender device) fails, returns an
1008    /// `Err(DecryptToDeviceError::OlmError)`.
1009    ///
1010    /// If we are in strict "exclude insecure devices" mode and the sender
1011    /// device is not verified, and the decrypted event type is not on the allow
1012    /// list, returns `Err(DecryptToDeviceError::UnverifiedSender)`
1013    ///
1014    /// (The allow list of types that are processed even if the sender is
1015    /// unverified is: `m.room_key`, `m.room_key.withheld`,
1016    /// `m.room_key_request`, `m.secret.request` and `m.key.verification.*`.)
1017    ///
1018    /// If the sender device is dehydrated, does no handling and immediately
1019    /// returns `Err(DecryptToDeviceError::FromDehydratedDevice)`.
1020    ///
1021    /// Otherwise, handles the decrypted event and returns it (decrypted) as
1022    /// `Ok(OlmDecryptionInfo)`.
1023    ///
1024    /// # Arguments
1025    ///
1026    /// - `event` - The to-device event that should be decrypted.
1027    async fn decrypt_to_device_event(
1028        &self,
1029        transaction: &mut StoreTransaction,
1030        event: &EncryptedToDeviceEvent,
1031        changes: &mut Changes,
1032        decryption_settings: &DecryptionSettings,
1033    ) -> Result<OlmDecryptionInfo, DecryptToDeviceError> {
1034        // Decrypt the event
1035        let mut decrypted = transaction
1036            .account()
1037            .await?
1038            .decrypt_to_device_event(&self.inner.store, event, decryption_settings)
1039            .await?;
1040
1041        // Return early if the sending device is a dehydrated device
1042        self.check_to_device_event_is_not_from_dehydrated_device(&decrypted, &event.sender).await?;
1043
1044        // Device is not dehydrated: handle it as normal e.g. create a Megolm
1045        // session
1046        self.handle_decrypted_to_device_event(transaction.cache(), &mut decrypted, changes).await?;
1047
1048        Ok(decrypted)
1049    }
1050
1051    #[instrument(
1052        skip_all,
1053        // This function is only ever called by add_room_key via
1054        // handle_decrypted_to_device_event, so sender, sender_key, and
1055        // algorithm are already recorded.
1056        fields(room_id = ? content.room_id, session_id, message_index, shared_history = content.shared_history)
1057    )]
1058    async fn handle_key(
1059        &self,
1060        sender_key: Curve25519PublicKey,
1061        event: &DecryptedRoomKeyEvent,
1062        content: &MegolmV1AesSha2Content,
1063    ) -> OlmResult<Option<InboundGroupSession>> {
1064        let session =
1065            InboundGroupSession::from_room_key_content(sender_key, event.keys.ed25519, content);
1066
1067        match session {
1068            Ok(mut session) => {
1069                Span::current().record("session_id", session.session_id());
1070                Span::current().record("message_index", session.first_known_index());
1071
1072                let sender_data =
1073                    SenderDataFinder::find_using_event(self.store(), sender_key, event, &session)
1074                        .await?;
1075                session.sender_data = sender_data;
1076
1077                Ok(self.store().merge_received_group_session(session).await?)
1078            }
1079            Err(e) => {
1080                Span::current().record("session_id", &content.session_id);
1081                warn!("Received a room key event which contained an invalid session key: {e}");
1082
1083                Ok(None)
1084            }
1085        }
1086    }
1087
1088    /// Create a group session from a room key and add it to our crypto store.
1089    #[instrument(skip_all, fields(algorithm = ?event.content.algorithm()))]
1090    async fn add_room_key(
1091        &self,
1092        sender_key: Curve25519PublicKey,
1093        event: &DecryptedRoomKeyEvent,
1094    ) -> OlmResult<Option<InboundGroupSession>> {
1095        match &event.content {
1096            RoomKeyContent::MegolmV1AesSha2(content) => {
1097                self.handle_key(sender_key, event, content).await
1098            }
1099            #[cfg(feature = "experimental-algorithms")]
1100            RoomKeyContent::MegolmV2AesSha2(content) => {
1101                self.handle_key(sender_key, event, content).await
1102            }
1103            RoomKeyContent::Unknown(_) => {
1104                warn!("Received a room key with an unsupported algorithm");
1105                Ok(None)
1106            }
1107        }
1108    }
1109
1110    /// Handle a received, decrypted, `m.room_key_bundle` to-device event.
1111    #[instrument()]
1112    async fn receive_room_key_bundle_data(
1113        &self,
1114        sender_key: Curve25519PublicKey,
1115        event: &DecryptedRoomKeyBundleEvent,
1116        changes: &mut Changes,
1117    ) -> OlmResult<()> {
1118        let Some(sender_device_keys) = &event.sender_device_keys else {
1119            warn!("Received a room key bundle with no sender device keys: ignoring");
1120            return Ok(());
1121        };
1122
1123        // NOTE: We already checked that `sender_device_keys` matches the actual
1124        // sender of the message when we decrypted the message, which included
1125        // doing `DeviceData::try_from` on it, so it can't fail.
1126
1127        let sender_device_data =
1128            DeviceData::try_from(sender_device_keys).expect("failed to verify sender device keys");
1129        let sender_device = self.store().wrap_device_data(sender_device_data).await?;
1130
1131        changes.received_room_key_bundles.push(StoredRoomKeyBundleData {
1132            sender_user: event.sender.clone(),
1133            sender_data: SenderData::from_device(&sender_device),
1134            sender_key,
1135            bundle_data: event.content.clone(),
1136        });
1137        Ok(())
1138    }
1139
1140    fn add_withheld_info(&self, changes: &mut Changes, event: &RoomKeyWithheldEvent) {
1141        debug!(?event.content, "Processing `m.room_key.withheld` event");
1142
1143        if let RoomKeyWithheldContent::MegolmV1AesSha2(
1144            MegolmV1AesSha2WithheldContent::BlackListed(c)
1145            | MegolmV1AesSha2WithheldContent::Unverified(c)
1146            | MegolmV1AesSha2WithheldContent::Unauthorised(c)
1147            | MegolmV1AesSha2WithheldContent::Unavailable(c),
1148        ) = &event.content
1149        {
1150            changes
1151                .withheld_session_info
1152                .entry(c.room_id.to_owned())
1153                .or_default()
1154                .insert(c.session_id.to_owned(), event.to_owned().into());
1155        }
1156    }
1157
1158    #[cfg(test)]
1159    pub(crate) async fn create_outbound_group_session_with_defaults_test_helper(
1160        &self,
1161        room_id: &RoomId,
1162    ) -> OlmResult<()> {
1163        let (_, session) = self
1164            .inner
1165            .group_session_manager
1166            .create_outbound_group_session(
1167                room_id,
1168                EncryptionSettings::default(),
1169                SenderData::unknown(),
1170            )
1171            .await?;
1172
1173        self.store().save_inbound_group_sessions(&[session]).await?;
1174
1175        Ok(())
1176    }
1177
1178    #[cfg(test)]
1179    #[allow(dead_code)]
1180    pub(crate) async fn create_inbound_session_test_helper(
1181        &self,
1182        room_id: &RoomId,
1183    ) -> OlmResult<InboundGroupSession> {
1184        let (_, session) = self
1185            .inner
1186            .group_session_manager
1187            .create_outbound_group_session(
1188                room_id,
1189                EncryptionSettings::default(),
1190                SenderData::unknown(),
1191            )
1192            .await?;
1193
1194        Ok(session)
1195    }
1196
1197    /// Encrypt a room message for the given room.
1198    ///
1199    /// Beware that a room key needs to be shared before this method can be
1200    /// called using the [`OlmMachine::share_room_key`] method.
1201    ///
1202    /// # Arguments
1203    ///
1204    /// - `room_id` - The id of the room for which the message should be
1205    ///   encrypted.
1206    ///
1207    /// - `content` - The plaintext content of the message that should be
1208    ///   encrypted.
1209    ///
1210    /// # Panics
1211    ///
1212    /// Panics if a room key for the given room wasn't shared beforehand.
1213    pub async fn encrypt_room_event(
1214        &self,
1215        room_id: &RoomId,
1216        content: impl MessageLikeEventContent,
1217    ) -> MegolmResult<RawEncryptionResult> {
1218        let event_type = content.event_type().to_string();
1219        let content = Raw::new(&content)?.cast_unchecked();
1220        self.encrypt_room_event_raw(room_id, &event_type, &content).await
1221    }
1222
1223    /// Encrypt a raw JSON content for the given room.
1224    ///
1225    /// This method is equivalent to the [`OlmMachine::encrypt_room_event()`]
1226    /// method but operates on an arbitrary JSON value instead of strongly-typed
1227    /// event content struct.
1228    ///
1229    /// # Arguments
1230    ///
1231    /// - `room_id` - The id of the room for which the message should be
1232    ///   encrypted.
1233    ///
1234    /// - `content` - The plaintext content of the message that should be
1235    ///   encrypted as a raw JSON value.
1236    ///
1237    /// - `event_type` - The plaintext type of the event.
1238    ///
1239    /// # Panics
1240    ///
1241    /// Panics if a group session for the given room wasn't shared beforehand.
1242    pub async fn encrypt_room_event_raw(
1243        &self,
1244        room_id: &RoomId,
1245        event_type: &str,
1246        content: &Raw<AnyMessageLikeEventContent>,
1247    ) -> MegolmResult<RawEncryptionResult> {
1248        self.inner.group_session_manager.encrypt(room_id, event_type, content).await.map(|result| {
1249            RawEncryptionResult {
1250                content: result.content,
1251                encryption_info: self
1252                    .own_encryption_info(result.algorithm, result.session_id.to_string()),
1253            }
1254        })
1255    }
1256
1257    fn own_encryption_info(
1258        &self,
1259        algorithm: EventEncryptionAlgorithm,
1260        session_id: String,
1261    ) -> EncryptionInfo {
1262        let identity_keys = self.identity_keys();
1263
1264        let algorithm_info = match algorithm {
1265            EventEncryptionAlgorithm::MegolmV1AesSha2 => AlgorithmInfo::MegolmV1AesSha2 {
1266                curve25519_key: identity_keys.curve25519.to_base64(),
1267                sender_claimed_keys: BTreeMap::from([(
1268                    DeviceKeyAlgorithm::Ed25519,
1269                    identity_keys.ed25519.to_base64(),
1270                )]),
1271                session_id: Some(session_id),
1272            },
1273            EventEncryptionAlgorithm::OlmV1Curve25519AesSha2 => {
1274                AlgorithmInfo::OlmV1Curve25519AesSha2 {
1275                    curve25519_public_key_base64: identity_keys.curve25519.to_base64(),
1276                }
1277            }
1278            _ => unreachable!(
1279                "Only MegolmV1AesSha2 and OlmV1Curve25519AesSha2 are supported on this level"
1280            ),
1281        };
1282
1283        EncryptionInfo {
1284            sender: self.inner.user_id.clone(),
1285            sender_device: Some(self.inner.device_id.clone()),
1286            forwarder: None,
1287            algorithm_info,
1288            verification_state: VerificationState::Verified,
1289        }
1290    }
1291
1292    /// Encrypt a state event for the given room.
1293    ///
1294    /// # Arguments
1295    ///
1296    /// - `room_id` - The id of the room for which the event should be
1297    ///   encrypted.
1298    ///
1299    /// - `content` - The plaintext content of the event that should be
1300    ///   encrypted.
1301    ///
1302    /// - `state_key` - The associated state key of the event.
1303    #[cfg(feature = "experimental-encrypted-state-events")]
1304    pub async fn encrypt_state_event<C, K>(
1305        &self,
1306        room_id: &RoomId,
1307        content: C,
1308        state_key: K,
1309    ) -> MegolmResult<Raw<RoomEncryptedEventContent>>
1310    where
1311        C: StateEventContent,
1312        C::StateKey: Borrow<K>,
1313        K: AsRef<str>,
1314    {
1315        let event_type = content.event_type().to_string();
1316        let content = Raw::new(&content)?.cast_unchecked();
1317        self.encrypt_state_event_raw(room_id, &event_type, state_key.as_ref(), &content).await
1318    }
1319
1320    /// Encrypt a state event for the given state event using its raw JSON
1321    /// content and state key.
1322    ///
1323    /// This method is equivalent to [`OlmMachine::encrypt_state_event`] method
1324    /// but operates on an arbitrary JSON value instead of strongly-typed event
1325    /// content struct.
1326    ///
1327    /// # Arguments
1328    ///
1329    /// - `room_id` - The id of the room for which the message should be
1330    ///   encrypted.
1331    ///
1332    /// - `event_type` - The type of the event.
1333    /// - `state_key` - The associated state key of the event.
1334    /// - `content` - The plaintext content of the event that should be
1335    ///   encrypted as a raw JSON value.
1336    #[cfg(feature = "experimental-encrypted-state-events")]
1337    pub async fn encrypt_state_event_raw(
1338        &self,
1339        room_id: &RoomId,
1340        event_type: &str,
1341        state_key: &str,
1342        content: &Raw<AnyStateEventContent>,
1343    ) -> MegolmResult<Raw<RoomEncryptedEventContent>> {
1344        self.inner
1345            .group_session_manager
1346            .encrypt_state(room_id, event_type, state_key, content)
1347            .await
1348    }
1349
1350    /// Forces the currently active room key, which is used to encrypt messages,
1351    /// to be rotated.
1352    ///
1353    /// A new room key will be crated and shared with all the room members the
1354    /// next time a message will be sent. You don't have to call this method,
1355    /// room keys will be rotated automatically when necessary. This method is
1356    /// still useful for debugging purposes.
1357    ///
1358    /// Returns true if a session was invalidated, false if there was no session
1359    /// to invalidate.
1360    pub async fn discard_room_key(&self, room_id: &RoomId) -> StoreResult<bool> {
1361        self.inner.group_session_manager.invalidate_group_session(room_id).await
1362    }
1363
1364    /// Get to-device requests to share a room key with users in a room.
1365    ///
1366    /// # Arguments
1367    ///
1368    /// `room_id` - The room id of the room where the room key will be used.
1369    ///
1370    /// `users` - The list of users that should receive the room key.
1371    ///
1372    /// `settings` - Encryption settings that affect when are room keys rotated
1373    /// and who are they shared with.
1374    ///
1375    /// # Returns
1376    ///
1377    /// List of the to-device requests that need to be sent out to the server
1378    /// and the responses need to be passed back to the state machine with
1379    /// [`mark_request_as_sent`], using the to-device `txn_id` as `request_id`.
1380    ///
1381    /// [`mark_request_as_sent`]: #method.mark_request_as_sent
1382    pub async fn share_room_key(
1383        &self,
1384        room_id: &RoomId,
1385        users: impl Iterator<Item = &UserId>,
1386        encryption_settings: impl Into<EncryptionSettings>,
1387    ) -> OlmResult<Vec<Arc<ToDeviceRequest>>> {
1388        self.inner.group_session_manager.share_room_key(room_id, users, encryption_settings).await
1389    }
1390
1391    /// Encrypts the given content using Olm for each of the given devices.
1392    ///
1393    /// The 1-to-1 session must be established prior to this call by using the
1394    /// [`OlmMachine::get_missing_sessions`] method or the encryption will fail.
1395    ///
1396    /// The caller is responsible for sending the encrypted event to the target
1397    /// device, and should do it ASAP to avoid out-of-order messages.
1398    ///
1399    /// # Returns
1400    ///
1401    /// A list of `ToDeviceRequest` to send out the event, and the list of
1402    /// devices where encryption did not succeed (device excluded or no olm)
1403    #[cfg(feature = "experimental-send-custom-to-device")]
1404    pub async fn encrypt_content_for_devices(
1405        &self,
1406        devices: Vec<DeviceData>,
1407        event_type: &str,
1408        content: &Value,
1409        share_strategy: CollectStrategy,
1410    ) -> OlmResult<(Vec<ToDeviceRequest>, Vec<(DeviceData, WithheldCode)>)> {
1411        let mut changes = Changes::default();
1412
1413        let (allowed_devices, mut blocked_devices) =
1414            split_devices_for_share_strategy(&self.inner.store, devices, share_strategy).await?;
1415
1416        let result = self
1417            .inner
1418            .group_session_manager
1419            .encrypt_content_for_devices(allowed_devices, event_type, content.clone(), &mut changes)
1420            .await;
1421
1422        // Persist any changes we might have collected.
1423        if !changes.is_empty() {
1424            let session_count = changes.sessions.len();
1425
1426            self.inner.store.save_changes(changes).await?;
1427
1428            trace!(
1429                session_count = session_count,
1430                "Stored the changed sessions after encrypting a custom to-device event"
1431            );
1432        }
1433
1434        result.map(|(to_device_requests, mut withheld)| {
1435            withheld.append(&mut blocked_devices);
1436            (to_device_requests, withheld)
1437        })
1438    }
1439    /// Collect the devices belonging to the given user, and send the details of
1440    /// a room key bundle to those devices.
1441    ///
1442    /// Returns a list of to-device requests which must be sent.
1443    pub async fn share_room_key_bundle_data(
1444        &self,
1445        user_id: &UserId,
1446        collect_strategy: &CollectStrategy,
1447        bundle_data: RoomKeyBundleContent,
1448    ) -> OlmResult<Vec<ToDeviceRequest>> {
1449        self.inner
1450            .group_session_manager
1451            .share_room_key_bundle_data(user_id, collect_strategy, bundle_data)
1452            .await
1453    }
1454
1455    /// Receive an unencrypted verification event.
1456    ///
1457    /// This method can be used to pass verification events that are happening
1458    /// in unencrypted rooms to the `OlmMachine`.
1459    ///
1460    /// **Note**: This does not need to be called for encrypted events since
1461    /// those will get passed to the `OlmMachine` during decryption.
1462    #[deprecated(note = "Use OlmMachine::receive_verification_event instead", since = "0.7.0")]
1463    pub async fn receive_unencrypted_verification_event(
1464        &self,
1465        event: &AnyMessageLikeEvent,
1466    ) -> StoreResult<()> {
1467        self.inner.verification_machine.receive_any_event(event).await
1468    }
1469
1470    /// Receive a verification event.
1471    ///
1472    /// The event should be in the decrypted form.
1473    ///
1474    /// **Note**: If the supplied event is an `m.room.message` event with
1475    /// `msgtype: m.key.verification.request`, then the device information for
1476    /// the sending user must be up-to-date before calling this method
1477    /// (otherwise, the request will be ignored). It is hard to guarantee this
1478    /// is the case, but you can maximize your chances by explicitly making a
1479    /// request for this user's device info by calling
1480    /// [`OlmMachine::query_keys_for_users`], sending the request, and
1481    /// processing the response with [`OlmMachine::mark_request_as_sent`].
1482    pub async fn receive_verification_event(&self, event: &AnyMessageLikeEvent) -> StoreResult<()> {
1483        self.inner.verification_machine.receive_any_event(event).await
1484    }
1485
1486    /// Receive and properly handle a decrypted to-device event.
1487    ///
1488    /// # Arguments
1489    ///
1490    /// * `decrypted` - The decrypted event and some associated metadata.
1491    #[instrument(
1492        skip_all,
1493        fields(
1494            sender_key = ?decrypted.result.sender_key,
1495            event_type = decrypted.result.event.event_type(),
1496        ),
1497    )]
1498    async fn handle_decrypted_to_device_event(
1499        &self,
1500        cache: &StoreCache,
1501        decrypted: &mut OlmDecryptionInfo,
1502        changes: &mut Changes,
1503    ) -> OlmResult<()> {
1504        debug!(
1505            sender_device_keys =
1506                ?decrypted.result.event.sender_device_keys().map(|k| (k.curve25519_key(), k.ed25519_key())).unwrap_or((None, None)),
1507            "Received a decrypted to-device event",
1508        );
1509
1510        match &*decrypted.result.event {
1511            AnyDecryptedOlmEvent::RoomKey(e) => {
1512                let session = self.add_room_key(decrypted.result.sender_key, e).await?;
1513                decrypted.inbound_group_session = session;
1514            }
1515            AnyDecryptedOlmEvent::ForwardedRoomKey(e) => {
1516                let session = self
1517                    .inner
1518                    .key_request_machine
1519                    .receive_forwarded_room_key(decrypted.result.sender_key, e)
1520                    .await?;
1521                decrypted.inbound_group_session = session;
1522            }
1523            AnyDecryptedOlmEvent::SecretSend(e) => {
1524                let name = self
1525                    .inner
1526                    .key_request_machine
1527                    .receive_secret_event(cache, decrypted.result.sender_key, e, changes)
1528                    .await?;
1529
1530                // Set the secret name so other consumers of the event know what
1531                // this event is about.
1532                if let Ok(ToDeviceEvents::SecretSend(mut e)) =
1533                    decrypted.result.raw_event.deserialize_as()
1534                {
1535                    e.content.secret_name = name;
1536                    decrypted.result.raw_event = Raw::from_json(to_raw_value(&e)?);
1537                }
1538
1539                if enabled!(tracing::Level::DEBUG) {
1540                    let cross_signing_status = self.cross_signing_status().await;
1541                    let backup_enabled = self.backup_machine().enabled().await;
1542                    debug!(
1543                        ?cross_signing_status,
1544                        backup_enabled, "Status after receiving secret event"
1545                    );
1546                }
1547            }
1548            AnyDecryptedOlmEvent::Dummy(_) => {
1549                debug!("Received an `m.dummy` event");
1550            }
1551            AnyDecryptedOlmEvent::RoomKeyBundle(e) => {
1552                debug!("Received a room key bundle event {:?}", e);
1553                self.receive_room_key_bundle_data(decrypted.result.sender_key, e, changes).await?;
1554            }
1555            #[cfg(feature = "experimental-push-secrets")]
1556            AnyDecryptedOlmEvent::SecretPush(e) => {
1557                self.inner
1558                    .key_request_machine
1559                    .receive_secret_push_event(&decrypted.result.sender_key, e, changes)
1560                    .await?;
1561            }
1562            AnyDecryptedOlmEvent::Custom(_) => {
1563                warn!("Received an unexpected encrypted to-device event");
1564            }
1565        }
1566
1567        Ok(())
1568    }
1569
1570    async fn handle_verification_event(&self, event: &ToDeviceEvents) {
1571        if let Err(e) = self.inner.verification_machine.receive_any_event(event).await {
1572            error!("Error handling a verification event: {e:?}");
1573        }
1574    }
1575
1576    /// Mark an outgoing to-device requests as sent.
1577    async fn mark_to_device_request_as_sent(&self, request_id: &TransactionId) -> StoreResult<()> {
1578        self.inner.verification_machine.mark_request_as_sent(request_id);
1579        self.inner.key_request_machine.mark_outgoing_request_as_sent(request_id).await?;
1580        self.inner.group_session_manager.mark_request_as_sent(request_id).await?;
1581        self.inner.session_manager.mark_outgoing_request_as_sent(request_id);
1582        Ok(())
1583    }
1584
1585    /// Get a verification object for the given user id with the given flow id.
1586    pub fn get_verification(&self, user_id: &UserId, flow_id: &str) -> Option<Verification> {
1587        self.inner.verification_machine.get_verification(user_id, flow_id)
1588    }
1589
1590    /// Get a verification request object with the given flow id.
1591    pub fn get_verification_request(
1592        &self,
1593        user_id: &UserId,
1594        flow_id: impl AsRef<str>,
1595    ) -> Option<VerificationRequest> {
1596        self.inner.verification_machine.get_request(user_id, flow_id)
1597    }
1598
1599    /// Get all the verification requests of a given user.
1600    pub fn get_verification_requests(&self, user_id: &UserId) -> Vec<VerificationRequest> {
1601        self.inner.verification_machine.get_requests(user_id)
1602    }
1603
1604    /// Given a to-device event that has either been decrypted or arrived in
1605    /// plaintext, handle it.
1606    ///
1607    /// Here, we only process events that are allowed to arrive in plaintext.
1608    async fn handle_to_device_event(&self, changes: &mut Changes, event: &ToDeviceEvents) {
1609        use crate::types::events::ToDeviceEvents::*;
1610
1611        match event {
1612            // These are handled here because we accept them either plaintext or
1613            // encrypted.
1614            //
1615            // Note: this list should match the allowed types in
1616            // check_to_device_is_from_verified_device_or_allowed_type
1617            RoomKeyRequest(e) => self.inner.key_request_machine.receive_incoming_key_request(e),
1618            SecretRequest(e) => self.inner.key_request_machine.receive_incoming_secret_request(e),
1619            RoomKeyWithheld(e) => self.add_withheld_info(changes, e),
1620            KeyVerificationAccept(..)
1621            | KeyVerificationCancel(..)
1622            | KeyVerificationKey(..)
1623            | KeyVerificationMac(..)
1624            | KeyVerificationRequest(..)
1625            | KeyVerificationReady(..)
1626            | KeyVerificationDone(..)
1627            | KeyVerificationStart(..) => {
1628                self.handle_verification_event(event).await;
1629            }
1630
1631            // We don't process custom or dummy events at all
1632            Custom(_) | Dummy(_) => {}
1633
1634            // Encrypted events are handled elsewhere
1635            RoomEncrypted(_) => {}
1636
1637            // These are handled in `handle_decrypted_to_device_event` because
1638            // we only accept them if they arrive encrypted.
1639            SecretSend(_) | RoomKey(_) | ForwardedRoomKey(_) => {}
1640        }
1641    }
1642
1643    fn record_message_id(event: &Raw<AnyToDeviceEvent>) {
1644        use serde::Deserialize;
1645
1646        #[derive(Deserialize)]
1647        struct ContentStub<'a> {
1648            #[serde(borrow, rename = "org.matrix.msgid")]
1649            message_id: Option<&'a str>,
1650        }
1651        #[derive(Deserialize)]
1652        struct ToDeviceStub<'a> {
1653            sender: &'a str,
1654            #[serde(rename = "type")]
1655            event_type: &'a str,
1656            #[serde(borrow)]
1657            content: ContentStub<'a>,
1658        }
1659
1660        if let Ok(event) = event.deserialize_as_unchecked::<ToDeviceStub<'_>>() {
1661            Span::current().record("sender", event.sender);
1662            Span::current().record("event_type", event.event_type);
1663            Span::current().record("message_id", event.content.message_id);
1664        }
1665    }
1666
1667    /// Decrypt the supplied to-device event (if needed, and if we can) and
1668    /// handle it.
1669    ///
1670    /// Return the same event, decrypted if possible and needed.
1671    ///
1672    /// If we can identify that this to-device event came from a dehydrated
1673    /// device, this method does not process it, and returns `None`.
1674    #[instrument(skip_all, fields(sender, event_type, message_id))]
1675    async fn receive_to_device_event(
1676        &self,
1677        transaction: &mut StoreTransaction,
1678        changes: &mut Changes,
1679        raw_event: Raw<AnyToDeviceEvent>,
1680        decryption_settings: &DecryptionSettings,
1681    ) -> Option<ProcessedToDeviceEvent> {
1682        Self::record_message_id(&raw_event);
1683
1684        let event: ToDeviceEvents = match raw_event.deserialize_as() {
1685            Ok(e) => e,
1686            Err(e) => {
1687                // Skip invalid events.
1688                warn!("Received an invalid to-device event: {e}");
1689                return Some(ProcessedToDeviceEvent::Invalid(raw_event));
1690            }
1691        };
1692
1693        debug!("Received a to-device event");
1694
1695        match event {
1696            ToDeviceEvents::RoomEncrypted(e) => {
1697                self.receive_encrypted_to_device_event(
1698                    transaction,
1699                    changes,
1700                    raw_event,
1701                    e,
1702                    decryption_settings,
1703                )
1704                .await
1705            }
1706            e => {
1707                self.handle_to_device_event(changes, &e).await;
1708                Some(ProcessedToDeviceEvent::PlainText(raw_event))
1709            }
1710        }
1711    }
1712
1713    /// Decrypt the supplied encrypted to-device event (if we can) and handle
1714    /// it.
1715    ///
1716    /// Return the same event, decrypted if possible.
1717    ///
1718    /// If we are in strict "exclude insecure devices" mode and the sender
1719    /// device is not verified, and the decrypted event type is not on the allow
1720    /// list, or if this event comes from a dehydrated device, this method does
1721    /// not process it, and returns `None`.
1722    ///
1723    /// (The allow list of types that are processed even if the sender is
1724    /// unverified is: `m.room_key`, `m.room_key.withheld`,
1725    /// `m.room_key_request`, `m.secret.request` and `m.key.verification.*`.)
1726    async fn receive_encrypted_to_device_event(
1727        &self,
1728        transaction: &mut StoreTransaction,
1729        changes: &mut Changes,
1730        mut raw_event: Raw<AnyToDeviceEvent>,
1731        e: ToDeviceEvent<ToDeviceEncryptedEventContent>,
1732        decryption_settings: &DecryptionSettings,
1733    ) -> Option<ProcessedToDeviceEvent> {
1734        let decrypted = match self
1735            .decrypt_to_device_event(transaction, &e, changes, decryption_settings)
1736            .await
1737        {
1738            Ok(decrypted) => decrypted,
1739            Err(DecryptToDeviceError::OlmError(err)) => {
1740                let reason = if let OlmError::UnverifiedSenderDevice = &err {
1741                    ToDeviceUnableToDecryptReason::UnverifiedSenderDevice
1742                } else {
1743                    ToDeviceUnableToDecryptReason::DecryptionFailure
1744                };
1745
1746                if let OlmError::SessionWedged(sender, curve_key) = err
1747                    && let Err(e) =
1748                        self.inner.session_manager.mark_device_as_wedged(&sender, curve_key).await
1749                {
1750                    error!(
1751                        error = ?e,
1752                        "Couldn't mark device to be unwedged",
1753                    );
1754                }
1755
1756                return Some(ProcessedToDeviceEvent::UnableToDecrypt {
1757                    encrypted_event: raw_event,
1758                    utd_info: ToDeviceUnableToDecryptInfo { reason },
1759                });
1760            }
1761            Err(DecryptToDeviceError::FromDehydratedDevice) => return None,
1762        };
1763
1764        // New sessions modify the account so we need to save that one as well.
1765        match decrypted.session {
1766            SessionType::New(s) | SessionType::Existing(s) => {
1767                changes.sessions.push(s);
1768            }
1769        }
1770
1771        changes.message_hashes.push(decrypted.message_hash);
1772
1773        if let Some(group_session) = decrypted.inbound_group_session {
1774            changes.inbound_group_sessions.push(group_session);
1775        }
1776
1777        match decrypted.result.raw_event.deserialize_as() {
1778            Ok(event) => {
1779                self.handle_to_device_event(changes, &event).await;
1780
1781                raw_event = event
1782                    .serialize_zeroized()
1783                    .expect("Zeroizing and reserializing our events should always work")
1784                    .cast();
1785            }
1786            Err(e) => {
1787                warn!("Received an invalid encrypted to-device event: {e}");
1788                raw_event = decrypted.result.raw_event;
1789            }
1790        }
1791
1792        Some(ProcessedToDeviceEvent::Decrypted {
1793            raw: raw_event,
1794            encryption_info: decrypted.result.encryption_info,
1795        })
1796    }
1797
1798    /// Return an error if the supplied to-device event was sent from a
1799    /// dehydrated device.
1800    async fn check_to_device_event_is_not_from_dehydrated_device(
1801        &self,
1802        decrypted: &OlmDecryptionInfo,
1803        sender_user_id: &UserId,
1804    ) -> Result<(), DecryptToDeviceError> {
1805        if self.to_device_event_is_from_dehydrated_device(decrypted, sender_user_id).await? {
1806            warn!(
1807                sender = ?sender_user_id,
1808                session = ?decrypted.session,
1809                "Received a to-device event from a dehydrated device. This is unexpected: ignoring event"
1810            );
1811            Err(DecryptToDeviceError::FromDehydratedDevice)
1812        } else {
1813            Ok(())
1814        }
1815    }
1816
1817    /// Decide whether a decrypted to-device event was sent from a dehydrated
1818    /// device.
1819    ///
1820    /// This accepts an [`OlmDecryptionInfo`] because it deals with a decrypted
1821    /// event.
1822    async fn to_device_event_is_from_dehydrated_device(
1823        &self,
1824        decrypted: &OlmDecryptionInfo,
1825        sender_user_id: &UserId,
1826    ) -> OlmResult<bool> {
1827        // Does the to-device message include device info?
1828        if let Some(device_keys) = decrypted.result.event.sender_device_keys() {
1829            // There is no need to check whether the device keys are signed
1830            // correctly - any to-device message that claims to be from a
1831            // dehydrated device is weird, so we will drop it.
1832
1833            // Does the included device info say the device is dehydrated?
1834            if device_keys.dehydrated.unwrap_or(false) {
1835                return Ok(true);
1836            }
1837            // If not, fall through and check our existing list of devices
1838            // below, just in case the sender is sending us incorrect
1839            // information embedded in the to-device message, but we know
1840            // better.
1841        }
1842
1843        // Do we already know about this device?
1844        Ok(self
1845            .store()
1846            .get_device_from_curve_key(sender_user_id, decrypted.result.sender_key)
1847            .await?
1848            .is_some_and(|d| d.is_dehydrated()))
1849    }
1850
1851    /// Handle changes in the end-to-end-encryption state we received from a
1852    /// /sync request.
1853    ///
1854    /// This will decrypt and handle to-device messages returning the decrypted
1855    /// versions of them.
1856    ///
1857    /// To decrypt an event from the room timeline, call
1858    /// [`OlmMachine::decrypt_room_event`].
1859    ///
1860    /// # Arguments
1861    ///
1862    /// - `sync_changes` - an [`EncryptionSyncChanges`] value, constructed from
1863    ///   a sync response.
1864    /// - `decryption_settings` - Settings controlling how the to-device
1865    ///   messages passed in the [`EncryptionSyncChanges`] should be decrypted.
1866    ///
1867    /// # Returns
1868    ///
1869    /// A tuple of (decrypted to-device events, updated room keys).
1870    #[instrument(skip_all)]
1871    pub async fn receive_sync_changes(
1872        &self,
1873        sync_changes: EncryptionSyncChanges<'_>,
1874        decryption_settings: &DecryptionSettings,
1875    ) -> OlmResult<(Vec<ProcessedToDeviceEvent>, Vec<RoomKeyInfo>)> {
1876        self.receive_sync_changes_impl(sync_changes, decryption_settings, true).await
1877    }
1878
1879    /// Handle changes in the end-to-end-encryption state we received from a
1880    /// MSC4186 /sync request.
1881    ///
1882    /// This will decrypt and handle to-device messages returning the decrypted
1883    /// versions of them.
1884    ///
1885    /// To decrypt an event from the room timeline, call
1886    /// [`OlmMachine::decrypt_room_event`].
1887    ///
1888    /// # Arguments
1889    ///
1890    /// - `sync_changes` - an [`EncryptionSyncChanges`] value, constructed from
1891    ///   a sync response.
1892    /// - `decryption_settings` - Settings controlling how the to-device
1893    ///   messages passed in the [`EncryptionSyncChanges`] should be decrypted.
1894    ///
1895    /// # Returns
1896    ///
1897    /// A tuple of (decrypted to-device events, updated room keys).
1898    #[instrument(skip_all)]
1899    pub async fn receive_sync_changes_msc4186(
1900        &self,
1901        sync_changes: EncryptionSyncChanges<'_>,
1902        decryption_settings: &DecryptionSettings,
1903    ) -> OlmResult<(Vec<ProcessedToDeviceEvent>, Vec<RoomKeyInfo>)> {
1904        self.receive_sync_changes_impl(sync_changes, decryption_settings, false).await
1905    }
1906
1907    /// Body for [`OlmMachine::receive_sync_changes`] and
1908    /// [`OlmMachine::receive_sync_changes_msc4186`].
1909    ///
1910    /// There exist some semantic differences between the two sync APIs we
1911    /// support, this is publicly exposed as different functions, but internally
1912    /// we just use a simple boolean switch.
1913    ///
1914    /// Please take a look at the docs for [`OlmMachine::receive_sync_changes`]
1915    /// and [`Account::update_key_counts`] for more info.
1916    async fn receive_sync_changes_impl(
1917        &self,
1918        sync_changes: EncryptionSyncChanges<'_>,
1919        decryption_settings: &DecryptionSettings,
1920        is_missing_count_zero: bool,
1921    ) -> OlmResult<(Vec<ProcessedToDeviceEvent>, Vec<RoomKeyInfo>)> {
1922        let mut store_transaction = self.inner.store.transaction().await;
1923
1924        {
1925            let account = store_transaction.account().await?;
1926            account.update_key_counts(
1927                sync_changes.one_time_keys_counts,
1928                sync_changes.unused_fallback_keys,
1929                is_missing_count_zero,
1930            )
1931        }
1932
1933        let (events, changes) = self
1934            .preprocess_sync_changes(&mut store_transaction, sync_changes, decryption_settings)
1935            .await?;
1936
1937        // Technically save_changes also does the same work, so if it's slow we
1938        // could refactor this to do it only once.
1939        let room_key_updates: Vec<_> =
1940            changes.inbound_group_sessions.iter().map(RoomKeyInfo::from).collect();
1941
1942        self.store().save_changes(changes).await?;
1943        store_transaction.commit().await?;
1944
1945        Ok((events, room_key_updates))
1946    }
1947
1948    /// Initial processing of the changes specified within a sync response.
1949    ///
1950    /// Returns the to-device events (decrypted where needed and where possible)
1951    /// and the processed set of changes.
1952    ///
1953    /// If any of the to-device events in the supplied changes were sent from
1954    /// dehydrated devices, these are not processed, and are omitted from the
1955    /// returned list, as per MSC3814.
1956    ///
1957    /// If we are in strict "exclude insecure devices" mode and the sender
1958    /// device of any event is not verified, and the decrypted event type is not
1959    /// on the allow list, these events are not processed and are omitted from
1960    /// the returned list.
1961    ///
1962    /// (The allow list of types that are processed even if the sender is
1963    /// unverified is: `m.room_key`, `m.room_key.withheld`,
1964    /// `m.room_key_request`, `m.secret.request` and `m.key.verification.*`.)
1965    pub(crate) async fn preprocess_sync_changes(
1966        &self,
1967        transaction: &mut StoreTransaction,
1968        sync_changes: EncryptionSyncChanges<'_>,
1969        decryption_settings: &DecryptionSettings,
1970    ) -> OlmResult<(Vec<ProcessedToDeviceEvent>, Changes)> {
1971        // Remove verification objects that have expired or are done.
1972        let mut events: Vec<ProcessedToDeviceEvent> = self
1973            .inner
1974            .verification_machine
1975            .garbage_collect()
1976            .iter()
1977            // These are `fake` to device events just serving as local echo in
1978            // order that our own client can react quickly to cancelled
1979            // transaction. Just use PlainText for that.
1980            .map(|e| ProcessedToDeviceEvent::PlainText(e.clone()))
1981            .collect();
1982        // The account is automatically saved by the store transaction created
1983        // by the caller.
1984        let mut changes = Default::default();
1985
1986        if let Err(e) = self
1987            .inner
1988            .identity_manager
1989            .receive_device_changes(
1990                transaction.cache(),
1991                sync_changes.changed_devices.changed.iter().map(|u| u.as_ref()),
1992            )
1993            .await
1994        {
1995            error!(error = ?e, "Error marking a tracked user as changed");
1996        }
1997
1998        for raw_event in sync_changes.to_device_events {
1999            let processed_event = Box::pin(self.receive_to_device_event(
2000                transaction,
2001                &mut changes,
2002                raw_event,
2003                decryption_settings,
2004            ))
2005            .await;
2006
2007            if let Some(processed_event) = processed_event {
2008                events.push(processed_event);
2009            }
2010        }
2011
2012        let changed_sessions = self
2013            .inner
2014            .key_request_machine
2015            .collect_incoming_key_requests(transaction.cache())
2016            .await?;
2017
2018        changes.sessions.extend(changed_sessions);
2019        changes.next_batch_token = sync_changes.next_batch_token;
2020
2021        Ok((events, changes))
2022    }
2023
2024    /// Request a room key from our devices.
2025    ///
2026    /// This method will return a request cancellation and a new key request if
2027    /// the key was already requested, otherwise it will return just the key
2028    /// request.
2029    ///
2030    /// The request cancellation _must_ be sent out before the request is sent
2031    /// out, otherwise devices will ignore the key request.
2032    ///
2033    /// # Arguments
2034    ///
2035    /// - `room_id` - The id of the room where the key is used in.
2036    /// - `sender_key` - The curve25519 key of the sender that owns the key.
2037    /// - `session_id` - The id that uniquely identifies the session.
2038    pub async fn request_room_key(
2039        &self,
2040        event: &Raw<EncryptedEvent>,
2041        room_id: &RoomId,
2042    ) -> MegolmResult<(Option<OutgoingRequest>, OutgoingRequest)> {
2043        let event = event.deserialize()?;
2044        self.inner.key_request_machine.request_key(room_id, &event).await
2045    }
2046
2047    /// Find whether an event decrypted via the supplied session is verified,
2048    /// and provide explanation of what is missing/wrong if not.
2049    ///
2050    /// Stores the updated [`SenderData`] for the session in the store if we
2051    /// find an updated value for it.
2052    ///
2053    /// # Arguments
2054    ///
2055    /// - `session` - The inbound Megolm session that was used to decrypt the
2056    ///   event.
2057    /// - `sender` - The `sender` of that event (as claimed by the envelope of
2058    ///   the event).
2059    async fn get_room_event_verification_state(
2060        &self,
2061        session: &InboundGroupSession,
2062        sender: &UserId,
2063    ) -> MegolmResult<(VerificationState, Option<OwnedDeviceId>)> {
2064        let sender_data = self.get_or_update_sender_data(session, sender).await?;
2065
2066        // If the user ID in the sender data doesn't match that in the event
2067        // envelope, this event is not from who it appears to be from.
2068        //
2069        // If `sender_data.user_id()` returns `None`, that means we don't have
2070        // any information about the owner of the session (i.e. we have
2071        // `SenderData::UnknownDevice`); in that case we fall through to the
2072        // logic in `sender_data_to_verification_state` which will pick an
2073        // appropriate `DeviceLinkProblem` for `VerificationLevel::None`.
2074        let (verification_state, device_id) = match sender_data.user_id() {
2075            Some(i) if i != sender => {
2076                (VerificationState::Unverified(VerificationLevel::MismatchedSender), None)
2077            }
2078
2079            Some(_) | None => {
2080                sender_data_to_verification_state(sender_data, session.has_been_imported())
2081            }
2082        };
2083
2084        Ok((verification_state, device_id))
2085    }
2086
2087    /// Get an up-to-date [`SenderData`] for the given session, suitable for
2088    /// determining if messages decrypted using that session are verified.
2089    ///
2090    /// Checks both the stored verification state of the session and a
2091    /// recalculated verification state based on our current knowledge, and
2092    /// returns the more trusted of the two.
2093    ///
2094    /// Stores the updated [`SenderData`] for the session in the store if we
2095    /// find an updated value for it.
2096    ///
2097    /// # Arguments
2098    ///
2099    /// - `session` - The Megolm session that was used to decrypt the event.
2100    /// - `sender` - The claimed sender of that event.
2101    async fn get_or_update_sender_data(
2102        &self,
2103        session: &InboundGroupSession,
2104        sender: &UserId,
2105    ) -> MegolmResult<SenderData> {
2106        let sender_data = if session.sender_data.should_recalculate() {
2107            // The session is not sure of the sender yet. Try to find a matching
2108            // device belonging to the claimed sender of the recently-received
2109            // event.
2110            //
2111            // It's worth noting that this could in theory result in unintuitive
2112            // changes, like a session which initially appears to belong to
2113            // Alice turning into a session which belongs to Bob [1]. This could
2114            // mean that a session initially successfully decrypts events from
2115            // Alice, but then stops decrypting those same events once we get an
2116            // update.
2117            //
2118            // That's ok though: if we get good evidence that the session
2119            // belongs to Bob, it's correct to update the session even if we
2120            // previously had weak evidence it belonged to Alice.
2121            //
2122            // [1] For example: maybe Alice and Bob both publish devices with
2123            // the _same_ keys (presumably because they are colluding).
2124            // Initially we think the session belongs to Alice, but then we do a
2125            // device lookup for Bob, we find a matching device with a
2126            // cross-signature, so prefer that.
2127            let calculated_sender_data = SenderDataFinder::find_using_curve_key(
2128                self.store(),
2129                session.sender_key(),
2130                sender,
2131                session,
2132            )
2133            .await?;
2134
2135            // Is the newly-calculated sender data more trusted?
2136            if calculated_sender_data.compare_trust_level(&session.sender_data).is_gt() {
2137                // Yes - save it to the store
2138                let mut new_session = session.clone();
2139                new_session.sender_data = calculated_sender_data.clone();
2140                self.store().save_inbound_group_sessions(&[new_session]).await?;
2141
2142                // and use it now.
2143                calculated_sender_data
2144            } else {
2145                // No - use the existing data.
2146                session.sender_data.clone()
2147            }
2148        } else {
2149            session.sender_data.clone()
2150        };
2151
2152        Ok(sender_data)
2153    }
2154
2155    /// Request missing local secrets from our devices (cross signing private
2156    /// keys, megolm backup). This will ask the sdk to create outgoing request
2157    /// to get the missing secrets.
2158    ///
2159    /// The requests will be processed as soon as `outgoing_requests()` is
2160    /// called to process them.
2161    ///
2162    /// # Returns
2163    ///
2164    /// A bool result saying if actual secrets were missing and have been
2165    /// requested
2166    ///
2167    /// # Examples
2168    ///
2169    /// ```
2170    /// # async {
2171    /// # use matrix_sdk_crypto::OlmMachine;
2172    /// # let machine: OlmMachine = unimplemented!();
2173    /// if machine.query_missing_secrets_from_other_sessions().await.unwrap() {
2174    ///     let to_send = machine.outgoing_requests().await.unwrap();
2175    ///     // send the to device requests
2176    /// };
2177    /// # anyhow::Ok(()) };
2178    /// ```
2179    pub async fn query_missing_secrets_from_other_sessions(&self) -> StoreResult<bool> {
2180        let identity = self.inner.user_identity.lock().await;
2181        let mut secrets = identity.get_missing_secrets().await;
2182
2183        if self.store().load_backup_keys().await?.decryption_key.is_none() {
2184            secrets.push(SecretName::RecoveryKey);
2185        }
2186
2187        if secrets.is_empty() {
2188            debug!("No missing requests to query");
2189            return Ok(false);
2190        }
2191
2192        let secret_requests = GossipMachine::request_missing_secrets(self.user_id(), secrets);
2193
2194        // Check if there are already in-flight requests for these secrets?
2195        let unsent_request = self.store().get_unsent_secret_requests().await?;
2196        let not_yet_requested = secret_requests
2197            .into_iter()
2198            .filter(|request| !unsent_request.iter().any(|unsent| unsent.info == request.info))
2199            .collect_vec();
2200
2201        if not_yet_requested.is_empty() {
2202            debug!("The missing secrets have already been requested");
2203            Ok(false)
2204        } else {
2205            debug!("Requesting missing secrets");
2206
2207            let changes = Changes { key_requests: not_yet_requested, ..Default::default() };
2208
2209            self.store().save_changes(changes).await?;
2210            Ok(true)
2211        }
2212    }
2213
2214    /// Push a secret to all of our other verified devices.
2215    ///
2216    /// This function assumes that we already have Olm sessions with the other
2217    /// devices. This can be done by calling
2218    /// [`OlmMachine::get_missing_sessions()`].
2219    ///
2220    /// - `secret_name` - The name of the secret to push
2221    #[cfg(feature = "experimental-push-secrets")]
2222    pub async fn push_secret_to_verified_devices(
2223        &self,
2224        secret_name: SecretName,
2225    ) -> Result<HashMap<OwnedDeviceId, OlmError>, SecretPushError> {
2226        self.inner.key_request_machine.push_secret_to_verified_devices(secret_name).await
2227    }
2228
2229    /// Get some metadata pertaining to a given group session.
2230    ///
2231    /// This includes the session owner's Matrix user ID, their device ID, info
2232    /// regarding the cryptographic algorithm and whether the session, and by
2233    /// extension the events decrypted by the session, are trusted.
2234    async fn get_encryption_info(
2235        &self,
2236        session: &InboundGroupSession,
2237        sender: &UserId,
2238    ) -> MegolmResult<Arc<EncryptionInfo>> {
2239        let (verification_state, device_id) =
2240            self.get_room_event_verification_state(session, sender).await?;
2241
2242        Ok(Arc::new(EncryptionInfo {
2243            sender: sender.to_owned(),
2244            sender_device: device_id,
2245            forwarder: session.forwarder_data.as_ref().and_then(|data| {
2246                // Per the comment on `KnownSenderData::device_id`, we should
2247                // never encounter a `None` value here, but must still deal with
2248                // an `Optional` for backwards compatibility. The approach below
2249                // allows us to avoid unwrapping.
2250                data.device_id().map(|device_id| ForwarderInfo {
2251                    device_id: device_id.to_owned(),
2252                    user_id: data.user_id().to_owned(),
2253                })
2254            }),
2255            algorithm_info: AlgorithmInfo::MegolmV1AesSha2 {
2256                curve25519_key: session.sender_key().to_base64(),
2257                sender_claimed_keys: session
2258                    .signing_keys()
2259                    .iter()
2260                    .map(|(k, v)| (k.to_owned(), v.to_base64()))
2261                    .collect(),
2262                session_id: Some(session.session_id().to_owned()),
2263            },
2264            verification_state,
2265        }))
2266    }
2267
2268    async fn decrypt_megolm_events(
2269        &self,
2270        room_id: &RoomId,
2271        event: &EncryptedEvent,
2272        content: &SupportedEventEncryptionSchemes<'_>,
2273        decryption_settings: &DecryptionSettings,
2274    ) -> MegolmResult<(JsonObject, Arc<EncryptionInfo>)> {
2275        let session =
2276            self.get_inbound_group_session_or_error(room_id, content.session_id()).await?;
2277
2278        // This function is only ever called by decrypt_room_event, so room_id,
2279        // sender, algorithm and session_id are recorded already
2280        //
2281        // While we already record the sender key in some cases from the event,
2282        // the sender key in the event is deprecated, so let's record it now.
2283        Span::current().record("sender_key", debug(session.sender_key()));
2284
2285        let result = session.decrypt(event).await;
2286        match result {
2287            Ok((decrypted_event, _)) => {
2288                let encryption_info = self.get_encryption_info(&session, &event.sender).await?;
2289
2290                self.check_sender_trust_requirement(
2291                    &session,
2292                    &encryption_info,
2293                    &decryption_settings.sender_device_trust_requirement,
2294                )?;
2295
2296                Ok((decrypted_event, encryption_info))
2297            }
2298            Err(error) => Err(
2299                if let MegolmError::Decryption(DecryptionError::UnknownMessageIndex(_, _)) = error {
2300                    let withheld_code = self
2301                        .inner
2302                        .store
2303                        .get_withheld_info(room_id, content.session_id())
2304                        .await?
2305                        .map(|e| e.content.withheld_code());
2306
2307                    if withheld_code.is_some() {
2308                        // Partially withheld, report with a withheld code if we
2309                        // have one.
2310                        MegolmError::MissingRoomKey(withheld_code)
2311                    } else {
2312                        error
2313                    }
2314                } else {
2315                    error
2316                },
2317            ),
2318        }
2319    }
2320
2321    /// Check that a Megolm event satisfies the sender trust requirement from
2322    /// the decryption settings.
2323    ///
2324    /// If the requirement is not satisfied, returns
2325    /// [`MegolmError::SenderIdentityNotTrusted`].
2326    fn check_sender_trust_requirement(
2327        &self,
2328        session: &InboundGroupSession,
2329        encryption_info: &EncryptionInfo,
2330        trust_requirement: &TrustRequirement,
2331    ) -> MegolmResult<()> {
2332        trace!(
2333            verification_state = ?encryption_info.verification_state,
2334            ?trust_requirement, "check_sender_trust_requirement",
2335        );
2336
2337        // VerificationState::Verified is acceptable for all TrustRequirement
2338        // levels, so let's get that out of the way
2339        let verification_level = match &encryption_info.verification_state {
2340            VerificationState::Verified => return Ok(()),
2341            VerificationState::Unverified(verification_level) => verification_level,
2342        };
2343
2344        let ok = match trust_requirement {
2345            TrustRequirement::Untrusted => true,
2346
2347            TrustRequirement::CrossSignedOrLegacy => {
2348                // `VerificationLevel::UnsignedDevice` and
2349                // `VerificationLevel::None` correspond to
2350                // `SenderData::DeviceInfo` and `SenderData::UnknownDevice`
2351                // respectively, and those cases may be acceptable if the reason
2352                // for the lack of data is that the sessions were established
2353                // before we started collecting SenderData.
2354                let legacy_session = match session.sender_data {
2355                    SenderData::DeviceInfo { legacy_session, .. } => legacy_session,
2356                    SenderData::UnknownDevice { legacy_session, .. } => legacy_session,
2357                    _ => false,
2358                };
2359
2360                // In the CrossSignedOrLegacy case the following rules apply:
2361                //
2362                // 1. Identities we have not yet verified can be decrypted
2363                //    regardless of the legacy state of the session.
2364                // 2. Devices that aren't signed by the owning identity of the
2365                //    device can only be decrypted if it's a legacy session.
2366                // 3. If we have no information about the device, we should only
2367                //    decrypt if it's a legacy session.
2368                // 4. Anything else, should throw an error.
2369                match (verification_level, legacy_session) {
2370                    // Case 1
2371                    (VerificationLevel::UnverifiedIdentity, _) => true,
2372
2373                    // Case 2
2374                    (VerificationLevel::UnsignedDevice, true) => true,
2375
2376                    // Case 3
2377                    (VerificationLevel::None(_), true) => true,
2378
2379                    // Case 4
2380                    (VerificationLevel::VerificationViolation, _)
2381                    | (VerificationLevel::MismatchedSender, _)
2382                    | (VerificationLevel::UnsignedDevice, false)
2383                    | (VerificationLevel::None(_), false) => false,
2384                }
2385            }
2386
2387            // If cross-signing of identities is required, the only acceptable
2388            // unverified case is when the identity is signed but not yet
2389            // verified by us.
2390            TrustRequirement::CrossSigned => match verification_level {
2391                VerificationLevel::UnverifiedIdentity => true,
2392
2393                VerificationLevel::VerificationViolation
2394                | VerificationLevel::MismatchedSender
2395                | VerificationLevel::UnsignedDevice
2396                | VerificationLevel::None(_) => false,
2397            },
2398        };
2399
2400        if ok {
2401            Ok(())
2402        } else {
2403            Err(MegolmError::SenderIdentityNotTrusted(verification_level.clone()))
2404        }
2405    }
2406
2407    /// Attempt to retrieve an inbound group session from the store.
2408    ///
2409    /// If the session is not found, checks for withheld reports, and returns a
2410    /// [`MegolmError::MissingRoomKey`] error.
2411    async fn get_inbound_group_session_or_error(
2412        &self,
2413        room_id: &RoomId,
2414        session_id: &str,
2415    ) -> MegolmResult<InboundGroupSession> {
2416        match self.store().get_inbound_group_session(room_id, session_id).await? {
2417            Some(session) => Ok(session),
2418            None => {
2419                let withheld_code = self
2420                    .inner
2421                    .store
2422                    .get_withheld_info(room_id, session_id)
2423                    .await?
2424                    .map(|e| e.content.withheld_code());
2425                Err(MegolmError::MissingRoomKey(withheld_code))
2426            }
2427        }
2428    }
2429
2430    /// Attempt to decrypt an event from a room timeline, returning information
2431    /// on the failure if it fails.
2432    ///
2433    /// # Arguments
2434    ///
2435    /// - `event` - The event that should be decrypted.
2436    /// - `room_id` - The ID of the room where the event was sent to.
2437    ///
2438    /// # Returns
2439    ///
2440    /// The decrypted event, if it was successfully decrypted. Otherwise,
2441    /// information on the failure, unless the failure was due to an internal
2442    /// error, in which case, an `Err` result.
2443    pub async fn try_decrypt_room_event(
2444        &self,
2445        raw_event: &Raw<EncryptedEvent>,
2446        room_id: &RoomId,
2447        decryption_settings: &DecryptionSettings,
2448    ) -> Result<RoomEventDecryptionResult, CryptoStoreError> {
2449        match self.decrypt_room_event_inner(raw_event, room_id, true, decryption_settings).await {
2450            Ok(decrypted) => Ok(RoomEventDecryptionResult::Decrypted(decrypted)),
2451            Err(err) => Ok(RoomEventDecryptionResult::UnableToDecrypt(megolm_error_to_utd_info(
2452                raw_event, err,
2453            )?)),
2454        }
2455    }
2456
2457    /// Decrypt an event from a room timeline.
2458    ///
2459    /// # Arguments
2460    ///
2461    /// * `event` - The event that should be decrypted.
2462    ///
2463    /// * `room_id` - The ID of the room where the event was sent to.
2464    pub async fn decrypt_room_event(
2465        &self,
2466        event: &Raw<EncryptedEvent>,
2467        room_id: &RoomId,
2468        decryption_settings: &DecryptionSettings,
2469    ) -> MegolmResult<DecryptedRoomEvent> {
2470        self.decrypt_room_event_inner(event, room_id, true, decryption_settings).await
2471    }
2472
2473    #[instrument(name = "decrypt_room_event", skip_all, fields(?room_id, event_id, origin_server_ts, sender, algorithm, session_id, message_index, sender_key))]
2474    async fn decrypt_room_event_inner(
2475        &self,
2476        event: &Raw<EncryptedEvent>,
2477        room_id: &RoomId,
2478        decrypt_unsigned: bool,
2479        decryption_settings: &DecryptionSettings,
2480    ) -> MegolmResult<DecryptedRoomEvent> {
2481        let _timer = timer!(tracing::Level::TRACE, "_method");
2482
2483        let event = event.deserialize()?;
2484
2485        Span::current()
2486            .record("sender", debug(&event.sender))
2487            .record("event_id", debug(&event.event_id))
2488            .record(
2489                "origin_server_ts",
2490                timestamp_to_iso8601(event.origin_server_ts)
2491                    .unwrap_or_else(|| "<out of range>".to_owned()),
2492            )
2493            .record("algorithm", debug(event.content.algorithm()));
2494
2495        let content: SupportedEventEncryptionSchemes<'_> = match &event.content.scheme {
2496            RoomEventEncryptionScheme::MegolmV1AesSha2(c) => {
2497                Span::current().record("sender_key", debug(c.sender_key));
2498                c.into()
2499            }
2500            #[cfg(feature = "experimental-algorithms")]
2501            RoomEventEncryptionScheme::MegolmV2AesSha2(c) => c.into(),
2502            RoomEventEncryptionScheme::Unknown(_) => {
2503                warn!("Received an encrypted room event with an unsupported algorithm");
2504                return Err(EventError::UnsupportedAlgorithm.into());
2505            }
2506        };
2507
2508        Span::current().record("session_id", content.session_id());
2509        Span::current().record("message_index", content.message_index());
2510
2511        let result =
2512            self.decrypt_megolm_events(room_id, &event, &content, decryption_settings).await;
2513
2514        if let Err(e) = &result {
2515            #[cfg(feature = "automatic-room-key-forwarding")]
2516            match e {
2517                // Optimisation should we request if we received a withheld
2518                // code? Maybe for some code there is no point
2519                MegolmError::MissingRoomKey(_)
2520                | MegolmError::Decryption(DecryptionError::UnknownMessageIndex(_, _)) => {
2521                    self.inner
2522                        .key_request_machine
2523                        .create_outgoing_key_request(room_id, &event)
2524                        .await?;
2525                }
2526                _ => {}
2527            }
2528
2529            warn!("Failed to decrypt a room event: {e}");
2530        }
2531
2532        let (mut decrypted_event, encryption_info) = result?;
2533
2534        let mut unsigned_encryption_info = None;
2535        if decrypt_unsigned {
2536            // Try to decrypt encrypted unsigned events.
2537            unsigned_encryption_info = self
2538                .decrypt_unsigned_events(&mut decrypted_event, room_id, decryption_settings)
2539                .await;
2540        }
2541
2542        let decrypted_event =
2543            serde_json::from_value::<Raw<AnyTimelineEvent>>(decrypted_event.into())?;
2544
2545        #[cfg(feature = "experimental-encrypted-state-events")]
2546        self.verify_packed_state_key(&event, &decrypted_event)?;
2547
2548        Ok(DecryptedRoomEvent { event: decrypted_event, encryption_info, unsigned_encryption_info })
2549    }
2550
2551    /// If the passed event is a state event, verify its outer packed state key
2552    /// matches the inner state key once unpacked.
2553    ///
2554    /// - `original` - The original encrypted event received over the wire.
2555    /// - `decrypted` - The decrypted event.
2556    ///
2557    /// # Errors
2558    ///
2559    /// Returns an error if any of the following are true:
2560    ///
2561    /// - The original event's state key failed to unpack;
2562    /// - The decrypted event could not be deserialised;
2563    /// - The unpacked event type does not match the type of the decrypted
2564    ///   event;
2565    /// - The unpacked event state key does not match the state key of the
2566    ///   decrypted event.
2567    #[cfg(feature = "experimental-encrypted-state-events")]
2568    fn verify_packed_state_key(
2569        &self,
2570        original: &EncryptedEvent,
2571        decrypted: &Raw<AnyTimelineEvent>,
2572    ) -> MegolmResult<()> {
2573        use serde::Deserialize;
2574
2575        // Helper for deserializing.
2576        #[derive(Deserialize)]
2577        struct PayloadDeserializationHelper {
2578            state_key: Option<String>,
2579            #[serde(rename = "type")]
2580            event_type: String,
2581        }
2582
2583        // Deserialize the decrypted event.
2584        let PayloadDeserializationHelper {
2585            state_key: inner_state_key,
2586            event_type: inner_event_type,
2587        } = decrypted
2588            .deserialize_as_unchecked()
2589            .map_err(|_| MegolmError::StateKeyVerificationFailed)?;
2590
2591        // Ensure we have a state key on the outer event iff there is one in the
2592        // inner.
2593        let (raw_state_key, inner_state_key) = match (&original.state_key, &inner_state_key) {
2594            (Some(raw_state_key), Some(inner_state_key)) => (raw_state_key, inner_state_key),
2595            (None, None) => return Ok(()),
2596            _ => return Err(MegolmError::StateKeyVerificationFailed),
2597        };
2598
2599        // Unpack event type and state key from the raw state key.
2600        let (outer_event_type, outer_state_key) =
2601            raw_state_key.split_once(":").ok_or(MegolmError::StateKeyVerificationFailed)?;
2602
2603        // Check event types match, discard if not.
2604        if outer_event_type != inner_event_type {
2605            return Err(MegolmError::StateKeyVerificationFailed);
2606        }
2607
2608        // Check state keys match, discard if not.
2609        if outer_state_key != inner_state_key {
2610            return Err(MegolmError::StateKeyVerificationFailed);
2611        }
2612        Ok(())
2613    }
2614
2615    /// Try to decrypt the events bundled in the `unsigned` object of the given
2616    /// event.
2617    ///
2618    /// # Arguments
2619    ///
2620    /// - `main_event` - The event that may contain bundled encrypted events in
2621    ///   its `unsigned` object.
2622    ///
2623    /// - `room_id` - The ID of the room where the event was sent to.
2624    async fn decrypt_unsigned_events(
2625        &self,
2626        main_event: &mut JsonObject,
2627        room_id: &RoomId,
2628        decryption_settings: &DecryptionSettings,
2629    ) -> Option<BTreeMap<UnsignedEventLocation, UnsignedDecryptionResult>> {
2630        let unsigned = main_event.get_mut("unsigned")?.as_object_mut()?;
2631        let mut unsigned_encryption_info: Option<
2632            BTreeMap<UnsignedEventLocation, UnsignedDecryptionResult>,
2633        > = None;
2634
2635        // Search for an encrypted event in `m.replace`, an edit.
2636        let location = UnsignedEventLocation::RelationsReplace;
2637        let replace = location.find_mut(unsigned);
2638        if let Some(decryption_result) =
2639            self.decrypt_unsigned_event(replace, room_id, decryption_settings).await
2640        {
2641            unsigned_encryption_info
2642                .get_or_insert_with(Default::default)
2643                .insert(location, decryption_result);
2644        }
2645
2646        // Search for an encrypted event in `latest_event` in `m.thread`, the
2647        // latest event of a thread.
2648        let location = UnsignedEventLocation::RelationsThreadLatestEvent;
2649        let thread_latest_event = location.find_mut(unsigned);
2650        if let Some(decryption_result) =
2651            self.decrypt_unsigned_event(thread_latest_event, room_id, decryption_settings).await
2652        {
2653            unsigned_encryption_info
2654                .get_or_insert_with(Default::default)
2655                .insert(location, decryption_result);
2656        }
2657
2658        unsigned_encryption_info
2659    }
2660
2661    /// Try to decrypt the given bundled event.
2662    ///
2663    /// # Arguments
2664    ///
2665    /// * `event` - The bundled event that may be encrypted
2666    ///
2667    /// * `room_id` - The ID of the room where the event was sent to.
2668    fn decrypt_unsigned_event<'a>(
2669        &'a self,
2670        event: Option<&'a mut Value>,
2671        room_id: &'a RoomId,
2672        decryption_settings: &'a DecryptionSettings,
2673    ) -> BoxFuture<'a, Option<UnsignedDecryptionResult>> {
2674        Box::pin(async move {
2675            let event = event?;
2676
2677            let is_encrypted = event
2678                .get("type")
2679                .and_then(|type_| type_.as_str())
2680                .is_some_and(|s| s == "m.room.encrypted");
2681            if !is_encrypted {
2682                return None;
2683            }
2684
2685            let raw_event = serde_json::from_value(event.clone()).ok()?;
2686            match self
2687                .decrypt_room_event_inner(&raw_event, room_id, false, decryption_settings)
2688                .await
2689            {
2690                Ok(decrypted_event) => {
2691                    // Replace the encrypted event.
2692                    *event = serde_json::to_value(decrypted_event.event).ok()?;
2693                    Some(UnsignedDecryptionResult::Decrypted(decrypted_event.encryption_info))
2694                }
2695                Err(err) => {
2696                    // For now, we throw away crypto store errors and just treat
2697                    // the unsigned event as unencrypted. Crypto store errors
2698                    // represent problems with the application rather than
2699                    // normal UTD errors, so they should probably be propagated
2700                    // rather than swallowed.
2701                    let utd_info = megolm_error_to_utd_info(&raw_event, err).ok()?;
2702                    Some(UnsignedDecryptionResult::UnableToDecrypt(utd_info))
2703                }
2704            }
2705        })
2706    }
2707
2708    /// Check if we have the room key for the given event in the store.
2709    ///
2710    /// # Arguments
2711    ///
2712    /// - `event` - The event to get information for.
2713    /// - `room_id` - The ID of the room where the event was sent to.
2714    pub async fn is_room_key_available(
2715        &self,
2716        event: &Raw<EncryptedEvent>,
2717        room_id: &RoomId,
2718    ) -> Result<bool, CryptoStoreError> {
2719        let event = event.deserialize()?;
2720
2721        let (session_id, message_index) = match &event.content.scheme {
2722            RoomEventEncryptionScheme::MegolmV1AesSha2(c) => {
2723                (&c.session_id, c.ciphertext.message_index())
2724            }
2725            #[cfg(feature = "experimental-algorithms")]
2726            RoomEventEncryptionScheme::MegolmV2AesSha2(c) => {
2727                (&c.session_id, c.ciphertext.message_index())
2728            }
2729            RoomEventEncryptionScheme::Unknown(_) => {
2730                // We don't support this encryption algorithm, so clearly don't
2731                // have its key.
2732                return Ok(false);
2733            }
2734        };
2735
2736        // Check that we have the session in the store, and that its first known
2737        // index predates the index of our message.
2738        Ok(self
2739            .store()
2740            .get_inbound_group_session(room_id, session_id)
2741            .await?
2742            .filter(|s| s.first_known_index() <= message_index)
2743            .is_some())
2744    }
2745
2746    /// Get encryption info for a decrypted timeline event.
2747    ///
2748    /// This recalculates the [`EncryptionInfo`] data that is returned by
2749    /// [`OlmMachine::decrypt_room_event`], based on the current verification
2750    /// status of the sender, etc.
2751    ///
2752    /// Returns an error for an unencrypted event.
2753    ///
2754    /// # Arguments
2755    ///
2756    /// - `event` - The event to get information for.
2757    /// - `room_id` - The ID of the room where the event was sent to.
2758    #[instrument(skip(self, event), fields(event_id, sender, session_id))]
2759    pub async fn get_room_event_encryption_info(
2760        &self,
2761        event: &Raw<EncryptedEvent>,
2762        room_id: &RoomId,
2763    ) -> MegolmResult<Arc<EncryptionInfo>> {
2764        let event = event.deserialize()?;
2765
2766        let content: SupportedEventEncryptionSchemes<'_> = match &event.content.scheme {
2767            RoomEventEncryptionScheme::MegolmV1AesSha2(c) => c.into(),
2768            #[cfg(feature = "experimental-algorithms")]
2769            RoomEventEncryptionScheme::MegolmV2AesSha2(c) => c.into(),
2770            RoomEventEncryptionScheme::Unknown(_) => {
2771                return Err(EventError::UnsupportedAlgorithm.into());
2772            }
2773        };
2774
2775        Span::current()
2776            .record("sender", debug(&event.sender))
2777            .record("event_id", debug(&event.event_id))
2778            .record("session_id", content.session_id());
2779
2780        self.get_session_encryption_info(room_id, content.session_id(), &event.sender).await
2781    }
2782
2783    /// Get encryption info for an event decrypted with a megolm session.
2784    ///
2785    /// This recalculates the [`EncryptionInfo`] data that is returned by
2786    /// [`OlmMachine::decrypt_room_event`], based on the current verification
2787    /// status of the sender, etc.
2788    ///
2789    /// Returns an error if the session can't be found.
2790    ///
2791    /// # Arguments
2792    ///
2793    /// - `room_id` - The ID of the room where the session is being used.
2794    /// - `session_id` - The ID of the session to get information for.
2795    /// - `sender` - The (claimed) sender of the event where the session was
2796    ///   used.
2797    pub async fn get_session_encryption_info(
2798        &self,
2799        room_id: &RoomId,
2800        session_id: &str,
2801        sender: &UserId,
2802    ) -> MegolmResult<Arc<EncryptionInfo>> {
2803        let session = self.get_inbound_group_session_or_error(room_id, session_id).await?;
2804        self.get_encryption_info(&session, sender).await
2805    }
2806
2807    /// Update the list of tracked users.
2808    ///
2809    /// The OlmMachine maintains a list of users whose devices we are keeping
2810    /// track of: these are known as "tracked users". These must be users that
2811    /// we share a room with, so that the server sends us updates for their
2812    /// device lists.
2813    ///
2814    /// # Arguments
2815    ///
2816    /// - `users` - An iterator over user ids that should be added to the list
2817    ///   of tracked users
2818    ///
2819    /// Any users that hadn't been seen before will be flagged for a key query
2820    /// immediately, and whenever [`OlmMachine::receive_sync_changes()`]
2821    /// receives a "changed" notification for that user in the future.
2822    ///
2823    /// Users that were already in the list are unaffected.
2824    pub async fn update_tracked_users(
2825        &self,
2826        users: impl IntoIterator<Item = &UserId>,
2827    ) -> StoreResult<()> {
2828        self.inner.identity_manager.update_tracked_users(users).await
2829    }
2830
2831    /// Mark all tracked users as dirty.
2832    ///
2833    /// All users _whose device lists we are tracking_ are flagged as needing a
2834    /// key query. Users whose devices we are not tracking are ignored.
2835    pub async fn mark_all_tracked_users_as_dirty(&self) -> StoreResult<()> {
2836        self.inner
2837            .identity_manager
2838            .mark_all_tracked_users_as_dirty(self.inner.store.cache().await?)
2839            .await
2840    }
2841
2842    async fn wait_if_user_pending(
2843        &self,
2844        user_id: &UserId,
2845        timeout: Option<Duration>,
2846    ) -> StoreResult<()> {
2847        if let Some(timeout) = timeout {
2848            let cache = self.store().cache().await?;
2849            self.inner
2850                .identity_manager
2851                .key_query_manager
2852                .wait_if_user_key_query_pending(cache, timeout, user_id)
2853                .await?;
2854        }
2855        Ok(())
2856    }
2857
2858    /// Get a specific device of a user.
2859    ///
2860    /// # Arguments
2861    ///
2862    /// - `user_id` - The unique id of the user that the device belongs to.
2863    /// - `device_id` - The unique id of the device.
2864    /// - `timeout` - The amount of time we should wait before returning if the
2865    /// user's device list has been marked as stale. **Note**, this assumes that
2866    /// the requests from [`OlmMachine::outgoing_requests`] are being processed
2867    /// and sent out.
2868    ///
2869    /// Returns a `Device` if one is found and the crypto store didn't throw an
2870    /// error.
2871    ///
2872    /// # Examples
2873    ///
2874    /// ```
2875    /// # use matrix_sdk_crypto::OlmMachine;
2876    /// # use ruma::{device_id, owned_user_id};
2877    /// # let alice = owned_user_id!("@alice:example.org");
2878    /// # futures_executor::block_on(async {
2879    /// # let machine = OlmMachine::new(&alice, device_id!("DEVICEID")).await;
2880    /// let device = machine.get_device(&alice, device_id!("DEVICEID"), None).await;
2881    ///
2882    /// println!("{:?}", device);
2883    /// # });
2884    /// ```
2885    #[instrument(skip(self))]
2886    pub async fn get_device(
2887        &self,
2888        user_id: &UserId,
2889        device_id: &DeviceId,
2890        timeout: Option<Duration>,
2891    ) -> StoreResult<Option<Device>> {
2892        self.wait_if_user_pending(user_id, timeout).await?;
2893        self.store().get_device(user_id, device_id).await
2894    }
2895
2896    /// Get the cross signing user identity of a user.
2897    ///
2898    /// # Arguments
2899    ///
2900    /// - `user_id` - The unique id of the user that the identity belongs to
2901    /// - `timeout` - The amount of time we should wait before returning if the
2902    /// user's device list has been marked as stale. **Note**, this assumes that
2903    /// the requests from [`OlmMachine::outgoing_requests`] are being processed
2904    /// and sent out.
2905    ///
2906    /// Returns a [`UserIdentity`] enum if one is found and the crypto store
2907    /// didn't throw an error.
2908    #[instrument(skip(self))]
2909    pub async fn get_identity(
2910        &self,
2911        user_id: &UserId,
2912        timeout: Option<Duration>,
2913    ) -> StoreResult<Option<UserIdentity>> {
2914        self.wait_if_user_pending(user_id, timeout).await?;
2915        self.store().get_identity(user_id).await
2916    }
2917
2918    /// Get a map holding all the devices of an user.
2919    ///
2920    /// # Arguments
2921    ///
2922    /// - `user_id` - The unique id of the user that the devices belong to.
2923    /// - `timeout` - The amount of time we should wait before returning if the
2924    /// user's device list has been marked as stale. **Note**, this assumes that
2925    /// the requests from [`OlmMachine::outgoing_requests`] are being processed
2926    /// and sent out.
2927    ///
2928    /// # Examples
2929    ///
2930    /// ```
2931    /// # use matrix_sdk_crypto::OlmMachine;
2932    /// # use ruma::{device_id, owned_user_id};
2933    /// # let alice = owned_user_id!("@alice:example.org");
2934    /// # futures_executor::block_on(async {
2935    /// # let machine = OlmMachine::new(&alice, device_id!("DEVICEID")).await;
2936    /// let devices = machine.get_user_devices(&alice, None).await.unwrap();
2937    ///
2938    /// for device in devices.devices() {
2939    ///     println!("{:?}", device);
2940    /// }
2941    /// # });
2942    /// ```
2943    #[instrument(skip(self))]
2944    pub async fn get_user_devices(
2945        &self,
2946        user_id: &UserId,
2947        timeout: Option<Duration>,
2948    ) -> StoreResult<UserDevices> {
2949        self.wait_if_user_pending(user_id, timeout).await?;
2950        self.store().get_user_devices(user_id).await
2951    }
2952
2953    /// Get the status of the private cross signing keys.
2954    ///
2955    /// This can be used to check which private cross signing keys we have
2956    /// stored locally.
2957    pub async fn cross_signing_status(&self) -> CrossSigningStatus {
2958        self.inner.user_identity.lock().await.status().await
2959    }
2960
2961    /// Export all the private cross signing keys we have.
2962    ///
2963    /// The export will contain the seed for the ed25519 keys as a unpadded
2964    /// base64 encoded string.
2965    ///
2966    /// This method returns `None` if we don't have any private cross signing
2967    /// keys.
2968    pub async fn export_cross_signing_keys(&self) -> StoreResult<Option<CrossSigningKeyExport>> {
2969        let master_key = self.store().export_secret(&SecretName::CrossSigningMasterKey).await?;
2970        let self_signing_key =
2971            self.store().export_secret(&SecretName::CrossSigningSelfSigningKey).await?;
2972        let user_signing_key =
2973            self.store().export_secret(&SecretName::CrossSigningUserSigningKey).await?;
2974
2975        Ok(if master_key.is_none() && self_signing_key.is_none() && user_signing_key.is_none() {
2976            None
2977        } else {
2978            Some(CrossSigningKeyExport { master_key, self_signing_key, user_signing_key })
2979        })
2980    }
2981
2982    /// Import our private cross signing keys.
2983    ///
2984    /// The export needs to contain the seed for the ed25519 keys as an unpadded
2985    /// base64 encoded string.
2986    pub async fn import_cross_signing_keys(
2987        &self,
2988        export: CrossSigningKeyExport,
2989    ) -> Result<CrossSigningStatus, SecretImportError> {
2990        self.store().import_cross_signing_keys(export).await
2991    }
2992
2993    async fn sign_with_master_key(
2994        &self,
2995        message: &str,
2996    ) -> Result<(OwnedDeviceKeyId, Ed25519Signature), SignatureError> {
2997        let identity = &*self.inner.user_identity.lock().await;
2998        let key_id = identity.master_key_id().await.ok_or(SignatureError::MissingSigningKey)?;
2999
3000        let signature = identity.sign(message).await?;
3001
3002        Ok((key_id, signature))
3003    }
3004
3005    /// Sign the given message using our device key and if available cross
3006    /// signing master key.
3007    ///
3008    /// Presently, this should only be used for signing the server-side room key
3009    /// backups.
3010    pub async fn sign(&self, message: &str) -> Result<Signatures, CryptoStoreError> {
3011        let mut signatures = Signatures::new();
3012
3013        {
3014            let cache = self.inner.store.cache().await?;
3015            let account = cache.account().await?;
3016            let key_id = account.signing_key_id();
3017            let signature = account.sign(message);
3018            signatures.add_signature(self.user_id().to_owned(), key_id, signature);
3019        }
3020
3021        match self.sign_with_master_key(message).await {
3022            Ok((key_id, signature)) => {
3023                signatures.add_signature(self.user_id().to_owned(), key_id, signature);
3024            }
3025            Err(e) => {
3026                warn!(error = ?e, "Couldn't sign the message using the cross signing master key")
3027            }
3028        }
3029
3030        Ok(signatures)
3031    }
3032
3033    /// Get a reference to the backup related state machine.
3034    ///
3035    /// This state machine can be used to incrementally backup all room keys to
3036    /// the server.
3037    pub fn backup_machine(&self) -> &BackupMachine {
3038        &self.inner.backup_machine
3039    }
3040
3041    /// Syncs the database and in-memory generation counter.
3042    ///
3043    /// This requires that the crypto store lock has been acquired already.
3044    pub async fn initialize_crypto_store_generation(
3045        &self,
3046        generation: &Mutex<Option<u64>>,
3047    ) -> StoreResult<()> {
3048        // Avoid reentrant initialization by taking the lock for the entire's
3049        // function scope.
3050        let mut gen_guard = generation.lock().await;
3051
3052        let prev_generation =
3053            self.inner.store.get_custom_value(Self::CURRENT_GENERATION_STORE_KEY).await?;
3054
3055        let generation = match prev_generation {
3056            Some(val) => {
3057                // There was a value in the store. We need to signal that we're
3058                // a different process, so we don't just reuse the value but
3059                // increment it.
3060                u64::from_le_bytes(val.try_into().map_err(|_| {
3061                    CryptoStoreError::InvalidLockGeneration("invalid format".to_owned())
3062                })?)
3063                .wrapping_add(1)
3064            }
3065            None => 0,
3066        };
3067
3068        tracing::debug!("Initialising crypto store generation at {generation}");
3069
3070        self.inner
3071            .store
3072            .set_custom_value(Self::CURRENT_GENERATION_STORE_KEY, generation.to_le_bytes().to_vec())
3073            .await?;
3074
3075        *gen_guard = Some(generation);
3076
3077        Ok(())
3078    }
3079
3080    /// If needs be, update the local and on-disk crypto store generation.
3081    ///
3082    /// ## Requirements
3083    ///
3084    /// - This assumes that `initialize_crypto_store_generation` has been called
3085    ///   beforehand.
3086    /// - This requires that the crypto store lock has been acquired.
3087    ///
3088    /// # Arguments
3089    ///
3090    /// - `generation` - The in-memory generation counter (or rather, the
3091    ///   `Mutex` wrapping it). This defines the "expected" generation on entry,
3092    ///   and, if we determine an update is needed, is updated to hold the "new"
3093    ///   generation.
3094    ///
3095    /// # Returns
3096    ///
3097    /// A tuple containing:
3098    ///
3099    /// - A `bool`, set to `true` if another process has updated the generation
3100    ///   number in the `Store` since our expected value, and as such we've
3101    ///   incremented and updated it in the database. Otherwise, `false`.
3102    ///
3103    /// - The (possibly updated) generation counter.
3104    pub async fn maintain_crypto_store_generation(
3105        &'_ self,
3106        generation: &Mutex<Option<u64>>,
3107    ) -> StoreResult<(bool, u64)> {
3108        let mut gen_guard = generation.lock().await;
3109
3110        // The database value must be there:
3111        //
3112        // - either we could initialize beforehand, thus write into the
3113        //   database,
3114        // - or we couldn't, and then another process was holding onto the
3115        //   database's lock, thus
3116        // has written a generation counter in there.
3117        let actual_gen = self
3118            .inner
3119            .store
3120            .get_custom_value(Self::CURRENT_GENERATION_STORE_KEY)
3121            .await?
3122            .ok_or_else(|| {
3123                CryptoStoreError::InvalidLockGeneration("counter missing in store".to_owned())
3124            })?;
3125
3126        let actual_gen =
3127            u64::from_le_bytes(actual_gen.try_into().map_err(|_| {
3128                CryptoStoreError::InvalidLockGeneration("invalid format".to_owned())
3129            })?);
3130
3131        let new_gen = match gen_guard.as_ref() {
3132            Some(expected_gen) => {
3133                if actual_gen == *expected_gen {
3134                    return Ok((false, actual_gen));
3135                }
3136                // Increment the biggest, and store it everywhere.
3137                actual_gen.max(*expected_gen).wrapping_add(1)
3138            }
3139            None => {
3140                // Some other process hold onto the lock when initializing, so
3141                // we must reload. Increment database value, and store it
3142                // everywhere.
3143                actual_gen.wrapping_add(1)
3144            }
3145        };
3146
3147        tracing::debug!(
3148            "Crypto store generation mismatch: previously known was {:?}, actual is {:?}, next is {}",
3149            *gen_guard,
3150            actual_gen,
3151            new_gen
3152        );
3153
3154        // Update known value.
3155        *gen_guard = Some(new_gen);
3156
3157        // Update value in database.
3158        self.inner
3159            .store
3160            .set_custom_value(Self::CURRENT_GENERATION_STORE_KEY, new_gen.to_le_bytes().to_vec())
3161            .await?;
3162
3163        Ok((true, new_gen))
3164    }
3165
3166    /// Manage dehydrated devices.
3167    pub fn dehydrated_devices(&self) -> DehydratedDevices {
3168        DehydratedDevices { inner: self.to_owned() }
3169    }
3170
3171    /// Get the stored encryption settings for the given room, such as the
3172    /// encryption algorithm or whether to encrypt only for trusted devices.
3173    ///
3174    /// These settings can be modified via [`OlmMachine::set_room_settings`].
3175    pub async fn room_settings(&self, room_id: &RoomId) -> StoreResult<Option<RoomSettings>> {
3176        // There's not much to do here: it's just exposed for symmetry with
3177        // `set_room_settings`.
3178        self.inner.store.get_room_settings(room_id).await
3179    }
3180
3181    /// Store encryption settings for the given room.
3182    ///
3183    /// This method checks if the new settings are "safe" -- ie, that they do
3184    /// not represent a downgrade in encryption security from any previous
3185    /// settings. Attempts to downgrade security will result in a
3186    /// [`SetRoomSettingsError::EncryptionDowngrade`].
3187    ///
3188    /// If the settings are valid, they will be persisted to the crypto store.
3189    /// These settings are not used directly by this library, but the saved
3190    /// settings can be retrieved via [`OlmMachine::room_settings`].
3191    pub async fn set_room_settings(
3192        &self,
3193        room_id: &RoomId,
3194        new_settings: &RoomSettings,
3195    ) -> Result<(), SetRoomSettingsError> {
3196        let store = &self.inner.store;
3197
3198        // We want to make sure that we do not race against a second concurrent
3199        // call to `set_room_settings`. By way of an easy way to do so, we start
3200        // a StoreTransaction. There's no need to commit() it: we're just using
3201        // it as a lock guard.
3202        let _store_transaction = store.transaction().await;
3203
3204        let old_settings = store.get_room_settings(room_id).await?;
3205
3206        // We want to make sure that the change to the room settings does not
3207        // represent a downgrade in security. The [E2EE implementation guide]
3208        // recommends:
3209        //
3210        //  > This flag should **not** be cleared if a later `m.room.encryption`
3211        //  > event changes the configuration.
3212        //
3213        // (However, it doesn't really address how to handle changes to the
3214        // rotation parameters, etc.) For now at least, we are very conservative
3215        // here: any new settings are rejected if they differ from the existing
3216        // settings. merit improvement (cf
3217        // https://github.com/element-hq/element-meta/issues/69).
3218        //
3219        // [E2EE implementation guide]: https://matrix.org/docs/matrix-concepts/end-to-end-encryption/#handling-an-m-room-encryption-state-event
3220        if let Some(old_settings) = old_settings {
3221            if old_settings != *new_settings {
3222                return Err(SetRoomSettingsError::EncryptionDowngrade);
3223            } else {
3224                // nothing to do here
3225                return Ok(());
3226            }
3227        }
3228
3229        // Make sure that the new settings are valid
3230        match new_settings.algorithm {
3231            EventEncryptionAlgorithm::MegolmV1AesSha2 => (),
3232
3233            #[cfg(feature = "experimental-algorithms")]
3234            EventEncryptionAlgorithm::MegolmV2AesSha2 => (),
3235
3236            _ => {
3237                warn!(
3238                    ?room_id,
3239                    "Rejecting invalid encryption algorithm {}", new_settings.algorithm
3240                );
3241                return Err(SetRoomSettingsError::InvalidSettings);
3242            }
3243        }
3244
3245        // The new settings are acceptable, so let's save them.
3246        store
3247            .save_changes(Changes {
3248                room_settings: HashMap::from([(room_id.to_owned(), new_settings.clone())]),
3249                ..Default::default()
3250            })
3251            .await?;
3252
3253        Ok(())
3254    }
3255
3256    /// Returns whether this `OlmMachine` is the same another one.
3257    ///
3258    /// Useful for testing purposes only.
3259    #[cfg(any(feature = "testing", test))]
3260    pub fn same_as(&self, other: &OlmMachine) -> bool {
3261        Arc::ptr_eq(&self.inner, &other.inner)
3262    }
3263
3264    /// Testing purposes only.
3265    #[cfg(any(feature = "testing", test))]
3266    pub async fn uploaded_key_count(&self) -> Result<u64, CryptoStoreError> {
3267        let cache = self.inner.store.cache().await?;
3268        let account = cache.account().await?;
3269        Ok(account.uploaded_key_count())
3270    }
3271
3272    /// Returns the identity manager.
3273    #[cfg(test)]
3274    pub(crate) fn identity_manager(&self) -> &IdentityManager {
3275        &self.inner.identity_manager
3276    }
3277
3278    /// Returns a store key, only useful for testing purposes.
3279    #[cfg(test)]
3280    pub(crate) fn key_for_has_migrated_verification_latch() -> &'static str {
3281        Self::HAS_MIGRATED_VERIFICATION_LATCH
3282    }
3283}
3284
3285fn sender_data_to_verification_state(
3286    sender_data: SenderData,
3287    session_has_been_imported: bool,
3288) -> (VerificationState, Option<OwnedDeviceId>) {
3289    match sender_data {
3290        SenderData::UnknownDevice { owner_check_failed: false, .. } => {
3291            let device_link_problem = if session_has_been_imported {
3292                DeviceLinkProblem::InsecureSource
3293            } else {
3294                DeviceLinkProblem::MissingDevice
3295            };
3296
3297            (VerificationState::Unverified(VerificationLevel::None(device_link_problem)), None)
3298        }
3299        SenderData::UnknownDevice { owner_check_failed: true, .. } => (
3300            VerificationState::Unverified(VerificationLevel::None(
3301                DeviceLinkProblem::InsecureSource,
3302            )),
3303            None,
3304        ),
3305        SenderData::DeviceInfo { device_keys, .. } => (
3306            VerificationState::Unverified(VerificationLevel::UnsignedDevice),
3307            Some(device_keys.device_id),
3308        ),
3309        SenderData::VerificationViolation(KnownSenderData { device_id, .. }) => {
3310            (VerificationState::Unverified(VerificationLevel::VerificationViolation), device_id)
3311        }
3312        SenderData::SenderUnverified(KnownSenderData { device_id, .. }) => {
3313            (VerificationState::Unverified(VerificationLevel::UnverifiedIdentity), device_id)
3314        }
3315        SenderData::SenderVerified(KnownSenderData { device_id, .. }) => {
3316            (VerificationState::Verified, device_id)
3317        }
3318    }
3319}
3320
3321/// A set of requests to be executed when bootstrapping cross-signing using
3322/// [`OlmMachine::bootstrap_cross_signing`].
3323#[derive(Debug, Clone)]
3324pub struct CrossSigningBootstrapRequests {
3325    /// An optional request to upload a device key.
3326    ///
3327    /// Should be sent first, if present.
3328    ///
3329    /// If present, its result must be processed back with
3330    /// `OlmMachine::mark_request_as_sent`.
3331    pub upload_keys_req: Option<OutgoingRequest>,
3332
3333    /// Request to upload the cross-signing keys.
3334    ///
3335    /// Should be sent second.
3336    pub upload_signing_keys_req: UploadSigningKeysRequest,
3337
3338    /// Request to upload key signatures, including those for the cross-signing
3339    /// keys, and maybe some for the optional uploaded key too.
3340    ///
3341    /// Should be sent last.
3342    pub upload_signatures_req: UploadSignaturesRequest,
3343}
3344
3345/// A handle to a cross-signing reset that has not yet been committed.
3346#[derive(Debug)]
3347pub struct UncommittedCrossSigningReset {
3348    /// A reference to the OlmMachine that created this handle.
3349    olm_machine: OlmMachine,
3350    /// The new private cross-signing identity.
3351    identity: PrivateCrossSigningIdentity,
3352    /// The public counterpart of the new cross-signing identity.
3353    public: OwnUserIdentityData,
3354    /// Request to upload the new cross-signing keys.
3355    ///
3356    /// See [`CrossSigningBootstrapRequests::upload_signing_keys_req`] for more
3357    /// information.
3358    upload_signing_keys_req: UploadSigningKeysRequest,
3359    /// Request to upload the signatures for the new cross-signing keys.
3360    ///
3361    /// See [`CrossSigningBootstrapRequests::upload_signatures_req`] for more
3362    /// information.
3363    upload_signatures_req: UploadSignaturesRequest,
3364}
3365
3366impl UncommittedCrossSigningReset {
3367    /// Get a reference to the request to upload the new cross-signing keys.
3368    pub fn upload_signing_keys_req(&self) -> &UploadSigningKeysRequest {
3369        &self.upload_signing_keys_req
3370    }
3371
3372    /// Commit the cross-signing reset.
3373    ///
3374    /// This will store the new cross-signing identity in the crypto store,
3375    /// overwriting any previous identity.
3376    ///
3377    /// Returns the request to upload the signatures for the new cross-signing
3378    /// keys. It should be sent out before any pending device keys are
3379    /// uploaded, since a failed device keys upload is retried after the next
3380    /// sync, while a failed signatures upload wouldn't be.
3381    pub async fn commit(self) -> Result<UploadSignaturesRequest, CryptoStoreError> {
3382        let Self { olm_machine, identity, public, upload_signatures_req, .. } = self;
3383
3384        *olm_machine.inner.user_identity.lock().await = identity.clone();
3385
3386        olm_machine
3387            .store()
3388            .save_changes(Changes {
3389                identities: IdentityChanges {
3390                    new: vec![public.clone().into()],
3391                    ..Default::default()
3392                },
3393                private_identity: Some(identity.clone()),
3394                ..Default::default()
3395            })
3396            .await?;
3397
3398        Ok(upload_signatures_req.clone())
3399    }
3400}
3401
3402/// An error that can occur during [`OlmMachine::bootstrap_cross_signing`]:
3403///
3404/// * because a failure with the store occurred, or
3405///
3406/// * because the new cross-signing identity could not be signed.
3407#[derive(Debug, thiserror::Error)]
3408pub enum BootstrapCrossSigningError {
3409    /// A failure with the store occurred.
3410    #[error(transparent)]
3411    CryptoStore(#[from] CryptoStoreError),
3412
3413    /// The new cross-signing identity could not be signed
3414    #[error(transparent)]
3415    Signature(#[from] SignatureError),
3416}
3417
3418/// Data contained from a sync response and that needs to be processed by the
3419/// OlmMachine.
3420#[derive(Debug)]
3421pub struct EncryptionSyncChanges<'a> {
3422    /// The list of to-device events received in the sync.
3423    pub to_device_events: Vec<Raw<AnyToDeviceEvent>>,
3424    /// The mapping of changed and left devices, per user, as returned in the
3425    /// sync response.
3426    pub changed_devices: &'a DeviceLists,
3427    /// The number of one time keys, as returned in the sync response.
3428    pub one_time_keys_counts: &'a BTreeMap<OneTimeKeyAlgorithm, UInt>,
3429    /// An optional list of fallback keys.
3430    pub unused_fallback_keys: Option<&'a [OneTimeKeyAlgorithm]>,
3431    /// A next-batch token obtained from a to-device sync query.
3432    pub next_batch_token: Option<String>,
3433}
3434
3435/// Convert a [`MegolmError`] into an [`UnableToDecryptInfo`] or a
3436/// [`CryptoStoreError`].
3437///
3438/// Most `MegolmError` codes are converted into a suitable
3439/// `UnableToDecryptInfo`. The exception is [`MegolmError::Store`], which
3440/// represents a problem with our datastore rather than with the message itself,
3441/// and is therefore returned as a `CryptoStoreError`.
3442fn megolm_error_to_utd_info(
3443    raw_event: &Raw<EncryptedEvent>,
3444    error: MegolmError,
3445) -> Result<UnableToDecryptInfo, CryptoStoreError> {
3446    use MegolmError::*;
3447    let reason = match error {
3448        EventError(_) => UnableToDecryptReason::MalformedEncryptedEvent,
3449        Decode(_) => UnableToDecryptReason::MalformedEncryptedEvent,
3450        MissingRoomKey(maybe_withheld) => {
3451            UnableToDecryptReason::MissingMegolmSession { withheld_code: maybe_withheld }
3452        }
3453        Decryption(DecryptionError::UnknownMessageIndex(_, _)) => {
3454            UnableToDecryptReason::UnknownMegolmMessageIndex
3455        }
3456        Decryption(_) => UnableToDecryptReason::MegolmDecryptionFailure,
3457        JsonError(_) => UnableToDecryptReason::PayloadDeserializationFailure,
3458        MismatchedIdentityKeys(_) => UnableToDecryptReason::MismatchedIdentityKeys,
3459        SenderIdentityNotTrusted(level) => UnableToDecryptReason::SenderIdentityNotTrusted(level),
3460        #[cfg(feature = "experimental-encrypted-state-events")]
3461        StateKeyVerificationFailed => UnableToDecryptReason::StateKeyVerificationFailed,
3462
3463        // Pass through crypto store errors, which indicate a problem with our
3464        // application, rather than a UTD.
3465        Store(error) => Err(error)?,
3466    };
3467
3468    let session_id = raw_event.deserialize().ok().and_then(|ev| match ev.content.scheme {
3469        RoomEventEncryptionScheme::MegolmV1AesSha2(s) => Some(s.session_id),
3470        #[cfg(feature = "experimental-algorithms")]
3471        RoomEventEncryptionScheme::MegolmV2AesSha2(s) => Some(s.session_id),
3472        RoomEventEncryptionScheme::Unknown(_) => None,
3473    });
3474
3475    Ok(UnableToDecryptInfo { session_id, reason })
3476}
3477
3478/// An error that can occur during [`OlmMachine::decrypt_to_device_event`]:
3479///
3480/// - because decryption failed, or
3481/// - because the sender device was not verified when we are in strict "exclude
3482///   insecure devices" mode, or
3483///
3484/// - because the sender device was a dehydrated device, which should never send
3485///   any to-device messages.
3486#[derive(Debug, thiserror::Error)]
3487pub(crate) enum DecryptToDeviceError {
3488    #[error("An Olm error occurred meaning we failed to decrypt the event")]
3489    OlmError(#[from] OlmError),
3490
3491    #[error("The event was sent from a dehydrated device")]
3492    FromDehydratedDevice,
3493}
3494
3495impl From<CryptoStoreError> for DecryptToDeviceError {
3496    fn from(value: CryptoStoreError) -> Self {
3497        Self::OlmError(value.into())
3498    }
3499}
3500
3501#[cfg(test)]
3502impl From<DecryptToDeviceError> for OlmError {
3503    /// Unwrap the `OlmError` inside this error, or panic if this does not
3504    /// contain an `OlmError`.
3505    fn from(value: DecryptToDeviceError) -> Self {
3506        match value {
3507            DecryptToDeviceError::OlmError(olm_error) => olm_error,
3508            DecryptToDeviceError::FromDehydratedDevice => {
3509                panic!("Expected an OlmError but found FromDehydratedDevice")
3510            }
3511        }
3512    }
3513}
3514
3515#[cfg(test)]
3516pub(crate) mod test_helpers;
3517
3518#[cfg(test)]
3519pub(crate) mod tests;