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,
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            algorithm_info,
1140            verification_state: VerificationState::Verified,
1141        }
1142    }
1143
1144    /// Encrypt a state event for the given room.
1145    ///
1146    /// # Arguments
1147    ///
1148    /// * `room_id` - The id of the room for which the event should be
1149    ///   encrypted.
1150    ///
1151    /// * `content` - The plaintext content of the event that should be
1152    ///   encrypted.
1153    ///
1154    /// * `state_key` - The associated state key of the event.
1155    #[cfg(feature = "experimental-encrypted-state-events")]
1156    pub async fn encrypt_state_event<C, K>(
1157        &self,
1158        room_id: &RoomId,
1159        content: C,
1160        state_key: K,
1161    ) -> MegolmResult<Raw<RoomEncryptedEventContent>>
1162    where
1163        C: StateEventContent,
1164        C::StateKey: Borrow<K>,
1165        K: AsRef<str>,
1166    {
1167        let event_type = content.event_type().to_string();
1168        let content = Raw::new(&content)?.cast_unchecked();
1169        self.encrypt_state_event_raw(room_id, &event_type, state_key.as_ref(), &content).await
1170    }
1171
1172    /// Encrypt a state event for the given state event using its raw JSON
1173    /// content and state key.
1174    ///
1175    /// This method is equivalent to [`OlmMachine::encrypt_state_event`]
1176    /// method but operates on an arbitrary JSON value instead of strongly-typed
1177    /// event content struct.
1178    ///
1179    /// # Arguments
1180    ///
1181    /// * `room_id` - The id of the room for which the message should be
1182    ///   encrypted.
1183    ///
1184    /// * `event_type` - The type of the event.
1185    ///
1186    /// * `state_key` - The associated state key of the event.
1187    ///
1188    /// * `content` - The plaintext content of the event that should be
1189    ///   encrypted as a raw JSON value.
1190    #[cfg(feature = "experimental-encrypted-state-events")]
1191    pub async fn encrypt_state_event_raw(
1192        &self,
1193        room_id: &RoomId,
1194        event_type: &str,
1195        state_key: &str,
1196        content: &Raw<AnyStateEventContent>,
1197    ) -> MegolmResult<Raw<RoomEncryptedEventContent>> {
1198        self.inner
1199            .group_session_manager
1200            .encrypt_state(room_id, event_type, state_key, content)
1201            .await
1202    }
1203
1204    /// Forces the currently active room key, which is used to encrypt messages,
1205    /// to be rotated.
1206    ///
1207    /// A new room key will be crated and shared with all the room members the
1208    /// next time a message will be sent. You don't have to call this method,
1209    /// room keys will be rotated automatically when necessary. This method is
1210    /// still useful for debugging purposes.
1211    ///
1212    /// Returns true if a session was invalidated, false if there was no session
1213    /// to invalidate.
1214    pub async fn discard_room_key(&self, room_id: &RoomId) -> StoreResult<bool> {
1215        self.inner.group_session_manager.invalidate_group_session(room_id).await
1216    }
1217
1218    /// Get to-device requests to share a room key with users in a room.
1219    ///
1220    /// # Arguments
1221    ///
1222    /// `room_id` - The room id of the room where the room key will be
1223    /// used.
1224    ///
1225    /// `users` - The list of users that should receive the room key.
1226    ///
1227    /// `settings` - Encryption settings that affect when are room keys rotated
1228    /// and who are they shared with.
1229    ///
1230    /// # Returns
1231    ///
1232    /// List of the to-device requests that need to be sent out to the server
1233    /// and the responses need to be passed back to the state machine with
1234    /// [`mark_request_as_sent`], using the to-device `txn_id` as `request_id`.
1235    ///
1236    /// [`mark_request_as_sent`]: #method.mark_request_as_sent
1237    pub async fn share_room_key(
1238        &self,
1239        room_id: &RoomId,
1240        users: impl Iterator<Item = &UserId>,
1241        encryption_settings: impl Into<EncryptionSettings>,
1242    ) -> OlmResult<Vec<Arc<ToDeviceRequest>>> {
1243        self.inner.group_session_manager.share_room_key(room_id, users, encryption_settings).await
1244    }
1245
1246    /// Encrypts the given content using Olm for each of the given devices.
1247    ///
1248    /// The 1-to-1 session must be established prior to this
1249    /// call by using the [`OlmMachine::get_missing_sessions`] method or the
1250    /// encryption will fail.
1251    ///
1252    /// The caller is responsible for sending the encrypted
1253    /// event to the target device, and should do it ASAP to avoid out-of-order
1254    /// messages.
1255    ///
1256    /// # Returns
1257    /// A list of `ToDeviceRequest` to send out the event, and the list of
1258    /// devices where encryption did not succeed (device excluded or no olm)
1259    #[cfg(feature = "experimental-send-custom-to-device")]
1260    pub async fn encrypt_content_for_devices(
1261        &self,
1262        devices: Vec<DeviceData>,
1263        event_type: &str,
1264        content: &Value,
1265        share_strategy: CollectStrategy,
1266    ) -> OlmResult<(Vec<ToDeviceRequest>, Vec<(DeviceData, WithheldCode)>)> {
1267        let mut changes = Changes::default();
1268
1269        let (allowed_devices, mut blocked_devices) =
1270            split_devices_for_share_strategy(&self.inner.store, devices, share_strategy).await?;
1271
1272        let result = self
1273            .inner
1274            .group_session_manager
1275            .encrypt_content_for_devices(allowed_devices, event_type, content.clone(), &mut changes)
1276            .await;
1277
1278        // Persist any changes we might have collected.
1279        if !changes.is_empty() {
1280            let session_count = changes.sessions.len();
1281
1282            self.inner.store.save_changes(changes).await?;
1283
1284            trace!(
1285                session_count = session_count,
1286                "Stored the changed sessions after encrypting a custom to-device event"
1287            );
1288        }
1289
1290        result.map(|(to_device_requests, mut withheld)| {
1291            withheld.append(&mut blocked_devices);
1292            (to_device_requests, withheld)
1293        })
1294    }
1295    /// Collect the devices belonging to the given user, and send the details of
1296    /// a room key bundle to those devices.
1297    ///
1298    /// Returns a list of to-device requests which must be sent.
1299    pub async fn share_room_key_bundle_data(
1300        &self,
1301        user_id: &UserId,
1302        collect_strategy: &CollectStrategy,
1303        bundle_data: RoomKeyBundleContent,
1304    ) -> OlmResult<Vec<ToDeviceRequest>> {
1305        self.inner
1306            .group_session_manager
1307            .share_room_key_bundle_data(user_id, collect_strategy, bundle_data)
1308            .await
1309    }
1310
1311    /// Receive an unencrypted verification event.
1312    ///
1313    /// This method can be used to pass verification events that are happening
1314    /// in unencrypted rooms to the `OlmMachine`.
1315    ///
1316    /// **Note**: This does not need to be called for encrypted events since
1317    /// those will get passed to the `OlmMachine` during decryption.
1318    #[deprecated(note = "Use OlmMachine::receive_verification_event instead", since = "0.7.0")]
1319    pub async fn receive_unencrypted_verification_event(
1320        &self,
1321        event: &AnyMessageLikeEvent,
1322    ) -> StoreResult<()> {
1323        self.inner.verification_machine.receive_any_event(event).await
1324    }
1325
1326    /// Receive a verification event.
1327    ///
1328    /// The event should be in the decrypted form.
1329    ///
1330    /// **Note**: If the supplied event is an `m.room.message` event with
1331    /// `msgtype: m.key.verification.request`, then the device information for
1332    /// the sending user must be up-to-date before calling this method
1333    /// (otherwise, the request will be ignored). It is hard to guarantee this
1334    /// is the case, but you can maximize your chances by explicitly making a
1335    /// request for this user's device info by calling
1336    /// [`OlmMachine::query_keys_for_users`], sending the request, and
1337    /// processing the response with [`OlmMachine::mark_request_as_sent`].
1338    pub async fn receive_verification_event(&self, event: &AnyMessageLikeEvent) -> StoreResult<()> {
1339        self.inner.verification_machine.receive_any_event(event).await
1340    }
1341
1342    /// Receive and properly handle a decrypted to-device event.
1343    ///
1344    /// # Arguments
1345    ///
1346    /// * `decrypted` - The decrypted event and some associated metadata.
1347    #[instrument(
1348        skip_all,
1349        fields(
1350            sender_key = ?decrypted.result.sender_key,
1351            event_type = decrypted.result.event.event_type(),
1352        ),
1353    )]
1354    async fn handle_decrypted_to_device_event(
1355        &self,
1356        cache: &StoreCache,
1357        decrypted: &mut OlmDecryptionInfo,
1358        changes: &mut Changes,
1359    ) -> OlmResult<()> {
1360        debug!(
1361            sender_device_keys =
1362                ?decrypted.result.event.sender_device_keys().map(|k| (k.curve25519_key(), k.ed25519_key())).unwrap_or((None, None)),
1363            "Received a decrypted to-device event",
1364        );
1365
1366        match &*decrypted.result.event {
1367            AnyDecryptedOlmEvent::RoomKey(e) => {
1368                let session = self.add_room_key(decrypted.result.sender_key, e).await?;
1369                decrypted.inbound_group_session = session;
1370            }
1371            AnyDecryptedOlmEvent::ForwardedRoomKey(e) => {
1372                let session = self
1373                    .inner
1374                    .key_request_machine
1375                    .receive_forwarded_room_key(decrypted.result.sender_key, e)
1376                    .await?;
1377                decrypted.inbound_group_session = session;
1378            }
1379            AnyDecryptedOlmEvent::SecretSend(e) => {
1380                let name = self
1381                    .inner
1382                    .key_request_machine
1383                    .receive_secret_event(cache, decrypted.result.sender_key, e, changes)
1384                    .await?;
1385
1386                // Set the secret name so other consumers of the event know
1387                // what this event is about.
1388                if let Ok(ToDeviceEvents::SecretSend(mut e)) =
1389                    decrypted.result.raw_event.deserialize_as()
1390                {
1391                    e.content.secret_name = name;
1392                    decrypted.result.raw_event = Raw::from_json(to_raw_value(&e)?);
1393                }
1394            }
1395            AnyDecryptedOlmEvent::Dummy(_) => {
1396                debug!("Received an `m.dummy` event");
1397            }
1398            AnyDecryptedOlmEvent::RoomKeyBundle(e) => {
1399                debug!("Received a room key bundle event {:?}", e);
1400                self.receive_room_key_bundle_data(decrypted.result.sender_key, e, changes).await?;
1401            }
1402            AnyDecryptedOlmEvent::Custom(_) => {
1403                warn!("Received an unexpected encrypted to-device event");
1404            }
1405        }
1406
1407        Ok(())
1408    }
1409
1410    async fn handle_verification_event(&self, event: &ToDeviceEvents) {
1411        if let Err(e) = self.inner.verification_machine.receive_any_event(event).await {
1412            error!("Error handling a verification event: {e:?}");
1413        }
1414    }
1415
1416    /// Mark an outgoing to-device requests as sent.
1417    async fn mark_to_device_request_as_sent(&self, request_id: &TransactionId) -> StoreResult<()> {
1418        self.inner.verification_machine.mark_request_as_sent(request_id);
1419        self.inner.key_request_machine.mark_outgoing_request_as_sent(request_id).await?;
1420        self.inner.group_session_manager.mark_request_as_sent(request_id).await?;
1421        self.inner.session_manager.mark_outgoing_request_as_sent(request_id);
1422        Ok(())
1423    }
1424
1425    /// Get a verification object for the given user id with the given flow id.
1426    pub fn get_verification(&self, user_id: &UserId, flow_id: &str) -> Option<Verification> {
1427        self.inner.verification_machine.get_verification(user_id, flow_id)
1428    }
1429
1430    /// Get a verification request object with the given flow id.
1431    pub fn get_verification_request(
1432        &self,
1433        user_id: &UserId,
1434        flow_id: impl AsRef<str>,
1435    ) -> Option<VerificationRequest> {
1436        self.inner.verification_machine.get_request(user_id, flow_id)
1437    }
1438
1439    /// Get all the verification requests of a given user.
1440    pub fn get_verification_requests(&self, user_id: &UserId) -> Vec<VerificationRequest> {
1441        self.inner.verification_machine.get_requests(user_id)
1442    }
1443
1444    /// Given a to-device event that has either been decrypted or arrived in
1445    /// plaintext, handle it.
1446    ///
1447    /// Here, we only process events that are allowed to arrive in plaintext.
1448    async fn handle_to_device_event(&self, changes: &mut Changes, event: &ToDeviceEvents) {
1449        use crate::types::events::ToDeviceEvents::*;
1450
1451        match event {
1452            // These are handled here because we accept them either plaintext or
1453            // encrypted.
1454            //
1455            // Note: this list should match the allowed types in
1456            // check_to_device_is_from_verified_device_or_allowed_type
1457            RoomKeyRequest(e) => self.inner.key_request_machine.receive_incoming_key_request(e),
1458            SecretRequest(e) => self.inner.key_request_machine.receive_incoming_secret_request(e),
1459            RoomKeyWithheld(e) => self.add_withheld_info(changes, e),
1460            KeyVerificationAccept(..)
1461            | KeyVerificationCancel(..)
1462            | KeyVerificationKey(..)
1463            | KeyVerificationMac(..)
1464            | KeyVerificationRequest(..)
1465            | KeyVerificationReady(..)
1466            | KeyVerificationDone(..)
1467            | KeyVerificationStart(..) => {
1468                self.handle_verification_event(event).await;
1469            }
1470
1471            // We don't process custom or dummy events at all
1472            Custom(_) | Dummy(_) => {}
1473
1474            // Encrypted events are handled elsewhere
1475            RoomEncrypted(_) => {}
1476
1477            // These are handled in `handle_decrypted_to_device_event` because we
1478            // only accept them if they arrive encrypted.
1479            SecretSend(_) | RoomKey(_) | ForwardedRoomKey(_) => {}
1480        }
1481    }
1482
1483    fn record_message_id(event: &Raw<AnyToDeviceEvent>) {
1484        use serde::Deserialize;
1485
1486        #[derive(Deserialize)]
1487        struct ContentStub<'a> {
1488            #[serde(borrow, rename = "org.matrix.msgid")]
1489            message_id: Option<&'a str>,
1490        }
1491        #[derive(Deserialize)]
1492        struct ToDeviceStub<'a> {
1493            sender: &'a str,
1494            #[serde(rename = "type")]
1495            event_type: &'a str,
1496            #[serde(borrow)]
1497            content: ContentStub<'a>,
1498        }
1499
1500        if let Ok(event) = event.deserialize_as_unchecked::<ToDeviceStub<'_>>() {
1501            Span::current().record("sender", event.sender);
1502            Span::current().record("event_type", event.event_type);
1503            Span::current().record("message_id", event.content.message_id);
1504        }
1505    }
1506
1507    /// Decrypt the supplied to-device event (if needed, and if we can) and
1508    /// handle it.
1509    ///
1510    /// Return the same event, decrypted if possible and needed.
1511    ///
1512    /// If we can identify that this to-device event came from a dehydrated
1513    /// device, this method does not process it, and returns `None`.
1514    #[instrument(skip_all, fields(sender, event_type, message_id))]
1515    async fn receive_to_device_event(
1516        &self,
1517        transaction: &mut StoreTransaction,
1518        changes: &mut Changes,
1519        raw_event: Raw<AnyToDeviceEvent>,
1520        decryption_settings: &DecryptionSettings,
1521    ) -> Option<ProcessedToDeviceEvent> {
1522        Self::record_message_id(&raw_event);
1523
1524        let event: ToDeviceEvents = match raw_event.deserialize_as() {
1525            Ok(e) => e,
1526            Err(e) => {
1527                // Skip invalid events.
1528                warn!("Received an invalid to-device event: {e}");
1529                return Some(ProcessedToDeviceEvent::Invalid(raw_event));
1530            }
1531        };
1532
1533        debug!("Received a to-device event");
1534
1535        match event {
1536            ToDeviceEvents::RoomEncrypted(e) => {
1537                self.receive_encrypted_to_device_event(
1538                    transaction,
1539                    changes,
1540                    raw_event,
1541                    e,
1542                    decryption_settings,
1543                )
1544                .await
1545            }
1546            e => {
1547                self.handle_to_device_event(changes, &e).await;
1548                Some(ProcessedToDeviceEvent::PlainText(raw_event))
1549            }
1550        }
1551    }
1552
1553    /// Decrypt the supplied encrypted to-device event (if we can) and handle
1554    /// it.
1555    ///
1556    /// Return the same event, decrypted if possible.
1557    ///
1558    /// If we are in strict "exclude insecure devices" mode and the sender
1559    /// device is not verified, and the decrypted event type is not on the
1560    /// allow list, or if this event comes from a dehydrated device, this method
1561    /// does not process it, and returns `None`.
1562    ///
1563    /// (The allow list of types that are processed even if the sender is
1564    /// unverified is: `m.room_key`, `m.room_key.withheld`,
1565    /// `m.room_key_request`, `m.secret.request` and `m.key.verification.*`.)
1566    async fn receive_encrypted_to_device_event(
1567        &self,
1568        transaction: &mut StoreTransaction,
1569        changes: &mut Changes,
1570        mut raw_event: Raw<AnyToDeviceEvent>,
1571        e: ToDeviceEvent<ToDeviceEncryptedEventContent>,
1572        decryption_settings: &DecryptionSettings,
1573    ) -> Option<ProcessedToDeviceEvent> {
1574        let decrypted = match self
1575            .decrypt_to_device_event(transaction, &e, changes, decryption_settings)
1576            .await
1577        {
1578            Ok(decrypted) => decrypted,
1579            Err(DecryptToDeviceError::OlmError(err)) => {
1580                let reason = if let OlmError::UnverifiedSenderDevice = &err {
1581                    ToDeviceUnableToDecryptReason::UnverifiedSenderDevice
1582                } else {
1583                    ToDeviceUnableToDecryptReason::DecryptionFailure
1584                };
1585
1586                if let OlmError::SessionWedged(sender, curve_key) = err
1587                    && let Err(e) =
1588                        self.inner.session_manager.mark_device_as_wedged(&sender, curve_key).await
1589                {
1590                    error!(
1591                        error = ?e,
1592                        "Couldn't mark device to be unwedged",
1593                    );
1594                }
1595
1596                return Some(ProcessedToDeviceEvent::UnableToDecrypt {
1597                    encrypted_event: raw_event,
1598                    utd_info: ToDeviceUnableToDecryptInfo { reason },
1599                });
1600            }
1601            Err(DecryptToDeviceError::FromDehydratedDevice) => return None,
1602        };
1603
1604        // New sessions modify the account so we need to save that
1605        // one as well.
1606        match decrypted.session {
1607            SessionType::New(s) | SessionType::Existing(s) => {
1608                changes.sessions.push(s);
1609            }
1610        }
1611
1612        changes.message_hashes.push(decrypted.message_hash);
1613
1614        if let Some(group_session) = decrypted.inbound_group_session {
1615            changes.inbound_group_sessions.push(group_session);
1616        }
1617
1618        match decrypted.result.raw_event.deserialize_as() {
1619            Ok(event) => {
1620                self.handle_to_device_event(changes, &event).await;
1621
1622                raw_event = event
1623                    .serialize_zeroized()
1624                    .expect("Zeroizing and reserializing our events should always work")
1625                    .cast();
1626            }
1627            Err(e) => {
1628                warn!("Received an invalid encrypted to-device event: {e}");
1629                raw_event = decrypted.result.raw_event;
1630            }
1631        }
1632
1633        Some(ProcessedToDeviceEvent::Decrypted {
1634            raw: raw_event,
1635            encryption_info: decrypted.result.encryption_info,
1636        })
1637    }
1638
1639    /// Return an error if the supplied to-device event was sent from a
1640    /// dehydrated device.
1641    async fn check_to_device_event_is_not_from_dehydrated_device(
1642        &self,
1643        decrypted: &OlmDecryptionInfo,
1644        sender_user_id: &UserId,
1645    ) -> Result<(), DecryptToDeviceError> {
1646        if self.to_device_event_is_from_dehydrated_device(decrypted, sender_user_id).await? {
1647            warn!(
1648                sender = ?sender_user_id,
1649                session = ?decrypted.session,
1650                "Received a to-device event from a dehydrated device. This is unexpected: ignoring event"
1651            );
1652            Err(DecryptToDeviceError::FromDehydratedDevice)
1653        } else {
1654            Ok(())
1655        }
1656    }
1657
1658    /// Decide whether a decrypted to-device event was sent from a dehydrated
1659    /// device.
1660    ///
1661    /// This accepts an [`OlmDecryptionInfo`] because it deals with a decrypted
1662    /// event.
1663    async fn to_device_event_is_from_dehydrated_device(
1664        &self,
1665        decrypted: &OlmDecryptionInfo,
1666        sender_user_id: &UserId,
1667    ) -> OlmResult<bool> {
1668        // Does the to-device message include device info?
1669        if let Some(device_keys) = decrypted.result.event.sender_device_keys() {
1670            // There is no need to check whether the device keys are signed correctly - any
1671            // to-device message that claims to be from a dehydrated device is weird, so we
1672            // will drop it.
1673
1674            // Does the included device info say the device is dehydrated?
1675            if device_keys.dehydrated.unwrap_or(false) {
1676                return Ok(true);
1677            }
1678            // If not, fall through and check our existing list of devices
1679            // below, just in case the sender is sending us incorrect
1680            // information embedded in the to-device message, but we know
1681            // better.
1682        }
1683
1684        // Do we already know about this device?
1685        Ok(self
1686            .store()
1687            .get_device_from_curve_key(sender_user_id, decrypted.result.sender_key)
1688            .await?
1689            .is_some_and(|d| d.is_dehydrated()))
1690    }
1691
1692    /// Handle a to-device and one-time key counts from a sync response.
1693    ///
1694    /// This will decrypt and handle to-device events returning the decrypted
1695    /// versions of them.
1696    ///
1697    /// To decrypt an event from the room timeline, call [`decrypt_room_event`].
1698    ///
1699    /// # Arguments
1700    ///
1701    /// * `sync_changes` - an [`EncryptionSyncChanges`] value, constructed from
1702    ///   a sync response.
1703    ///
1704    /// [`decrypt_room_event`]: #method.decrypt_room_event
1705    ///
1706    /// # Returns
1707    ///
1708    /// A tuple of (decrypted to-device events, updated room keys).
1709    #[instrument(skip_all)]
1710    pub async fn receive_sync_changes(
1711        &self,
1712        sync_changes: EncryptionSyncChanges<'_>,
1713        decryption_settings: &DecryptionSettings,
1714    ) -> OlmResult<(Vec<ProcessedToDeviceEvent>, Vec<RoomKeyInfo>)> {
1715        let mut store_transaction = self.inner.store.transaction().await;
1716
1717        let (events, changes) = self
1718            .preprocess_sync_changes(&mut store_transaction, sync_changes, decryption_settings)
1719            .await?;
1720
1721        // Technically save_changes also does the same work, so if it's slow we could
1722        // refactor this to do it only once.
1723        let room_key_updates: Vec<_> =
1724            changes.inbound_group_sessions.iter().map(RoomKeyInfo::from).collect();
1725
1726        self.store().save_changes(changes).await?;
1727        store_transaction.commit().await?;
1728
1729        Ok((events, room_key_updates))
1730    }
1731
1732    /// Initial processing of the changes specified within a sync response.
1733    ///
1734    /// Returns the to-device events (decrypted where needed and where possible)
1735    /// and the processed set of changes.
1736    ///
1737    /// If any of the to-device events in the supplied changes were sent from
1738    /// dehydrated devices, these are not processed, and are omitted from
1739    /// the returned list, as per MSC3814.
1740    ///
1741    /// If we are in strict "exclude insecure devices" mode and the sender
1742    /// device of any event is not verified, and the decrypted event type is not
1743    /// on the allow list, these events are not processed and are omitted from
1744    /// the returned list.
1745    ///
1746    /// (The allow list of types that are processed even if the sender is
1747    /// unverified is: `m.room_key`, `m.room_key.withheld`,
1748    /// `m.room_key_request`, `m.secret.request` and `m.key.verification.*`.)
1749    pub(crate) async fn preprocess_sync_changes(
1750        &self,
1751        transaction: &mut StoreTransaction,
1752        sync_changes: EncryptionSyncChanges<'_>,
1753        decryption_settings: &DecryptionSettings,
1754    ) -> OlmResult<(Vec<ProcessedToDeviceEvent>, Changes)> {
1755        // Remove verification objects that have expired or are done.
1756        let mut events: Vec<ProcessedToDeviceEvent> = self
1757            .inner
1758            .verification_machine
1759            .garbage_collect()
1760            .iter()
1761            // These are `fake` to device events just serving as local echo
1762            // in order that our own client can react quickly to cancelled transaction.
1763            // Just use PlainText for that.
1764            .map(|e| ProcessedToDeviceEvent::PlainText(e.clone()))
1765            .collect();
1766        // The account is automatically saved by the store transaction created by the
1767        // caller.
1768        let mut changes = Default::default();
1769
1770        {
1771            let account = transaction.account().await?;
1772            account.update_key_counts(
1773                sync_changes.one_time_keys_counts,
1774                sync_changes.unused_fallback_keys,
1775            )
1776        }
1777
1778        if let Err(e) = self
1779            .inner
1780            .identity_manager
1781            .receive_device_changes(
1782                transaction.cache(),
1783                sync_changes.changed_devices.changed.iter().map(|u| u.as_ref()),
1784            )
1785            .await
1786        {
1787            error!(error = ?e, "Error marking a tracked user as changed");
1788        }
1789
1790        for raw_event in sync_changes.to_device_events {
1791            let processed_event = Box::pin(self.receive_to_device_event(
1792                transaction,
1793                &mut changes,
1794                raw_event,
1795                decryption_settings,
1796            ))
1797            .await;
1798
1799            if let Some(processed_event) = processed_event {
1800                events.push(processed_event);
1801            }
1802        }
1803
1804        let changed_sessions = self
1805            .inner
1806            .key_request_machine
1807            .collect_incoming_key_requests(transaction.cache())
1808            .await?;
1809
1810        changes.sessions.extend(changed_sessions);
1811        changes.next_batch_token = sync_changes.next_batch_token;
1812
1813        Ok((events, changes))
1814    }
1815
1816    /// Request a room key from our devices.
1817    ///
1818    /// This method will return a request cancellation and a new key request if
1819    /// the key was already requested, otherwise it will return just the key
1820    /// request.
1821    ///
1822    /// The request cancellation *must* be sent out before the request is sent
1823    /// out, otherwise devices will ignore the key request.
1824    ///
1825    /// # Arguments
1826    ///
1827    /// * `room_id` - The id of the room where the key is used in.
1828    ///
1829    /// * `sender_key` - The curve25519 key of the sender that owns the key.
1830    ///
1831    /// * `session_id` - The id that uniquely identifies the session.
1832    pub async fn request_room_key(
1833        &self,
1834        event: &Raw<EncryptedEvent>,
1835        room_id: &RoomId,
1836    ) -> MegolmResult<(Option<OutgoingRequest>, OutgoingRequest)> {
1837        let event = event.deserialize()?;
1838        self.inner.key_request_machine.request_key(room_id, &event).await
1839    }
1840
1841    /// Find whether an event decrypted via the supplied session is verified,
1842    /// and provide explanation of what is missing/wrong if not.
1843    ///
1844    /// Stores the updated [`SenderData`] for the session in the store
1845    /// if we find an updated value for it.
1846    ///
1847    /// # Arguments
1848    ///
1849    /// * `session` - The inbound Megolm session that was used to decrypt the
1850    ///   event.
1851    /// * `sender` - The `sender` of that event (as claimed by the envelope of
1852    ///   the event).
1853    async fn get_room_event_verification_state(
1854        &self,
1855        session: &InboundGroupSession,
1856        sender: &UserId,
1857    ) -> MegolmResult<(VerificationState, Option<OwnedDeviceId>)> {
1858        let sender_data = self.get_or_update_sender_data(session, sender).await?;
1859
1860        // If the user ID in the sender data doesn't match that in the event envelope,
1861        // this event is not from who it appears to be from.
1862        //
1863        // If `sender_data.user_id()` returns `None`, that means we don't have any
1864        // information about the owner of the session (i.e. we have
1865        // `SenderData::UnknownDevice`); in that case we fall through to the
1866        // logic in `sender_data_to_verification_state` which will pick an appropriate
1867        // `DeviceLinkProblem` for `VerificationLevel::None`.
1868        let (verification_state, device_id) = match sender_data.user_id() {
1869            Some(i) if i != sender => {
1870                (VerificationState::Unverified(VerificationLevel::MismatchedSender), None)
1871            }
1872
1873            Some(_) | None => {
1874                sender_data_to_verification_state(sender_data, session.has_been_imported())
1875            }
1876        };
1877
1878        Ok((verification_state, device_id))
1879    }
1880
1881    /// Get an up-to-date [`SenderData`] for the given session, suitable for
1882    /// determining if messages decrypted using that session are verified.
1883    ///
1884    /// Checks both the stored verification state of the session and a
1885    /// recalculated verification state based on our current knowledge, and
1886    /// returns the more trusted of the two.
1887    ///
1888    /// Stores the updated [`SenderData`] for the session in the store
1889    /// if we find an updated value for it.
1890    ///
1891    /// # Arguments
1892    ///
1893    /// * `session` - The Megolm session that was used to decrypt the event.
1894    /// * `sender` - The claimed sender of that event.
1895    async fn get_or_update_sender_data(
1896        &self,
1897        session: &InboundGroupSession,
1898        sender: &UserId,
1899    ) -> MegolmResult<SenderData> {
1900        let sender_data = if session.sender_data.should_recalculate() {
1901            // The session is not sure of the sender yet. Try to find a matching device
1902            // belonging to the claimed sender of the recently-received event.
1903            //
1904            // It's worth noting that this could in theory result in unintuitive changes,
1905            // like a session which initially appears to belong to Alice turning into a
1906            // session which belongs to Bob [1]. This could mean that a session initially
1907            // successfully decrypts events from Alice, but then stops decrypting those same
1908            // events once we get an update.
1909            //
1910            // That's ok though: if we get good evidence that the session belongs to Bob,
1911            // it's correct to update the session even if we previously had weak
1912            // evidence it belonged to Alice.
1913            //
1914            // [1] For example: maybe Alice and Bob both publish devices with the *same*
1915            // keys (presumably because they are colluding). Initially we think
1916            // the session belongs to Alice, but then we do a device lookup for
1917            // Bob, we find a matching device with a cross-signature, so prefer
1918            // that.
1919            let calculated_sender_data = SenderDataFinder::find_using_curve_key(
1920                self.store(),
1921                session.sender_key(),
1922                sender,
1923                session,
1924            )
1925            .await?;
1926
1927            // Is the newly-calculated sender data more trusted?
1928            if calculated_sender_data.compare_trust_level(&session.sender_data).is_gt() {
1929                // Yes - save it to the store
1930                let mut new_session = session.clone();
1931                new_session.sender_data = calculated_sender_data.clone();
1932                self.store().save_inbound_group_sessions(&[new_session]).await?;
1933
1934                // and use it now.
1935                calculated_sender_data
1936            } else {
1937                // No - use the existing data.
1938                session.sender_data.clone()
1939            }
1940        } else {
1941            session.sender_data.clone()
1942        };
1943
1944        Ok(sender_data)
1945    }
1946
1947    /// Request missing local secrets from our devices (cross signing private
1948    /// keys, megolm backup). This will ask the sdk to create outgoing
1949    /// request to get the missing secrets.
1950    ///
1951    /// The requests will be processed as soon as `outgoing_requests()` is
1952    /// called to process them.
1953    ///
1954    /// # Returns
1955    ///
1956    /// A bool result saying if actual secrets were missing and have been
1957    /// requested
1958    ///
1959    /// # Examples
1960    //
1961    /// ```
1962    /// # async {
1963    /// # use matrix_sdk_crypto::OlmMachine;
1964    /// # let machine: OlmMachine = unimplemented!();
1965    /// if machine.query_missing_secrets_from_other_sessions().await.unwrap() {
1966    ///     let to_send = machine.outgoing_requests().await.unwrap();
1967    ///     // send the to device requests
1968    /// };
1969    /// # anyhow::Ok(()) };
1970    /// ```
1971    pub async fn query_missing_secrets_from_other_sessions(&self) -> StoreResult<bool> {
1972        let identity = self.inner.user_identity.lock().await;
1973        let mut secrets = identity.get_missing_secrets().await;
1974
1975        if self.store().load_backup_keys().await?.decryption_key.is_none() {
1976            secrets.push(SecretName::RecoveryKey);
1977        }
1978
1979        if secrets.is_empty() {
1980            debug!("No missing requests to query");
1981            return Ok(false);
1982        }
1983
1984        let secret_requests = GossipMachine::request_missing_secrets(self.user_id(), secrets);
1985
1986        // Check if there are already in-flight requests for these secrets?
1987        let unsent_request = self.store().get_unsent_secret_requests().await?;
1988        let not_yet_requested = secret_requests
1989            .into_iter()
1990            .filter(|request| !unsent_request.iter().any(|unsent| unsent.info == request.info))
1991            .collect_vec();
1992
1993        if not_yet_requested.is_empty() {
1994            debug!("The missing secrets have already been requested");
1995            Ok(false)
1996        } else {
1997            debug!("Requesting missing secrets");
1998
1999            let changes = Changes { key_requests: not_yet_requested, ..Default::default() };
2000
2001            self.store().save_changes(changes).await?;
2002            Ok(true)
2003        }
2004    }
2005
2006    /// Get some metadata pertaining to a given group session.
2007    ///
2008    /// This includes the session owner's Matrix user ID, their device ID, info
2009    /// regarding the cryptographic algorithm and whether the session, and by
2010    /// extension the events decrypted by the session, are trusted.
2011    async fn get_encryption_info(
2012        &self,
2013        session: &InboundGroupSession,
2014        sender: &UserId,
2015    ) -> MegolmResult<Arc<EncryptionInfo>> {
2016        let (verification_state, device_id) =
2017            self.get_room_event_verification_state(session, sender).await?;
2018
2019        let sender = sender.to_owned();
2020
2021        Ok(Arc::new(EncryptionInfo {
2022            sender,
2023            sender_device: device_id,
2024            algorithm_info: AlgorithmInfo::MegolmV1AesSha2 {
2025                curve25519_key: session.sender_key().to_base64(),
2026                sender_claimed_keys: session
2027                    .signing_keys()
2028                    .iter()
2029                    .map(|(k, v)| (k.to_owned(), v.to_base64()))
2030                    .collect(),
2031                session_id: Some(session.session_id().to_owned()),
2032            },
2033            verification_state,
2034        }))
2035    }
2036
2037    async fn decrypt_megolm_events(
2038        &self,
2039        room_id: &RoomId,
2040        event: &EncryptedEvent,
2041        content: &SupportedEventEncryptionSchemes<'_>,
2042        decryption_settings: &DecryptionSettings,
2043    ) -> MegolmResult<(JsonObject, Arc<EncryptionInfo>)> {
2044        let session =
2045            self.get_inbound_group_session_or_error(room_id, content.session_id()).await?;
2046
2047        // This function is only ever called by decrypt_room_event, so
2048        // room_id, sender, algorithm and session_id are recorded already
2049        //
2050        // While we already record the sender key in some cases from the event, the
2051        // sender key in the event is deprecated, so let's record it now.
2052        Span::current().record("sender_key", debug(session.sender_key()));
2053
2054        let result = session.decrypt(event).await;
2055        match result {
2056            Ok((decrypted_event, _)) => {
2057                let encryption_info = self.get_encryption_info(&session, &event.sender).await?;
2058
2059                self.check_sender_trust_requirement(
2060                    &session,
2061                    &encryption_info,
2062                    &decryption_settings.sender_device_trust_requirement,
2063                )?;
2064
2065                Ok((decrypted_event, encryption_info))
2066            }
2067            Err(error) => Err(
2068                if let MegolmError::Decryption(DecryptionError::UnknownMessageIndex(_, _)) = error {
2069                    let withheld_code = self
2070                        .inner
2071                        .store
2072                        .get_withheld_info(room_id, content.session_id())
2073                        .await?
2074                        .map(|e| e.content.withheld_code());
2075
2076                    if withheld_code.is_some() {
2077                        // Partially withheld, report with a withheld code if we have one.
2078                        MegolmError::MissingRoomKey(withheld_code)
2079                    } else {
2080                        error
2081                    }
2082                } else {
2083                    error
2084                },
2085            ),
2086        }
2087    }
2088
2089    /// Check that a Megolm event satisfies the sender trust
2090    /// requirement from the decryption settings.
2091    ///
2092    /// If the requirement is not satisfied, returns
2093    /// [`MegolmError::SenderIdentityNotTrusted`].
2094    fn check_sender_trust_requirement(
2095        &self,
2096        session: &InboundGroupSession,
2097        encryption_info: &EncryptionInfo,
2098        trust_requirement: &TrustRequirement,
2099    ) -> MegolmResult<()> {
2100        trace!(
2101            verification_state = ?encryption_info.verification_state,
2102            ?trust_requirement, "check_sender_trust_requirement",
2103        );
2104
2105        // VerificationState::Verified is acceptable for all TrustRequirement levels, so
2106        // let's get that out of the way
2107        let verification_level = match &encryption_info.verification_state {
2108            VerificationState::Verified => return Ok(()),
2109            VerificationState::Unverified(verification_level) => verification_level,
2110        };
2111
2112        let ok = match trust_requirement {
2113            TrustRequirement::Untrusted => true,
2114
2115            TrustRequirement::CrossSignedOrLegacy => {
2116                // `VerificationLevel::UnsignedDevice` and `VerificationLevel::None` correspond
2117                // to `SenderData::DeviceInfo` and `SenderData::UnknownDevice`
2118                // respectively, and those cases may be acceptable if the reason
2119                // for the lack of data is that the sessions were established
2120                // before we started collecting SenderData.
2121                let legacy_session = match session.sender_data {
2122                    SenderData::DeviceInfo { legacy_session, .. } => legacy_session,
2123                    SenderData::UnknownDevice { legacy_session, .. } => legacy_session,
2124                    _ => false,
2125                };
2126
2127                // In the CrossSignedOrLegacy case the following rules apply:
2128                //
2129                // 1. Identities we have not yet verified can be decrypted regardless of the
2130                //    legacy state of the session.
2131                // 2. Devices that aren't signed by the owning identity of the device can only
2132                //    be decrypted if it's a legacy session.
2133                // 3. If we have no information about the device, we should only decrypt if it's
2134                //    a legacy session.
2135                // 4. Anything else, should throw an error.
2136                match (verification_level, legacy_session) {
2137                    // Case 1
2138                    (VerificationLevel::UnverifiedIdentity, _) => true,
2139
2140                    // Case 2
2141                    (VerificationLevel::UnsignedDevice, true) => true,
2142
2143                    // Case 3
2144                    (VerificationLevel::None(_), true) => true,
2145
2146                    // Case 4
2147                    (VerificationLevel::VerificationViolation, _)
2148                    | (VerificationLevel::MismatchedSender, _)
2149                    | (VerificationLevel::UnsignedDevice, false)
2150                    | (VerificationLevel::None(_), false) => false,
2151                }
2152            }
2153
2154            // If cross-signing of identities is required, the only acceptable unverified case
2155            // is when the identity is signed but not yet verified by us.
2156            TrustRequirement::CrossSigned => match verification_level {
2157                VerificationLevel::UnverifiedIdentity => true,
2158
2159                VerificationLevel::VerificationViolation
2160                | VerificationLevel::MismatchedSender
2161                | VerificationLevel::UnsignedDevice
2162                | VerificationLevel::None(_) => false,
2163            },
2164        };
2165
2166        if ok {
2167            Ok(())
2168        } else {
2169            Err(MegolmError::SenderIdentityNotTrusted(verification_level.clone()))
2170        }
2171    }
2172
2173    /// Attempt to retrieve an inbound group session from the store.
2174    ///
2175    /// If the session is not found, checks for withheld reports, and returns a
2176    /// [`MegolmError::MissingRoomKey`] error.
2177    async fn get_inbound_group_session_or_error(
2178        &self,
2179        room_id: &RoomId,
2180        session_id: &str,
2181    ) -> MegolmResult<InboundGroupSession> {
2182        match self.store().get_inbound_group_session(room_id, session_id).await? {
2183            Some(session) => Ok(session),
2184            None => {
2185                let withheld_code = self
2186                    .inner
2187                    .store
2188                    .get_withheld_info(room_id, session_id)
2189                    .await?
2190                    .map(|e| e.content.withheld_code());
2191                Err(MegolmError::MissingRoomKey(withheld_code))
2192            }
2193        }
2194    }
2195
2196    /// Attempt to decrypt an event from a room timeline, returning information
2197    /// on the failure if it fails.
2198    ///
2199    /// # Arguments
2200    ///
2201    /// * `event` - The event that should be decrypted.
2202    ///
2203    /// * `room_id` - The ID of the room where the event was sent to.
2204    ///
2205    /// # Returns
2206    ///
2207    /// The decrypted event, if it was successfully decrypted. Otherwise,
2208    /// information on the failure, unless the failure was due to an
2209    /// internal error, in which case, an `Err` result.
2210    pub async fn try_decrypt_room_event(
2211        &self,
2212        raw_event: &Raw<EncryptedEvent>,
2213        room_id: &RoomId,
2214        decryption_settings: &DecryptionSettings,
2215    ) -> Result<RoomEventDecryptionResult, CryptoStoreError> {
2216        match self.decrypt_room_event_inner(raw_event, room_id, true, decryption_settings).await {
2217            Ok(decrypted) => Ok(RoomEventDecryptionResult::Decrypted(decrypted)),
2218            Err(err) => Ok(RoomEventDecryptionResult::UnableToDecrypt(megolm_error_to_utd_info(
2219                raw_event, err,
2220            )?)),
2221        }
2222    }
2223
2224    /// Decrypt an event from a room timeline.
2225    ///
2226    /// # Arguments
2227    ///
2228    /// * `event` - The event that should be decrypted.
2229    ///
2230    /// * `room_id` - The ID of the room where the event was sent to.
2231    pub async fn decrypt_room_event(
2232        &self,
2233        event: &Raw<EncryptedEvent>,
2234        room_id: &RoomId,
2235        decryption_settings: &DecryptionSettings,
2236    ) -> MegolmResult<DecryptedRoomEvent> {
2237        self.decrypt_room_event_inner(event, room_id, true, decryption_settings).await
2238    }
2239
2240    #[instrument(name = "decrypt_room_event", skip_all, fields(?room_id, event_id, origin_server_ts, sender, algorithm, session_id, message_index, sender_key))]
2241    async fn decrypt_room_event_inner(
2242        &self,
2243        event: &Raw<EncryptedEvent>,
2244        room_id: &RoomId,
2245        decrypt_unsigned: bool,
2246        decryption_settings: &DecryptionSettings,
2247    ) -> MegolmResult<DecryptedRoomEvent> {
2248        let _timer = timer!(tracing::Level::TRACE, "_method");
2249
2250        let event = event.deserialize()?;
2251
2252        Span::current()
2253            .record("sender", debug(&event.sender))
2254            .record("event_id", debug(&event.event_id))
2255            .record(
2256                "origin_server_ts",
2257                timestamp_to_iso8601(event.origin_server_ts)
2258                    .unwrap_or_else(|| "<out of range>".to_owned()),
2259            )
2260            .record("algorithm", debug(event.content.algorithm()));
2261
2262        let content: SupportedEventEncryptionSchemes<'_> = match &event.content.scheme {
2263            RoomEventEncryptionScheme::MegolmV1AesSha2(c) => {
2264                Span::current().record("sender_key", debug(c.sender_key));
2265                c.into()
2266            }
2267            #[cfg(feature = "experimental-algorithms")]
2268            RoomEventEncryptionScheme::MegolmV2AesSha2(c) => c.into(),
2269            RoomEventEncryptionScheme::Unknown(_) => {
2270                warn!("Received an encrypted room event with an unsupported algorithm");
2271                return Err(EventError::UnsupportedAlgorithm.into());
2272            }
2273        };
2274
2275        Span::current().record("session_id", content.session_id());
2276        Span::current().record("message_index", content.message_index());
2277
2278        let result =
2279            self.decrypt_megolm_events(room_id, &event, &content, decryption_settings).await;
2280
2281        if let Err(e) = &result {
2282            #[cfg(feature = "automatic-room-key-forwarding")]
2283            match e {
2284                // Optimisation should we request if we received a withheld code?
2285                // Maybe for some code there is no point
2286                MegolmError::MissingRoomKey(_)
2287                | MegolmError::Decryption(DecryptionError::UnknownMessageIndex(_, _)) => {
2288                    self.inner
2289                        .key_request_machine
2290                        .create_outgoing_key_request(room_id, &event)
2291                        .await?;
2292                }
2293                _ => {}
2294            }
2295
2296            warn!("Failed to decrypt a room event: {e}");
2297        }
2298
2299        let (mut decrypted_event, encryption_info) = result?;
2300
2301        let mut unsigned_encryption_info = None;
2302        if decrypt_unsigned {
2303            // Try to decrypt encrypted unsigned events.
2304            unsigned_encryption_info = self
2305                .decrypt_unsigned_events(&mut decrypted_event, room_id, decryption_settings)
2306                .await;
2307        }
2308
2309        let decrypted_event =
2310            serde_json::from_value::<Raw<AnyTimelineEvent>>(decrypted_event.into())?;
2311
2312        #[cfg(feature = "experimental-encrypted-state-events")]
2313        self.verify_packed_state_key(&event, &decrypted_event)?;
2314
2315        Ok(DecryptedRoomEvent { event: decrypted_event, encryption_info, unsigned_encryption_info })
2316    }
2317
2318    /// If the passed event is a state event, verify its outer packed state key
2319    /// matches the inner state key once unpacked.
2320    ///
2321    /// * `original` - The original encrypted event received over the wire.
2322    /// * `decrypted` - The decrypted event.
2323    ///
2324    /// # Errors
2325    ///
2326    /// Returns an error if any of the following are true:
2327    ///
2328    /// * The original event's state key failed to unpack;
2329    /// * The decrypted event could not be deserialised;
2330    /// * The unpacked event type does not match the type of the decrypted
2331    ///   event;
2332    /// * The unpacked event state key does not match the state key of the
2333    ///   decrypted event.
2334    #[cfg(feature = "experimental-encrypted-state-events")]
2335    fn verify_packed_state_key(
2336        &self,
2337        original: &EncryptedEvent,
2338        decrypted: &Raw<AnyTimelineEvent>,
2339    ) -> MegolmResult<()> {
2340        use serde::Deserialize;
2341
2342        // Helper for deserializing.
2343        #[derive(Deserialize)]
2344        struct PayloadDeserializationHelper {
2345            state_key: Option<String>,
2346            #[serde(rename = "type")]
2347            event_type: String,
2348        }
2349
2350        // Deserialize the decrypted event.
2351        let PayloadDeserializationHelper {
2352            state_key: inner_state_key,
2353            event_type: inner_event_type,
2354        } = decrypted
2355            .deserialize_as_unchecked()
2356            .map_err(|_| MegolmError::StateKeyVerificationFailed)?;
2357
2358        // Ensure we have a state key on the outer event iff there is one in the inner.
2359        let (raw_state_key, inner_state_key) = match (&original.state_key, &inner_state_key) {
2360            (Some(raw_state_key), Some(inner_state_key)) => (raw_state_key, inner_state_key),
2361            (None, None) => return Ok(()),
2362            _ => return Err(MegolmError::StateKeyVerificationFailed),
2363        };
2364
2365        // Unpack event type and state key from the raw state key.
2366        let (outer_event_type, outer_state_key) =
2367            raw_state_key.split_once(":").ok_or(MegolmError::StateKeyVerificationFailed)?;
2368
2369        // Check event types match, discard if not.
2370        if outer_event_type != inner_event_type {
2371            return Err(MegolmError::StateKeyVerificationFailed);
2372        }
2373
2374        // Check state keys match, discard if not.
2375        if outer_state_key != inner_state_key {
2376            return Err(MegolmError::StateKeyVerificationFailed);
2377        }
2378        Ok(())
2379    }
2380
2381    /// Try to decrypt the events bundled in the `unsigned` object of the given
2382    /// event.
2383    ///
2384    /// # Arguments
2385    ///
2386    /// * `main_event` - The event that may contain bundled encrypted events in
2387    ///   its `unsigned` object.
2388    ///
2389    /// * `room_id` - The ID of the room where the event was sent to.
2390    async fn decrypt_unsigned_events(
2391        &self,
2392        main_event: &mut JsonObject,
2393        room_id: &RoomId,
2394        decryption_settings: &DecryptionSettings,
2395    ) -> Option<BTreeMap<UnsignedEventLocation, UnsignedDecryptionResult>> {
2396        let unsigned = main_event.get_mut("unsigned")?.as_object_mut()?;
2397        let mut unsigned_encryption_info: Option<
2398            BTreeMap<UnsignedEventLocation, UnsignedDecryptionResult>,
2399        > = None;
2400
2401        // Search for an encrypted event in `m.replace`, an edit.
2402        let location = UnsignedEventLocation::RelationsReplace;
2403        let replace = location.find_mut(unsigned);
2404        if let Some(decryption_result) =
2405            self.decrypt_unsigned_event(replace, room_id, decryption_settings).await
2406        {
2407            unsigned_encryption_info
2408                .get_or_insert_with(Default::default)
2409                .insert(location, decryption_result);
2410        }
2411
2412        // Search for an encrypted event in `latest_event` in `m.thread`, the
2413        // latest event of a thread.
2414        let location = UnsignedEventLocation::RelationsThreadLatestEvent;
2415        let thread_latest_event = location.find_mut(unsigned);
2416        if let Some(decryption_result) =
2417            self.decrypt_unsigned_event(thread_latest_event, room_id, decryption_settings).await
2418        {
2419            unsigned_encryption_info
2420                .get_or_insert_with(Default::default)
2421                .insert(location, decryption_result);
2422        }
2423
2424        unsigned_encryption_info
2425    }
2426
2427    /// Try to decrypt the given bundled event.
2428    ///
2429    /// # Arguments
2430    ///
2431    /// * `event` - The bundled event that may be encrypted
2432    ///
2433    /// * `room_id` - The ID of the room where the event was sent to.
2434    fn decrypt_unsigned_event<'a>(
2435        &'a self,
2436        event: Option<&'a mut Value>,
2437        room_id: &'a RoomId,
2438        decryption_settings: &'a DecryptionSettings,
2439    ) -> BoxFuture<'a, Option<UnsignedDecryptionResult>> {
2440        Box::pin(async move {
2441            let event = event?;
2442
2443            let is_encrypted = event
2444                .get("type")
2445                .and_then(|type_| type_.as_str())
2446                .is_some_and(|s| s == "m.room.encrypted");
2447            if !is_encrypted {
2448                return None;
2449            }
2450
2451            let raw_event = serde_json::from_value(event.clone()).ok()?;
2452            match self
2453                .decrypt_room_event_inner(&raw_event, room_id, false, decryption_settings)
2454                .await
2455            {
2456                Ok(decrypted_event) => {
2457                    // Replace the encrypted event.
2458                    *event = serde_json::to_value(decrypted_event.event).ok()?;
2459                    Some(UnsignedDecryptionResult::Decrypted(decrypted_event.encryption_info))
2460                }
2461                Err(err) => {
2462                    // For now, we throw away crypto store errors and just treat the unsigned event
2463                    // as unencrypted. Crypto store errors represent problems with the application
2464                    // rather than normal UTD errors, so they should probably be propagated
2465                    // rather than swallowed.
2466                    let utd_info = megolm_error_to_utd_info(&raw_event, err).ok()?;
2467                    Some(UnsignedDecryptionResult::UnableToDecrypt(utd_info))
2468                }
2469            }
2470        })
2471    }
2472
2473    /// Check if we have the room key for the given event in the store.
2474    ///
2475    /// # Arguments
2476    ///
2477    /// * `event` - The event to get information for.
2478    /// * `room_id` - The ID of the room where the event was sent to.
2479    pub async fn is_room_key_available(
2480        &self,
2481        event: &Raw<EncryptedEvent>,
2482        room_id: &RoomId,
2483    ) -> Result<bool, CryptoStoreError> {
2484        let event = event.deserialize()?;
2485
2486        let (session_id, message_index) = match &event.content.scheme {
2487            RoomEventEncryptionScheme::MegolmV1AesSha2(c) => {
2488                (&c.session_id, c.ciphertext.message_index())
2489            }
2490            #[cfg(feature = "experimental-algorithms")]
2491            RoomEventEncryptionScheme::MegolmV2AesSha2(c) => {
2492                (&c.session_id, c.ciphertext.message_index())
2493            }
2494            RoomEventEncryptionScheme::Unknown(_) => {
2495                // We don't support this encryption algorithm, so clearly don't have its key.
2496                return Ok(false);
2497            }
2498        };
2499
2500        // Check that we have the session in the store, and that its first known index
2501        // predates the index of our message.
2502        Ok(self
2503            .store()
2504            .get_inbound_group_session(room_id, session_id)
2505            .await?
2506            .filter(|s| s.first_known_index() <= message_index)
2507            .is_some())
2508    }
2509
2510    /// Get encryption info for a decrypted timeline event.
2511    ///
2512    /// This recalculates the [`EncryptionInfo`] data that is returned by
2513    /// [`OlmMachine::decrypt_room_event`], based on the current
2514    /// verification status of the sender, etc.
2515    ///
2516    /// Returns an error for an unencrypted event.
2517    ///
2518    /// # Arguments
2519    ///
2520    /// * `event` - The event to get information for.
2521    /// * `room_id` - The ID of the room where the event was sent to.
2522    #[instrument(skip(self, event), fields(event_id, sender, session_id))]
2523    pub async fn get_room_event_encryption_info(
2524        &self,
2525        event: &Raw<EncryptedEvent>,
2526        room_id: &RoomId,
2527    ) -> MegolmResult<Arc<EncryptionInfo>> {
2528        let event = event.deserialize()?;
2529
2530        let content: SupportedEventEncryptionSchemes<'_> = match &event.content.scheme {
2531            RoomEventEncryptionScheme::MegolmV1AesSha2(c) => c.into(),
2532            #[cfg(feature = "experimental-algorithms")]
2533            RoomEventEncryptionScheme::MegolmV2AesSha2(c) => c.into(),
2534            RoomEventEncryptionScheme::Unknown(_) => {
2535                return Err(EventError::UnsupportedAlgorithm.into());
2536            }
2537        };
2538
2539        Span::current()
2540            .record("sender", debug(&event.sender))
2541            .record("event_id", debug(&event.event_id))
2542            .record("session_id", content.session_id());
2543
2544        self.get_session_encryption_info(room_id, content.session_id(), &event.sender).await
2545    }
2546
2547    /// Get encryption info for an event decrypted with a megolm session.
2548    ///
2549    /// This recalculates the [`EncryptionInfo`] data that is returned by
2550    /// [`OlmMachine::decrypt_room_event`], based on the current
2551    /// verification status of the sender, etc.
2552    ///
2553    /// Returns an error if the session can't be found.
2554    ///
2555    /// # Arguments
2556    ///
2557    /// * `room_id` - The ID of the room where the session is being used.
2558    /// * `session_id` - The ID of the session to get information for.
2559    /// * `sender` - The (claimed) sender of the event where the session was
2560    ///   used.
2561    pub async fn get_session_encryption_info(
2562        &self,
2563        room_id: &RoomId,
2564        session_id: &str,
2565        sender: &UserId,
2566    ) -> MegolmResult<Arc<EncryptionInfo>> {
2567        let session = self.get_inbound_group_session_or_error(room_id, session_id).await?;
2568        self.get_encryption_info(&session, sender).await
2569    }
2570
2571    /// Update the list of tracked users.
2572    ///
2573    /// The OlmMachine maintains a list of users whose devices we are keeping
2574    /// track of: these are known as "tracked users". These must be users
2575    /// that we share a room with, so that the server sends us updates for
2576    /// their device lists.
2577    ///
2578    /// # Arguments
2579    ///
2580    /// * `users` - An iterator over user ids that should be added to the list
2581    ///   of tracked users
2582    ///
2583    /// Any users that hadn't been seen before will be flagged for a key query
2584    /// immediately, and whenever [`OlmMachine::receive_sync_changes()`]
2585    /// receives a "changed" notification for that user in the future.
2586    ///
2587    /// Users that were already in the list are unaffected.
2588    pub async fn update_tracked_users(
2589        &self,
2590        users: impl IntoIterator<Item = &UserId>,
2591    ) -> StoreResult<()> {
2592        self.inner.identity_manager.update_tracked_users(users).await
2593    }
2594
2595    /// Mark all tracked users as dirty.
2596    ///
2597    /// All users *whose device lists we are tracking* are flagged as needing a
2598    /// key query. Users whose devices we are not tracking are ignored.
2599    pub async fn mark_all_tracked_users_as_dirty(&self) -> StoreResult<()> {
2600        self.inner
2601            .identity_manager
2602            .mark_all_tracked_users_as_dirty(self.inner.store.cache().await?)
2603            .await
2604    }
2605
2606    async fn wait_if_user_pending(
2607        &self,
2608        user_id: &UserId,
2609        timeout: Option<Duration>,
2610    ) -> StoreResult<()> {
2611        if let Some(timeout) = timeout {
2612            let cache = self.store().cache().await?;
2613            self.inner
2614                .identity_manager
2615                .key_query_manager
2616                .wait_if_user_key_query_pending(cache, timeout, user_id)
2617                .await?;
2618        }
2619        Ok(())
2620    }
2621
2622    /// Get a specific device of a user.
2623    ///
2624    /// # Arguments
2625    ///
2626    /// * `user_id` - The unique id of the user that the device belongs to.
2627    ///
2628    /// * `device_id` - The unique id of the device.
2629    ///
2630    /// * `timeout` - The amount of time we should wait before returning if the
2631    /// user's device list has been marked as stale. **Note**, this assumes that
2632    /// the requests from [`OlmMachine::outgoing_requests`] are being
2633    /// processed and sent out.
2634    ///
2635    /// Returns a `Device` if one is found and the crypto store didn't throw an
2636    /// error.
2637    ///
2638    /// # Examples
2639    ///
2640    /// ```
2641    /// # use matrix_sdk_crypto::OlmMachine;
2642    /// # use ruma::{device_id, user_id};
2643    /// # let alice = user_id!("@alice:example.org").to_owned();
2644    /// # futures_executor::block_on(async {
2645    /// # let machine = OlmMachine::new(&alice, device_id!("DEVICEID")).await;
2646    /// let device = machine.get_device(&alice, device_id!("DEVICEID"), None).await;
2647    ///
2648    /// println!("{:?}", device);
2649    /// # });
2650    /// ```
2651    #[instrument(skip(self))]
2652    pub async fn get_device(
2653        &self,
2654        user_id: &UserId,
2655        device_id: &DeviceId,
2656        timeout: Option<Duration>,
2657    ) -> StoreResult<Option<Device>> {
2658        self.wait_if_user_pending(user_id, timeout).await?;
2659        self.store().get_device(user_id, device_id).await
2660    }
2661
2662    /// Get the cross signing user identity of a user.
2663    ///
2664    /// # Arguments
2665    ///
2666    /// * `user_id` - The unique id of the user that the identity belongs to
2667    ///
2668    /// * `timeout` - The amount of time we should wait before returning if the
2669    /// user's device list has been marked as stale. **Note**, this assumes that
2670    /// the requests from [`OlmMachine::outgoing_requests`] are being
2671    /// processed and sent out.
2672    ///
2673    /// Returns a [`UserIdentity`] enum if one is found and the crypto store
2674    /// didn't throw an error.
2675    #[instrument(skip(self))]
2676    pub async fn get_identity(
2677        &self,
2678        user_id: &UserId,
2679        timeout: Option<Duration>,
2680    ) -> StoreResult<Option<UserIdentity>> {
2681        self.wait_if_user_pending(user_id, timeout).await?;
2682        self.store().get_identity(user_id).await
2683    }
2684
2685    /// Get a map holding all the devices of an user.
2686    ///
2687    /// # Arguments
2688    ///
2689    /// * `user_id` - The unique id of the user that the devices belong to.
2690    ///
2691    /// * `timeout` - The amount of time we should wait before returning if the
2692    /// user's device list has been marked as stale. **Note**, this assumes that
2693    /// the requests from [`OlmMachine::outgoing_requests`] are being
2694    /// processed and sent out.
2695    ///
2696    /// # Examples
2697    ///
2698    /// ```
2699    /// # use matrix_sdk_crypto::OlmMachine;
2700    /// # use ruma::{device_id, user_id};
2701    /// # let alice = user_id!("@alice:example.org").to_owned();
2702    /// # futures_executor::block_on(async {
2703    /// # let machine = OlmMachine::new(&alice, device_id!("DEVICEID")).await;
2704    /// let devices = machine.get_user_devices(&alice, None).await.unwrap();
2705    ///
2706    /// for device in devices.devices() {
2707    ///     println!("{:?}", device);
2708    /// }
2709    /// # });
2710    /// ```
2711    #[instrument(skip(self))]
2712    pub async fn get_user_devices(
2713        &self,
2714        user_id: &UserId,
2715        timeout: Option<Duration>,
2716    ) -> StoreResult<UserDevices> {
2717        self.wait_if_user_pending(user_id, timeout).await?;
2718        self.store().get_user_devices(user_id).await
2719    }
2720
2721    /// Get the status of the private cross signing keys.
2722    ///
2723    /// This can be used to check which private cross signing keys we have
2724    /// stored locally.
2725    pub async fn cross_signing_status(&self) -> CrossSigningStatus {
2726        self.inner.user_identity.lock().await.status().await
2727    }
2728
2729    /// Export all the private cross signing keys we have.
2730    ///
2731    /// The export will contain the seed for the ed25519 keys as a unpadded
2732    /// base64 encoded string.
2733    ///
2734    /// This method returns `None` if we don't have any private cross signing
2735    /// keys.
2736    pub async fn export_cross_signing_keys(&self) -> StoreResult<Option<CrossSigningKeyExport>> {
2737        let master_key = self.store().export_secret(&SecretName::CrossSigningMasterKey).await?;
2738        let self_signing_key =
2739            self.store().export_secret(&SecretName::CrossSigningSelfSigningKey).await?;
2740        let user_signing_key =
2741            self.store().export_secret(&SecretName::CrossSigningUserSigningKey).await?;
2742
2743        Ok(if master_key.is_none() && self_signing_key.is_none() && user_signing_key.is_none() {
2744            None
2745        } else {
2746            Some(CrossSigningKeyExport { master_key, self_signing_key, user_signing_key })
2747        })
2748    }
2749
2750    /// Import our private cross signing keys.
2751    ///
2752    /// The export needs to contain the seed for the ed25519 keys as an unpadded
2753    /// base64 encoded string.
2754    pub async fn import_cross_signing_keys(
2755        &self,
2756        export: CrossSigningKeyExport,
2757    ) -> Result<CrossSigningStatus, SecretImportError> {
2758        self.store().import_cross_signing_keys(export).await
2759    }
2760
2761    async fn sign_with_master_key(
2762        &self,
2763        message: &str,
2764    ) -> Result<(OwnedDeviceKeyId, Ed25519Signature), SignatureError> {
2765        let identity = &*self.inner.user_identity.lock().await;
2766        let key_id = identity.master_key_id().await.ok_or(SignatureError::MissingSigningKey)?;
2767
2768        let signature = identity.sign(message).await?;
2769
2770        Ok((key_id, signature))
2771    }
2772
2773    /// Sign the given message using our device key and if available cross
2774    /// signing master key.
2775    ///
2776    /// Presently, this should only be used for signing the server-side room
2777    /// key backups.
2778    pub async fn sign(&self, message: &str) -> Result<Signatures, CryptoStoreError> {
2779        let mut signatures = Signatures::new();
2780
2781        {
2782            let cache = self.inner.store.cache().await?;
2783            let account = cache.account().await?;
2784            let key_id = account.signing_key_id();
2785            let signature = account.sign(message);
2786            signatures.add_signature(self.user_id().to_owned(), key_id, signature);
2787        }
2788
2789        match self.sign_with_master_key(message).await {
2790            Ok((key_id, signature)) => {
2791                signatures.add_signature(self.user_id().to_owned(), key_id, signature);
2792            }
2793            Err(e) => {
2794                warn!(error = ?e, "Couldn't sign the message using the cross signing master key")
2795            }
2796        }
2797
2798        Ok(signatures)
2799    }
2800
2801    /// Get a reference to the backup related state machine.
2802    ///
2803    /// This state machine can be used to incrementally backup all room keys to
2804    /// the server.
2805    pub fn backup_machine(&self) -> &BackupMachine {
2806        &self.inner.backup_machine
2807    }
2808
2809    /// Syncs the database and in-memory generation counter.
2810    ///
2811    /// This requires that the crypto store lock has been acquired already.
2812    pub async fn initialize_crypto_store_generation(
2813        &self,
2814        generation: &Mutex<Option<u64>>,
2815    ) -> StoreResult<()> {
2816        // Avoid reentrant initialization by taking the lock for the entire's function
2817        // scope.
2818        let mut gen_guard = generation.lock().await;
2819
2820        let prev_generation =
2821            self.inner.store.get_custom_value(Self::CURRENT_GENERATION_STORE_KEY).await?;
2822
2823        let generation = match prev_generation {
2824            Some(val) => {
2825                // There was a value in the store. We need to signal that we're a different
2826                // process, so we don't just reuse the value but increment it.
2827                u64::from_le_bytes(val.try_into().map_err(|_| {
2828                    CryptoStoreError::InvalidLockGeneration("invalid format".to_owned())
2829                })?)
2830                .wrapping_add(1)
2831            }
2832            None => 0,
2833        };
2834
2835        tracing::debug!("Initialising crypto store generation at {generation}");
2836
2837        self.inner
2838            .store
2839            .set_custom_value(Self::CURRENT_GENERATION_STORE_KEY, generation.to_le_bytes().to_vec())
2840            .await?;
2841
2842        *gen_guard = Some(generation);
2843
2844        Ok(())
2845    }
2846
2847    /// If needs be, update the local and on-disk crypto store generation.
2848    ///
2849    /// ## Requirements
2850    ///
2851    /// - This assumes that `initialize_crypto_store_generation` has been called
2852    ///   beforehand.
2853    /// - This requires that the crypto store lock has been acquired.
2854    ///
2855    /// # Arguments
2856    ///
2857    /// * `generation` - The in-memory generation counter (or rather, the
2858    ///   `Mutex` wrapping it). This defines the "expected" generation on entry,
2859    ///   and, if we determine an update is needed, is updated to hold the "new"
2860    ///   generation.
2861    ///
2862    /// # Returns
2863    ///
2864    /// A tuple containing:
2865    ///
2866    /// * A `bool`, set to `true` if another process has updated the generation
2867    ///   number in the `Store` since our expected value, and as such we've
2868    ///   incremented and updated it in the database. Otherwise, `false`.
2869    ///
2870    /// * The (possibly updated) generation counter.
2871    pub async fn maintain_crypto_store_generation(
2872        &'_ self,
2873        generation: &Mutex<Option<u64>>,
2874    ) -> StoreResult<(bool, u64)> {
2875        let mut gen_guard = generation.lock().await;
2876
2877        // The database value must be there:
2878        // - either we could initialize beforehand, thus write into the database,
2879        // - or we couldn't, and then another process was holding onto the database's
2880        //   lock, thus
2881        // has written a generation counter in there.
2882        let actual_gen = self
2883            .inner
2884            .store
2885            .get_custom_value(Self::CURRENT_GENERATION_STORE_KEY)
2886            .await?
2887            .ok_or_else(|| {
2888                CryptoStoreError::InvalidLockGeneration("counter missing in store".to_owned())
2889            })?;
2890
2891        let actual_gen =
2892            u64::from_le_bytes(actual_gen.try_into().map_err(|_| {
2893                CryptoStoreError::InvalidLockGeneration("invalid format".to_owned())
2894            })?);
2895
2896        let new_gen = match gen_guard.as_ref() {
2897            Some(expected_gen) => {
2898                if actual_gen == *expected_gen {
2899                    return Ok((false, actual_gen));
2900                }
2901                // Increment the biggest, and store it everywhere.
2902                actual_gen.max(*expected_gen).wrapping_add(1)
2903            }
2904            None => {
2905                // Some other process hold onto the lock when initializing, so we must reload.
2906                // Increment database value, and store it everywhere.
2907                actual_gen.wrapping_add(1)
2908            }
2909        };
2910
2911        tracing::debug!(
2912            "Crypto store generation mismatch: previously known was {:?}, actual is {:?}, next is {}",
2913            *gen_guard,
2914            actual_gen,
2915            new_gen
2916        );
2917
2918        // Update known value.
2919        *gen_guard = Some(new_gen);
2920
2921        // Update value in database.
2922        self.inner
2923            .store
2924            .set_custom_value(Self::CURRENT_GENERATION_STORE_KEY, new_gen.to_le_bytes().to_vec())
2925            .await?;
2926
2927        Ok((true, new_gen))
2928    }
2929
2930    /// Manage dehydrated devices.
2931    pub fn dehydrated_devices(&self) -> DehydratedDevices {
2932        DehydratedDevices { inner: self.to_owned() }
2933    }
2934
2935    /// Get the stored encryption settings for the given room, such as the
2936    /// encryption algorithm or whether to encrypt only for trusted devices.
2937    ///
2938    /// These settings can be modified via [`OlmMachine::set_room_settings`].
2939    pub async fn room_settings(&self, room_id: &RoomId) -> StoreResult<Option<RoomSettings>> {
2940        // There's not much to do here: it's just exposed for symmetry with
2941        // `set_room_settings`.
2942        self.inner.store.get_room_settings(room_id).await
2943    }
2944
2945    /// Store encryption settings for the given room.
2946    ///
2947    /// This method checks if the new settings are "safe" -- ie, that they do
2948    /// not represent a downgrade in encryption security from any previous
2949    /// settings. Attempts to downgrade security will result in a
2950    /// [`SetRoomSettingsError::EncryptionDowngrade`].
2951    ///
2952    /// If the settings are valid, they will be persisted to the crypto store.
2953    /// These settings are not used directly by this library, but the saved
2954    /// settings can be retrieved via [`OlmMachine::room_settings`].
2955    pub async fn set_room_settings(
2956        &self,
2957        room_id: &RoomId,
2958        new_settings: &RoomSettings,
2959    ) -> Result<(), SetRoomSettingsError> {
2960        let store = &self.inner.store;
2961
2962        // We want to make sure that we do not race against a second concurrent call to
2963        // `set_room_settings`. By way of an easy way to do so, we start a
2964        // StoreTransaction. There's no need to commit() it: we're just using it as a
2965        // lock guard.
2966        let _store_transaction = store.transaction().await;
2967
2968        let old_settings = store.get_room_settings(room_id).await?;
2969
2970        // We want to make sure that the change to the room settings does not represent
2971        // a downgrade in security. The [E2EE implementation guide] recommends:
2972        //
2973        //  > This flag should **not** be cleared if a later `m.room.encryption` event
2974        //  > changes the configuration.
2975        //
2976        // (However, it doesn't really address how to handle changes to the rotation
2977        // parameters, etc.) For now at least, we are very conservative here:
2978        // any new settings are rejected if they differ from the existing settings.
2979        // merit improvement (cf https://github.com/element-hq/element-meta/issues/69).
2980        //
2981        // [E2EE implementation guide]: https://matrix.org/docs/matrix-concepts/end-to-end-encryption/#handling-an-m-room-encryption-state-event
2982        if let Some(old_settings) = old_settings {
2983            if old_settings != *new_settings {
2984                return Err(SetRoomSettingsError::EncryptionDowngrade);
2985            } else {
2986                // nothing to do here
2987                return Ok(());
2988            }
2989        }
2990
2991        // Make sure that the new settings are valid
2992        match new_settings.algorithm {
2993            EventEncryptionAlgorithm::MegolmV1AesSha2 => (),
2994
2995            #[cfg(feature = "experimental-algorithms")]
2996            EventEncryptionAlgorithm::MegolmV2AesSha2 => (),
2997
2998            _ => {
2999                warn!(
3000                    ?room_id,
3001                    "Rejecting invalid encryption algorithm {}", new_settings.algorithm
3002                );
3003                return Err(SetRoomSettingsError::InvalidSettings);
3004            }
3005        }
3006
3007        // The new settings are acceptable, so let's save them.
3008        store
3009            .save_changes(Changes {
3010                room_settings: HashMap::from([(room_id.to_owned(), new_settings.clone())]),
3011                ..Default::default()
3012            })
3013            .await?;
3014
3015        Ok(())
3016    }
3017
3018    /// Returns whether this `OlmMachine` is the same another one.
3019    ///
3020    /// Useful for testing purposes only.
3021    #[cfg(any(feature = "testing", test))]
3022    pub fn same_as(&self, other: &OlmMachine) -> bool {
3023        Arc::ptr_eq(&self.inner, &other.inner)
3024    }
3025
3026    /// Testing purposes only.
3027    #[cfg(any(feature = "testing", test))]
3028    pub async fn uploaded_key_count(&self) -> Result<u64, CryptoStoreError> {
3029        let cache = self.inner.store.cache().await?;
3030        let account = cache.account().await?;
3031        Ok(account.uploaded_key_count())
3032    }
3033
3034    /// Returns the identity manager.
3035    #[cfg(test)]
3036    pub(crate) fn identity_manager(&self) -> &IdentityManager {
3037        &self.inner.identity_manager
3038    }
3039
3040    /// Returns a store key, only useful for testing purposes.
3041    #[cfg(test)]
3042    pub(crate) fn key_for_has_migrated_verification_latch() -> &'static str {
3043        Self::HAS_MIGRATED_VERIFICATION_LATCH
3044    }
3045}
3046
3047fn sender_data_to_verification_state(
3048    sender_data: SenderData,
3049    session_has_been_imported: bool,
3050) -> (VerificationState, Option<OwnedDeviceId>) {
3051    match sender_data {
3052        SenderData::UnknownDevice { owner_check_failed: false, .. } => {
3053            let device_link_problem = if session_has_been_imported {
3054                DeviceLinkProblem::InsecureSource
3055            } else {
3056                DeviceLinkProblem::MissingDevice
3057            };
3058
3059            (VerificationState::Unverified(VerificationLevel::None(device_link_problem)), None)
3060        }
3061        SenderData::UnknownDevice { owner_check_failed: true, .. } => (
3062            VerificationState::Unverified(VerificationLevel::None(
3063                DeviceLinkProblem::InsecureSource,
3064            )),
3065            None,
3066        ),
3067        SenderData::DeviceInfo { device_keys, .. } => (
3068            VerificationState::Unverified(VerificationLevel::UnsignedDevice),
3069            Some(device_keys.device_id),
3070        ),
3071        SenderData::VerificationViolation(KnownSenderData { device_id, .. }) => {
3072            (VerificationState::Unverified(VerificationLevel::VerificationViolation), device_id)
3073        }
3074        SenderData::SenderUnverified(KnownSenderData { device_id, .. }) => {
3075            (VerificationState::Unverified(VerificationLevel::UnverifiedIdentity), device_id)
3076        }
3077        SenderData::SenderVerified(KnownSenderData { device_id, .. }) => {
3078            (VerificationState::Verified, device_id)
3079        }
3080    }
3081}
3082
3083/// A set of requests to be executed when bootstrapping cross-signing using
3084/// [`OlmMachine::bootstrap_cross_signing`].
3085#[derive(Debug, Clone)]
3086pub struct CrossSigningBootstrapRequests {
3087    /// An optional request to upload a device key.
3088    ///
3089    /// Should be sent first, if present.
3090    ///
3091    /// If present, its result must be processed back with
3092    /// `OlmMachine::mark_request_as_sent`.
3093    pub upload_keys_req: Option<OutgoingRequest>,
3094
3095    /// Request to upload the cross-signing keys.
3096    ///
3097    /// Should be sent second.
3098    pub upload_signing_keys_req: UploadSigningKeysRequest,
3099
3100    /// Request to upload key signatures, including those for the cross-signing
3101    /// keys, and maybe some for the optional uploaded key too.
3102    ///
3103    /// Should be sent last.
3104    pub upload_signatures_req: UploadSignaturesRequest,
3105}
3106
3107/// Data contained from a sync response and that needs to be processed by the
3108/// OlmMachine.
3109#[derive(Debug)]
3110pub struct EncryptionSyncChanges<'a> {
3111    /// The list of to-device events received in the sync.
3112    pub to_device_events: Vec<Raw<AnyToDeviceEvent>>,
3113    /// The mapping of changed and left devices, per user, as returned in the
3114    /// sync response.
3115    pub changed_devices: &'a DeviceLists,
3116    /// The number of one time keys, as returned in the sync response.
3117    pub one_time_keys_counts: &'a BTreeMap<OneTimeKeyAlgorithm, UInt>,
3118    /// An optional list of fallback keys.
3119    pub unused_fallback_keys: Option<&'a [OneTimeKeyAlgorithm]>,
3120    /// A next-batch token obtained from a to-device sync query.
3121    pub next_batch_token: Option<String>,
3122}
3123
3124/// Convert a [`MegolmError`] into an [`UnableToDecryptInfo`] or a
3125/// [`CryptoStoreError`].
3126///
3127/// Most `MegolmError` codes are converted into a suitable
3128/// `UnableToDecryptInfo`. The exception is [`MegolmError::Store`], which
3129/// represents a problem with our datastore rather than with the message itself,
3130/// and is therefore returned as a `CryptoStoreError`.
3131fn megolm_error_to_utd_info(
3132    raw_event: &Raw<EncryptedEvent>,
3133    error: MegolmError,
3134) -> Result<UnableToDecryptInfo, CryptoStoreError> {
3135    use MegolmError::*;
3136    let reason = match error {
3137        EventError(_) => UnableToDecryptReason::MalformedEncryptedEvent,
3138        Decode(_) => UnableToDecryptReason::MalformedEncryptedEvent,
3139        MissingRoomKey(maybe_withheld) => {
3140            UnableToDecryptReason::MissingMegolmSession { withheld_code: maybe_withheld }
3141        }
3142        Decryption(DecryptionError::UnknownMessageIndex(_, _)) => {
3143            UnableToDecryptReason::UnknownMegolmMessageIndex
3144        }
3145        Decryption(_) => UnableToDecryptReason::MegolmDecryptionFailure,
3146        JsonError(_) => UnableToDecryptReason::PayloadDeserializationFailure,
3147        MismatchedIdentityKeys(_) => UnableToDecryptReason::MismatchedIdentityKeys,
3148        SenderIdentityNotTrusted(level) => UnableToDecryptReason::SenderIdentityNotTrusted(level),
3149        #[cfg(feature = "experimental-encrypted-state-events")]
3150        StateKeyVerificationFailed => UnableToDecryptReason::StateKeyVerificationFailed,
3151
3152        // Pass through crypto store errors, which indicate a problem with our
3153        // application, rather than a UTD.
3154        Store(error) => Err(error)?,
3155    };
3156
3157    let session_id = raw_event.deserialize().ok().and_then(|ev| match ev.content.scheme {
3158        RoomEventEncryptionScheme::MegolmV1AesSha2(s) => Some(s.session_id),
3159        #[cfg(feature = "experimental-algorithms")]
3160        RoomEventEncryptionScheme::MegolmV2AesSha2(s) => Some(s.session_id),
3161        RoomEventEncryptionScheme::Unknown(_) => None,
3162    });
3163
3164    Ok(UnableToDecryptInfo { session_id, reason })
3165}
3166
3167/// An error that can occur during [`OlmMachine::decrypt_to_device_event`]:
3168///
3169/// * because decryption failed, or
3170///
3171/// * because the sender device was not verified when we are in strict "exclude
3172///   insecure devices" mode, or
3173///
3174/// * because the sender device was a dehydrated device, which should never send
3175///   any to-device messages.
3176#[derive(Debug, thiserror::Error)]
3177pub(crate) enum DecryptToDeviceError {
3178    #[error("An Olm error occurred meaning we failed to decrypt the event")]
3179    OlmError(#[from] OlmError),
3180
3181    #[error("The event was sent from a dehydrated device")]
3182    FromDehydratedDevice,
3183}
3184
3185impl From<CryptoStoreError> for DecryptToDeviceError {
3186    fn from(value: CryptoStoreError) -> Self {
3187        Self::OlmError(value.into())
3188    }
3189}
3190
3191#[cfg(test)]
3192impl From<DecryptToDeviceError> for OlmError {
3193    /// Unwrap the `OlmError` inside this error, or panic if this does not
3194    /// contain an `OlmError`.
3195    fn from(value: DecryptToDeviceError) -> Self {
3196        match value {
3197            DecryptToDeviceError::OlmError(olm_error) => olm_error,
3198            DecryptToDeviceError::FromDehydratedDevice => {
3199                panic!("Expected an OlmError but found FromDehydratedDevice")
3200            }
3201        }
3202    }
3203}
3204
3205#[cfg(test)]
3206pub(crate) mod test_helpers;
3207
3208#[cfg(test)]
3209pub(crate) mod tests;