matrix_sdk_crypto/machine/
mod.rs

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