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