matrix_sdk_crypto/olm/
account.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
15use std::{
16    collections::{BTreeMap, HashMap},
17    fmt,
18    ops::{Deref, Not as _},
19    sync::Arc,
20    time::Duration,
21};
22
23use hkdf::Hkdf;
24use js_option::JsOption;
25use matrix_sdk_common::deserialized_responses::{
26    AlgorithmInfo, DeviceLinkProblem, EncryptionInfo, VerificationLevel, VerificationState,
27};
28#[cfg(test)]
29use ruma::api::client::dehydrated_device::DehydratedDeviceV1;
30use ruma::{
31    DeviceId, DeviceKeyAlgorithm, DeviceKeyId, MilliSecondsSinceUnixEpoch, OneTimeKeyAlgorithm,
32    OneTimeKeyId, OwnedDeviceId, OwnedDeviceKeyId, OwnedOneTimeKeyId, OwnedUserId, RoomId,
33    SecondsSinceUnixEpoch, UInt, UserId,
34    api::client::{
35        dehydrated_device::{DehydratedDeviceData, DehydratedDeviceV2},
36        keys::{
37            upload_keys,
38            upload_signatures::v3::{Request as SignatureUploadRequest, SignedKeys},
39        },
40    },
41    events::{AnyToDeviceEvent, room::history_visibility::HistoryVisibility},
42    serde::Raw,
43};
44use serde::{Deserialize, Serialize, de::Error};
45use serde_json::{
46    Value,
47    value::{RawValue as RawJsonValue, to_raw_value},
48};
49use sha2::{Digest, Sha256};
50use tokio::sync::Mutex;
51use tracing::{Span, debug, field::debug, info, instrument, trace, warn};
52use vodozemac::{
53    Curve25519PublicKey, Ed25519Signature, KeyId, PickleError, base64_encode,
54    olm::{
55        Account as InnerAccount, AccountPickle, IdentityKeys, OlmMessage,
56        OneTimeKeyGenerationResult, PreKeyMessage, SessionConfig,
57    },
58};
59
60use super::{
61    EncryptionSettings, InboundGroupSession, OutboundGroupSession, PrivateCrossSigningIdentity,
62    Session, SessionCreationError as MegolmSessionCreationError, utility::SignJson,
63};
64#[cfg(feature = "experimental-algorithms")]
65use crate::types::events::room::encrypted::OlmV2Curve25519AesSha2Content;
66use crate::{
67    DecryptionSettings, Device, OlmError, SignatureError, TrustRequirement,
68    dehydrated_devices::DehydrationError,
69    error::{EventError, OlmResult, SessionCreationError},
70    identities::DeviceData,
71    olm::SenderData,
72    store::{
73        Store,
74        types::{Changes, DeviceChanges},
75    },
76    types::{
77        CrossSigningKey, DeviceKeys, EventEncryptionAlgorithm, MasterPubkey, OneTimeKey, SignedKey,
78        events::{
79            olm_v1::AnyDecryptedOlmEvent,
80            room::encrypted::{
81                EncryptedToDeviceEvent, OlmV1Curve25519AesSha2Content,
82                ToDeviceEncryptedEventContent,
83            },
84        },
85        requests::UploadSigningKeysRequest,
86    },
87};
88
89#[derive(Debug)]
90enum PrekeyBundle {
91    Olm3DH { key: SignedKey },
92}
93
94#[derive(Debug, Clone)]
95pub(crate) enum SessionType {
96    New(Session),
97    Existing(Session),
98}
99
100#[derive(Debug)]
101pub struct InboundCreationResult {
102    pub session: Session,
103    pub plaintext: String,
104}
105
106impl SessionType {
107    #[cfg(test)]
108    pub fn session(self) -> Session {
109        match self {
110            SessionType::New(s) => s,
111            SessionType::Existing(s) => s,
112        }
113    }
114}
115
116/// A struct witnessing a successful decryption of an Olm-encrypted to-device
117/// event.
118///
119/// Contains the decrypted event plaintext along with some associated metadata,
120/// such as the identity (Curve25519) key of the to-device event sender.
121#[derive(Debug)]
122pub(crate) struct OlmDecryptionInfo {
123    pub session: SessionType,
124    pub message_hash: OlmMessageHash,
125    pub inbound_group_session: Option<InboundGroupSession>,
126    pub result: DecryptionResult,
127}
128
129#[derive(Debug)]
130pub(crate) struct DecryptionResult {
131    // AnyDecryptedOlmEvent is pretty big at 512 bytes, box it to reduce stack size
132    pub event: Box<AnyDecryptedOlmEvent>,
133    pub raw_event: Raw<AnyToDeviceEvent>,
134    pub sender_key: Curve25519PublicKey,
135    pub encryption_info: EncryptionInfo,
136}
137
138/// A hash of a successfully decrypted Olm message.
139///
140/// Can be used to check if a message has been replayed to us.
141#[derive(Debug, Clone, Serialize, Deserialize)]
142pub struct OlmMessageHash {
143    /// The curve25519 key of the sender that sent us the Olm message.
144    pub sender_key: String,
145    /// The hash of the message.
146    pub hash: String,
147}
148
149impl OlmMessageHash {
150    fn new(sender_key: Curve25519PublicKey, ciphertext: &OlmMessage) -> Self {
151        let (message_type, ciphertext) = ciphertext.clone().to_parts();
152        let sender_key = sender_key.to_base64();
153
154        let sha = Sha256::new()
155            .chain_update(sender_key.as_bytes())
156            .chain_update([message_type as u8])
157            .chain_update(ciphertext)
158            .finalize();
159
160        Self { sender_key, hash: base64_encode(sha.as_slice()) }
161    }
162}
163
164/// Account data that's static for the lifetime of a Client.
165///
166/// This data never changes once it's set, so it can be freely passed and cloned
167/// everywhere.
168#[derive(Clone)]
169#[cfg_attr(not(tarpaulin_include), derive(Debug))]
170pub struct StaticAccountData {
171    /// The user_id this account belongs to.
172    pub user_id: OwnedUserId,
173    /// The device_id of this entry.
174    pub device_id: OwnedDeviceId,
175    /// The associated identity keys.
176    pub identity_keys: Arc<IdentityKeys>,
177    /// Whether the account is for a dehydrated device.
178    pub dehydrated: bool,
179    // The creation time of the account in milliseconds since epoch.
180    creation_local_time: MilliSecondsSinceUnixEpoch,
181}
182
183impl StaticAccountData {
184    const ALGORITHMS: &'static [&'static EventEncryptionAlgorithm] = &[
185        &EventEncryptionAlgorithm::OlmV1Curve25519AesSha2,
186        #[cfg(feature = "experimental-algorithms")]
187        &EventEncryptionAlgorithm::OlmV2Curve25519AesSha2,
188        &EventEncryptionAlgorithm::MegolmV1AesSha2,
189        #[cfg(feature = "experimental-algorithms")]
190        &EventEncryptionAlgorithm::MegolmV2AesSha2,
191    ];
192
193    /// Create a group session pair.
194    ///
195    /// This session pair can be used to encrypt and decrypt messages meant for
196    /// a large group of participants.
197    ///
198    /// The outbound session is used to encrypt messages while the inbound one
199    /// is used to decrypt messages encrypted by the outbound one.
200    ///
201    /// # Arguments
202    ///
203    /// * `room_id` - The ID of the room where the group session will be used.
204    ///
205    /// * `settings` - Settings determining the algorithm and rotation period of
206    ///   the outbound group session.
207    pub async fn create_group_session_pair(
208        &self,
209        room_id: &RoomId,
210        settings: EncryptionSettings,
211        own_sender_data: SenderData,
212    ) -> Result<(OutboundGroupSession, InboundGroupSession), MegolmSessionCreationError> {
213        trace!(?room_id, algorithm = settings.algorithm.as_str(), "Creating a new room key");
214
215        let visibility = settings.history_visibility.clone();
216        let algorithm = settings.algorithm.to_owned();
217
218        let outbound = OutboundGroupSession::new(
219            self.device_id.clone(),
220            self.identity_keys.clone(),
221            room_id,
222            settings,
223        )?;
224
225        let identity_keys = &self.identity_keys;
226
227        let sender_key = identity_keys.curve25519;
228        let signing_key = identity_keys.ed25519;
229        let shared_history = shared_history_from_history_visibility(&visibility);
230
231        let inbound = InboundGroupSession::new(
232            sender_key,
233            signing_key,
234            room_id,
235            &outbound.session_key().await,
236            own_sender_data,
237            None,
238            algorithm,
239            Some(visibility),
240            shared_history,
241        )?;
242
243        Ok((outbound, inbound))
244    }
245
246    #[cfg(any(test, feature = "testing"))]
247    #[allow(dead_code)]
248    /// Testing only facility to create a group session pair with default
249    /// settings.
250    pub async fn create_group_session_pair_with_defaults(
251        &self,
252        room_id: &RoomId,
253    ) -> (OutboundGroupSession, InboundGroupSession) {
254        self.create_group_session_pair(
255            room_id,
256            EncryptionSettings::default(),
257            SenderData::unknown(),
258        )
259        .await
260        .expect("Can't create default group session pair")
261    }
262
263    /// Get the key ID of our Ed25519 signing key.
264    pub fn signing_key_id(&self) -> OwnedDeviceKeyId {
265        DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, self.device_id())
266    }
267
268    /// Check if the given JSON is signed by this Account key.
269    ///
270    /// This method should only be used if an object's signature needs to be
271    /// checked multiple times, and you'd like to avoid performing the
272    /// canonicalization step each time.
273    ///
274    /// **Note**: Use this method with caution, the `canonical_json` needs to be
275    /// correctly canonicalized and make sure that the object you are checking
276    /// the signature for is allowed to be signed by our own device.
277    pub fn has_signed_raw(
278        &self,
279        signatures: &crate::types::Signatures,
280        canonical_json: &str,
281    ) -> Result<(), SignatureError> {
282        use crate::olm::utility::VerifyJson;
283
284        let signing_key = self.identity_keys.ed25519;
285
286        signing_key.verify_canonicalized_json(
287            &self.user_id,
288            &DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, self.device_id()),
289            signatures,
290            canonical_json,
291        )
292    }
293
294    /// Generate the unsigned `DeviceKeys` from this `StaticAccountData`.
295    pub fn unsigned_device_keys(&self) -> DeviceKeys {
296        let identity_keys = self.identity_keys();
297        let keys = BTreeMap::from([
298            (
299                DeviceKeyId::from_parts(DeviceKeyAlgorithm::Curve25519, &self.device_id),
300                identity_keys.curve25519.into(),
301            ),
302            (
303                DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, &self.device_id),
304                identity_keys.ed25519.into(),
305            ),
306        ]);
307
308        let mut ret = DeviceKeys::new(
309            (*self.user_id).to_owned(),
310            (*self.device_id).to_owned(),
311            Self::ALGORITHMS.iter().map(|a| (**a).clone()).collect(),
312            keys,
313            Default::default(),
314        );
315        if self.dehydrated {
316            ret.dehydrated = JsOption::Some(true);
317        }
318        ret
319    }
320
321    /// Get the user id of the owner of the account.
322    pub fn user_id(&self) -> &UserId {
323        &self.user_id
324    }
325
326    /// Get the device ID that owns this account.
327    pub fn device_id(&self) -> &DeviceId {
328        &self.device_id
329    }
330
331    /// Get the public parts of the identity keys for the account.
332    pub fn identity_keys(&self) -> IdentityKeys {
333        *self.identity_keys
334    }
335
336    /// Get the local timestamp creation of the account in secs since epoch.
337    pub fn creation_local_time(&self) -> MilliSecondsSinceUnixEpoch {
338        self.creation_local_time
339    }
340}
341
342/// Account holding identity keys for which sessions can be created.
343///
344/// An account is the central identity for encrypted communication between two
345/// devices.
346pub struct Account {
347    pub(crate) static_data: StaticAccountData,
348    /// `vodozemac` account.
349    inner: Box<InnerAccount>,
350    /// Is this account ready to encrypt messages? (i.e. has it shared keys with
351    /// a homeserver)
352    shared: bool,
353    /// The number of signed one-time keys we have uploaded to the server. If
354    /// this is None, no action will be taken. After a sync request the client
355    /// needs to set this for us, depending on the count we will suggest the
356    /// client to upload new keys.
357    uploaded_signed_key_count: u64,
358    /// The timestamp of the last time we generated a fallback key. Fallback
359    /// keys are rotated in a time-based manner. This field records when we
360    /// either generated our first fallback key or rotated one.
361    ///
362    /// Will be `None` if we never created a fallback key, or if we're migrating
363    /// from a `AccountPickle` that didn't use time-based fallback key
364    /// rotation.
365    fallback_creation_timestamp: Option<MilliSecondsSinceUnixEpoch>,
366}
367
368impl Deref for Account {
369    type Target = StaticAccountData;
370
371    fn deref(&self) -> &Self::Target {
372        &self.static_data
373    }
374}
375
376/// A pickled version of an `Account`.
377///
378/// Holds all the information that needs to be stored in a database to restore
379/// an account.
380#[derive(Serialize, Deserialize)]
381#[allow(missing_debug_implementations)]
382pub struct PickledAccount {
383    /// The user id of the account owner.
384    pub user_id: OwnedUserId,
385    /// The device ID of the account owner.
386    pub device_id: OwnedDeviceId,
387    /// The pickled version of the Olm account.
388    pub pickle: AccountPickle,
389    /// Was the account shared.
390    pub shared: bool,
391    /// Whether this is for a dehydrated device
392    #[serde(default)]
393    pub dehydrated: bool,
394    /// The number of uploaded one-time keys we have on the server.
395    pub uploaded_signed_key_count: u64,
396    /// The local time creation of this account (milliseconds since epoch), used
397    /// as creation time of own device
398    #[serde(default = "default_account_creation_time")]
399    pub creation_local_time: MilliSecondsSinceUnixEpoch,
400    /// The timestamp of the last time we generated a fallback key.
401    #[serde(default)]
402    pub fallback_key_creation_timestamp: Option<MilliSecondsSinceUnixEpoch>,
403}
404
405fn default_account_creation_time() -> MilliSecondsSinceUnixEpoch {
406    MilliSecondsSinceUnixEpoch(UInt::default())
407}
408
409#[cfg(not(tarpaulin_include))]
410impl fmt::Debug for Account {
411    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
412        f.debug_struct("Account")
413            .field("identity_keys", &self.identity_keys())
414            .field("shared", &self.shared())
415            .finish()
416    }
417}
418
419pub type OneTimeKeys = BTreeMap<OwnedOneTimeKeyId, Raw<ruma::encryption::OneTimeKey>>;
420pub type FallbackKeys = OneTimeKeys;
421
422impl Account {
423    pub(crate) fn new_helper(
424        mut account: InnerAccount,
425        user_id: &UserId,
426        device_id: &DeviceId,
427    ) -> Self {
428        let identity_keys = account.identity_keys();
429
430        // Let's generate some initial one-time keys while we're here. Since we know
431        // that this is a completely new [`Account`] we're certain that the
432        // server does not yet have any one-time keys of ours.
433        //
434        // This ensures we upload one-time keys along with our device keys right
435        // away, rather than waiting for the key counts to be echoed back to us
436        // from the server.
437        //
438        // It would be nice to do this for the fallback key as well but we can't assume
439        // that the server supports fallback keys. Maybe one of these days we
440        // will be able to do so.
441        account.generate_one_time_keys(account.max_number_of_one_time_keys());
442
443        Self {
444            static_data: StaticAccountData {
445                user_id: user_id.into(),
446                device_id: device_id.into(),
447                identity_keys: Arc::new(identity_keys),
448                dehydrated: false,
449                creation_local_time: MilliSecondsSinceUnixEpoch::now(),
450            },
451            inner: Box::new(account),
452            shared: false,
453            uploaded_signed_key_count: 0,
454            fallback_creation_timestamp: None,
455        }
456    }
457
458    /// Create a fresh new account, this will generate the identity key-pair.
459    pub fn with_device_id(user_id: &UserId, device_id: &DeviceId) -> Self {
460        let account = InnerAccount::new();
461
462        Self::new_helper(account, user_id, device_id)
463    }
464
465    /// Create a new random Olm Account, the long-term Curve25519 identity key
466    /// encoded as base64 will be used for the device ID.
467    pub fn new(user_id: &UserId) -> Self {
468        let account = InnerAccount::new();
469        let device_id: OwnedDeviceId =
470            base64_encode(account.identity_keys().curve25519.as_bytes()).into();
471
472        Self::new_helper(account, user_id, &device_id)
473    }
474
475    /// Create a new random Olm Account for a dehydrated device
476    pub fn new_dehydrated(user_id: &UserId) -> Self {
477        let account = InnerAccount::new();
478        let device_id: OwnedDeviceId =
479            base64_encode(account.identity_keys().curve25519.as_bytes()).into();
480
481        let mut ret = Self::new_helper(account, user_id, &device_id);
482        ret.static_data.dehydrated = true;
483        ret
484    }
485
486    /// Get the immutable data for this account.
487    pub fn static_data(&self) -> &StaticAccountData {
488        &self.static_data
489    }
490
491    /// Update the uploaded key count.
492    ///
493    /// # Arguments
494    ///
495    /// * `new_count` - The new count that was reported by the server.
496    pub fn update_uploaded_key_count(&mut self, new_count: u64) {
497        self.uploaded_signed_key_count = new_count;
498    }
499
500    /// Get the currently known uploaded key count.
501    pub fn uploaded_key_count(&self) -> u64 {
502        self.uploaded_signed_key_count
503    }
504
505    /// Has the account been shared with the server.
506    pub fn shared(&self) -> bool {
507        self.shared
508    }
509
510    /// Mark the account as shared.
511    ///
512    /// Messages shouldn't be encrypted with the session before it has been
513    /// shared.
514    pub fn mark_as_shared(&mut self) {
515        self.shared = true;
516    }
517
518    /// Get the one-time keys of the account.
519    ///
520    /// This can be empty, keys need to be generated first.
521    pub fn one_time_keys(&self) -> HashMap<KeyId, Curve25519PublicKey> {
522        self.inner.one_time_keys()
523    }
524
525    /// Generate count number of one-time keys.
526    pub fn generate_one_time_keys(&mut self, count: usize) -> OneTimeKeyGenerationResult {
527        self.inner.generate_one_time_keys(count)
528    }
529
530    /// Get the maximum number of one-time keys the account can hold.
531    pub fn max_one_time_keys(&self) -> usize {
532        self.inner.max_number_of_one_time_keys()
533    }
534
535    pub(crate) fn update_key_counts(
536        &mut self,
537        one_time_key_counts: &BTreeMap<OneTimeKeyAlgorithm, UInt>,
538        unused_fallback_keys: Option<&[OneTimeKeyAlgorithm]>,
539    ) {
540        if let Some(count) = one_time_key_counts.get(&OneTimeKeyAlgorithm::SignedCurve25519) {
541            let count: u64 = (*count).into();
542            let old_count = self.uploaded_key_count();
543
544            // Some servers might always return the key counts in the sync
545            // response, we don't want to the logs with noop changes if they do
546            // so.
547            if count != old_count {
548                debug!(
549                    "Updated uploaded one-time key count {} -> {count}.",
550                    self.uploaded_key_count(),
551                );
552            }
553
554            self.update_uploaded_key_count(count);
555            self.generate_one_time_keys_if_needed();
556        }
557
558        // If the server supports fallback keys or if it did so in the past, shown by
559        // the existence of a fallback creation timestamp, generate a new one if
560        // we don't have one, or if the current fallback key expired.
561        if unused_fallback_keys.is_some() || self.fallback_creation_timestamp.is_some() {
562            self.generate_fallback_key_if_needed();
563        }
564    }
565
566    /// Generate new one-time keys that need to be uploaded to the server.
567    ///
568    /// Returns None if no keys need to be uploaded, otherwise the number of
569    /// newly generated one-time keys. May return 0 if some one-time keys are
570    /// already generated but weren't uploaded.
571    ///
572    /// Generally `Some` means that keys should be uploaded, while `None` means
573    /// that keys should not be uploaded.
574    #[instrument(skip_all)]
575    pub fn generate_one_time_keys_if_needed(&mut self) -> Option<u64> {
576        // Only generate one-time keys if there aren't any, otherwise the caller
577        // might have failed to upload them the last time this method was
578        // called.
579        if !self.one_time_keys().is_empty() {
580            return Some(0);
581        }
582
583        let count = self.uploaded_key_count();
584        let max_keys = self.max_one_time_keys();
585
586        if count >= max_keys as u64 {
587            return None;
588        }
589
590        let key_count = (max_keys as u64) - count;
591        let key_count: usize = key_count.try_into().unwrap_or(max_keys);
592
593        let result = self.generate_one_time_keys(key_count);
594
595        debug!(
596            count = key_count,
597            discarded_keys = ?result.removed,
598            created_keys = ?result.created,
599            "Generated new one-time keys"
600        );
601
602        Some(key_count as u64)
603    }
604
605    /// Generate a new fallback key iff a unpublished one isn't already inside
606    /// of vodozemac and if the currently active one expired.
607    ///
608    /// The former is checked using [`Account::fallback_key().is_empty()`],
609    /// which is a hashmap that gets cleared by the
610    /// [`Account::mark_keys_as_published()`] call.
611    pub(crate) fn generate_fallback_key_if_needed(&mut self) {
612        if self.inner.fallback_key().is_empty() && self.fallback_key_expired() {
613            let removed_fallback_key = self.inner.generate_fallback_key();
614            self.fallback_creation_timestamp = Some(MilliSecondsSinceUnixEpoch::now());
615
616            debug!(
617                ?removed_fallback_key,
618                "The fallback key either expired or we didn't have one: generated a new fallback key.",
619            );
620        }
621    }
622
623    /// Check if our most recent fallback key has expired.
624    ///
625    /// We consider the fallback key to be expired if it's older than a week.
626    /// This is the lower bound for the recommended signed pre-key bundle
627    /// rotation interval in the X3DH spec[1].
628    ///
629    /// [1]: https://signal.org/docs/specifications/x3dh/#publishing-keys
630    fn fallback_key_expired(&self) -> bool {
631        const FALLBACK_KEY_MAX_AGE: Duration = Duration::from_secs(3600 * 24 * 7);
632
633        if let Some(time) = self.fallback_creation_timestamp {
634            // `to_system_time()` returns `None` if the the UNIX_EPOCH + `time` doesn't fit
635            // into a i64. This will likely never happen, but let's rotate the
636            // key in case the values are messed up for some other reason.
637            let Some(system_time) = time.to_system_time() else {
638                return true;
639            };
640
641            // `elapsed()` errors if the `system_time` is in the future, this should mean
642            // that our clock has changed to the past, let's rotate just in case
643            // and then we'll get to a normal time.
644            let Ok(elapsed) = system_time.elapsed() else {
645                return true;
646            };
647
648            // Alright, our times are normal and we know how much time elapsed since the
649            // last time we created/rotated a fallback key.
650            //
651            // If the key is older than a week, then we rotate it.
652            elapsed > FALLBACK_KEY_MAX_AGE
653        } else {
654            // We never created a fallback key, or we're migrating to the time-based
655            // fallback key rotation, so let's generate a new fallback key.
656            true
657        }
658    }
659
660    fn fallback_key(&self) -> HashMap<KeyId, Curve25519PublicKey> {
661        self.inner.fallback_key()
662    }
663
664    /// Get a tuple of device, one-time, and fallback keys that need to be
665    /// uploaded.
666    ///
667    /// If no keys need to be uploaded the `DeviceKeys` will be `None` and the
668    /// one-time and fallback keys maps will be empty.
669    pub fn keys_for_upload(&self) -> (Option<DeviceKeys>, OneTimeKeys, FallbackKeys) {
670        let device_keys = self.shared().not().then(|| self.device_keys());
671
672        let one_time_keys = self.signed_one_time_keys();
673        let fallback_keys = self.signed_fallback_keys();
674
675        (device_keys, one_time_keys, fallback_keys)
676    }
677
678    /// Mark the current set of one-time keys as being published.
679    pub fn mark_keys_as_published(&mut self) {
680        self.inner.mark_keys_as_published();
681    }
682
683    /// Sign the given string using the accounts signing key.
684    ///
685    /// Returns the signature as a base64 encoded string.
686    pub fn sign(&self, string: &str) -> Ed25519Signature {
687        self.inner.sign(string)
688    }
689
690    /// Get a serializable version of the `Account` so it can be persisted.
691    pub fn pickle(&self) -> PickledAccount {
692        let pickle = self.inner.pickle();
693
694        PickledAccount {
695            user_id: self.user_id().to_owned(),
696            device_id: self.device_id().to_owned(),
697            pickle,
698            shared: self.shared(),
699            dehydrated: self.static_data.dehydrated,
700            uploaded_signed_key_count: self.uploaded_key_count(),
701            creation_local_time: self.static_data.creation_local_time,
702            fallback_key_creation_timestamp: self.fallback_creation_timestamp,
703        }
704    }
705
706    pub(crate) fn dehydrate(&self, pickle_key: &[u8; 32]) -> Raw<DehydratedDeviceData> {
707        let dehydration_result = self
708            .inner
709            .to_dehydrated_device(pickle_key)
710            .expect("We should be able to convert a freshly created Account into a libolm pickle");
711
712        let data = DehydratedDeviceData::V2(DehydratedDeviceV2::new(
713            dehydration_result.ciphertext,
714            dehydration_result.nonce,
715        ));
716        Raw::from_json(to_raw_value(&data).expect("Couldn't serialize our dehydrated device data"))
717    }
718
719    pub(crate) fn rehydrate(
720        pickle_key: &[u8; 32],
721        user_id: &UserId,
722        device_id: &DeviceId,
723        device_data: Raw<DehydratedDeviceData>,
724    ) -> Result<Self, DehydrationError> {
725        let data = device_data.deserialize()?;
726
727        match data {
728            DehydratedDeviceData::V1(d) => {
729                let pickle_key = expand_legacy_pickle_key(pickle_key, device_id);
730                let account =
731                    InnerAccount::from_libolm_pickle(&d.device_pickle, pickle_key.as_ref())?;
732                Ok(Self::new_helper(account, user_id, device_id))
733            }
734            DehydratedDeviceData::V2(d) => {
735                let account =
736                    InnerAccount::from_dehydrated_device(&d.device_pickle, &d.nonce, pickle_key)?;
737                Ok(Self::new_helper(account, user_id, device_id))
738            }
739            _ => Err(DehydrationError::Json(serde_json::Error::custom(format!(
740                "Unsupported dehydrated device algorithm {:?}",
741                data.algorithm()
742            )))),
743        }
744    }
745
746    /// Produce a dehydrated device using a format described in an older version
747    /// of MSC3814.
748    #[cfg(test)]
749    pub(crate) fn legacy_dehydrate(&self, pickle_key: &[u8; 32]) -> Raw<DehydratedDeviceData> {
750        let pickle_key = expand_legacy_pickle_key(pickle_key, &self.device_id);
751        let device_pickle = self
752            .inner
753            .to_libolm_pickle(pickle_key.as_ref())
754            .expect("We should be able to convert a freshly created Account into a libolm pickle");
755
756        let data = DehydratedDeviceData::V1(DehydratedDeviceV1::new(device_pickle));
757        Raw::from_json(to_raw_value(&data).expect("Couldn't serialize our dehydrated device data"))
758    }
759
760    /// Restore an account from a previously pickled one.
761    ///
762    /// # Arguments
763    ///
764    /// * `pickle` - The pickled version of the Account.
765    ///
766    /// * `pickle_mode` - The mode that was used to pickle the account, either
767    ///   an unencrypted mode or an encrypted using passphrase.
768    pub fn from_pickle(pickle: PickledAccount) -> Result<Self, PickleError> {
769        let account: vodozemac::olm::Account = pickle.pickle.into();
770        let identity_keys = account.identity_keys();
771
772        Ok(Self {
773            static_data: StaticAccountData {
774                user_id: (*pickle.user_id).into(),
775                device_id: (*pickle.device_id).into(),
776                identity_keys: Arc::new(identity_keys),
777                dehydrated: pickle.dehydrated,
778                creation_local_time: pickle.creation_local_time,
779            },
780            inner: Box::new(account),
781            shared: pickle.shared,
782            uploaded_signed_key_count: pickle.uploaded_signed_key_count,
783            fallback_creation_timestamp: pickle.fallback_key_creation_timestamp,
784        })
785    }
786
787    /// Sign the device keys of the account and return them so they can be
788    /// uploaded.
789    pub fn device_keys(&self) -> DeviceKeys {
790        let mut device_keys = self.unsigned_device_keys();
791
792        // Create a copy of the device keys containing only fields that will
793        // get signed.
794        let json_device_keys =
795            serde_json::to_value(&device_keys).expect("device key is always safe to serialize");
796        let signature = self
797            .sign_json(json_device_keys)
798            .expect("Newly created device keys can always be signed");
799
800        device_keys.signatures.add_signature(
801            self.user_id().to_owned(),
802            DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, &self.static_data.device_id),
803            signature,
804        );
805
806        device_keys
807    }
808
809    /// Bootstraps cross-signing, generating new cross-signing keys and creating
810    /// the necessary upload and signature requests.
811    ///
812    /// # Returns
813    /// A tuple containing:
814    /// - [`PrivateCrossSigningIdentity`]: The newly-generated cross-signing
815    ///   identity (including a signature from this device).
816    /// - [`UploadSigningKeysRequest`]: The request to upload the
817    ///   newly-generated cross-signing keys to the server.
818    /// - [`SignatureUploadRequest`]: The request to upload the signature of
819    ///   this device to the server.
820    pub async fn bootstrap_cross_signing(
821        &self,
822    ) -> (PrivateCrossSigningIdentity, UploadSigningKeysRequest, SignatureUploadRequest) {
823        let identity = PrivateCrossSigningIdentity::for_account(self);
824
825        let signature_request = identity
826            .sign_account(self.static_data())
827            .await
828            .expect("Can't sign own device with new cross signing keys");
829
830        let upload_request = identity.as_upload_request().await;
831
832        (identity, upload_request, signature_request)
833    }
834
835    /// Sign the given CrossSigning Key in place
836    pub fn sign_cross_signing_key(
837        &self,
838        cross_signing_key: &mut CrossSigningKey,
839    ) -> Result<(), SignatureError> {
840        #[allow(clippy::needless_borrows_for_generic_args)]
841        // XXX: false positive, see https://github.com/rust-lang/rust-clippy/issues/12856
842        let signature = self.sign_json(serde_json::to_value(&cross_signing_key)?)?;
843
844        cross_signing_key.signatures.add_signature(
845            self.user_id().to_owned(),
846            DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, self.device_id()),
847            signature,
848        );
849
850        Ok(())
851    }
852
853    /// Sign the given Master Key
854    pub fn sign_master_key(
855        &self,
856        master_key: &MasterPubkey,
857    ) -> Result<SignatureUploadRequest, SignatureError> {
858        let public_key =
859            master_key.get_first_key().ok_or(SignatureError::MissingSigningKey)?.to_base64().into();
860
861        let mut cross_signing_key: CrossSigningKey = master_key.as_ref().clone();
862        cross_signing_key.signatures.clear();
863        self.sign_cross_signing_key(&mut cross_signing_key)?;
864
865        let mut user_signed_keys = SignedKeys::new();
866        user_signed_keys.add_cross_signing_keys(public_key, cross_signing_key.to_raw());
867
868        let signed_keys = [(self.user_id().to_owned(), user_signed_keys)].into();
869        Ok(SignatureUploadRequest::new(signed_keys))
870    }
871
872    /// Convert a JSON value to the canonical representation and sign the JSON
873    /// string.
874    ///
875    /// # Arguments
876    ///
877    /// * `json` - The value that should be converted into a canonical JSON
878    ///   string.
879    pub fn sign_json(&self, json: Value) -> Result<Ed25519Signature, SignatureError> {
880        self.inner.sign_json(json)
881    }
882
883    /// Sign and prepare one-time keys to be uploaded.
884    ///
885    /// If no one-time keys need to be uploaded, returns an empty `BTreeMap`.
886    pub fn signed_one_time_keys(&self) -> OneTimeKeys {
887        let one_time_keys = self.one_time_keys();
888
889        if one_time_keys.is_empty() {
890            BTreeMap::new()
891        } else {
892            self.signed_keys(one_time_keys, false)
893        }
894    }
895
896    /// Sign and prepare fallback keys to be uploaded.
897    ///
898    /// If no fallback keys need to be uploaded returns an empty BTreeMap.
899    pub fn signed_fallback_keys(&self) -> FallbackKeys {
900        let fallback_key = self.fallback_key();
901
902        if fallback_key.is_empty() { BTreeMap::new() } else { self.signed_keys(fallback_key, true) }
903    }
904
905    fn signed_keys(
906        &self,
907        keys: HashMap<KeyId, Curve25519PublicKey>,
908        fallback: bool,
909    ) -> OneTimeKeys {
910        let mut keys_map = BTreeMap::new();
911
912        for (key_id, key) in keys {
913            let signed_key = self.sign_key(key, fallback);
914
915            keys_map.insert(
916                OneTimeKeyId::from_parts(
917                    OneTimeKeyAlgorithm::SignedCurve25519,
918                    key_id.to_base64().as_str().into(),
919                ),
920                signed_key.into_raw(),
921            );
922        }
923
924        keys_map
925    }
926
927    fn sign_key(&self, key: Curve25519PublicKey, fallback: bool) -> SignedKey {
928        let mut key = if fallback {
929            SignedKey::new_fallback(key.to_owned())
930        } else {
931            SignedKey::new(key.to_owned())
932        };
933
934        let signature = self
935            .sign_json(serde_json::to_value(&key).expect("Can't serialize a signed key"))
936            .expect("Newly created one-time keys can always be signed");
937
938        key.signatures_mut().add_signature(
939            self.user_id().to_owned(),
940            DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, self.device_id()),
941            signature,
942        );
943
944        key
945    }
946
947    /// Create a new session with another account given a one-time key.
948    ///
949    /// Returns the newly created session or a `OlmSessionError` if creating a
950    /// session failed.
951    ///
952    /// # Arguments
953    ///
954    /// * `config` - The session config that should be used when creating the
955    ///   Session.
956    ///
957    /// * `identity_key` - The other account's identity/curve25519 key.
958    ///
959    /// * `one_time_key` - A signed one-time key that the other account created
960    ///   and shared with us.
961    ///
962    /// * `fallback_used` - Was the one-time key a fallback key.
963    ///
964    /// * `our_device_keys` - Our own `DeviceKeys`, including cross-signing
965    ///   signatures if applicable, for embedding in encrypted messages.
966    pub fn create_outbound_session_helper(
967        &self,
968        config: SessionConfig,
969        identity_key: Curve25519PublicKey,
970        one_time_key: Curve25519PublicKey,
971        fallback_used: bool,
972        our_device_keys: DeviceKeys,
973    ) -> Session {
974        let session = self.inner.create_outbound_session(config, identity_key, one_time_key);
975
976        let now = SecondsSinceUnixEpoch::now();
977        let session_id = session.session_id();
978
979        Session {
980            inner: Arc::new(Mutex::new(session)),
981            session_id: session_id.into(),
982            sender_key: identity_key,
983            our_device_keys,
984            created_using_fallback_key: fallback_used,
985            creation_time: now,
986            last_use_time: now,
987        }
988    }
989
990    #[instrument(
991        skip_all,
992        fields(
993            user_id = ?device.user_id(),
994            device_id = ?device.device_id(),
995            algorithms = ?device.algorithms()
996        )
997    )]
998    fn find_pre_key_bundle(
999        device: &DeviceData,
1000        key_map: &OneTimeKeys,
1001    ) -> Result<PrekeyBundle, SessionCreationError> {
1002        let mut keys = key_map.iter();
1003
1004        let first_key = keys.next().ok_or_else(|| {
1005            SessionCreationError::OneTimeKeyMissing(
1006                device.user_id().to_owned(),
1007                device.device_id().into(),
1008            )
1009        })?;
1010
1011        let first_key_id = first_key.0.to_owned();
1012        let first_key = OneTimeKey::deserialize(first_key_id.algorithm(), first_key.1)?;
1013
1014        let result = match first_key {
1015            OneTimeKey::SignedKey(key) => Ok(PrekeyBundle::Olm3DH { key }),
1016        };
1017
1018        trace!(?result, "Finished searching for a valid pre-key bundle");
1019
1020        result
1021    }
1022
1023    /// Create a new session with another account given a one-time key and a
1024    /// device.
1025    ///
1026    /// Returns the newly created session or a `OlmSessionError` if creating a
1027    /// session failed.
1028    ///
1029    /// # Arguments
1030    /// * `device` - The other account's device.
1031    ///
1032    /// * `key_map` - A map from the algorithm and device ID to the one-time key
1033    ///   that the other account created and shared with us.
1034    ///
1035    /// * `our_device_keys` - Our own `DeviceKeys`, including cross-signing
1036    ///   signatures if applicable, for embedding in encrypted messages.
1037    #[allow(clippy::result_large_err)]
1038    pub fn create_outbound_session(
1039        &self,
1040        device: &DeviceData,
1041        key_map: &OneTimeKeys,
1042        our_device_keys: DeviceKeys,
1043    ) -> Result<Session, SessionCreationError> {
1044        let pre_key_bundle = Self::find_pre_key_bundle(device, key_map)?;
1045
1046        match pre_key_bundle {
1047            PrekeyBundle::Olm3DH { key } => {
1048                device.verify_one_time_key(&key).map_err(|error| {
1049                    SessionCreationError::InvalidSignature {
1050                        signing_key: device.ed25519_key().map(Box::new),
1051                        one_time_key: key.clone().into(),
1052                        error: error.into(),
1053                    }
1054                })?;
1055
1056                let identity_key = device.curve25519_key().ok_or_else(|| {
1057                    SessionCreationError::DeviceMissingCurveKey(
1058                        device.user_id().to_owned(),
1059                        device.device_id().into(),
1060                    )
1061                })?;
1062
1063                let is_fallback = key.fallback();
1064                let one_time_key = key.key();
1065                let config = device.olm_session_config();
1066
1067                Ok(self.create_outbound_session_helper(
1068                    config,
1069                    identity_key,
1070                    one_time_key,
1071                    is_fallback,
1072                    our_device_keys,
1073                ))
1074            }
1075        }
1076    }
1077
1078    /// Create a new session with another account given a pre-key Olm message.
1079    ///
1080    /// Returns the newly created session or a `OlmSessionError` if creating a
1081    /// session failed.
1082    ///
1083    /// # Arguments
1084    ///
1085    /// * `their_identity_key` - The other account's identity/curve25519 key.
1086    ///
1087    /// * `our_device_keys` - Our own `DeviceKeys`, including cross-signing
1088    ///   signatures if applicable, for embedding in encrypted messages.
1089    ///
1090    /// * `message` - A pre-key Olm message that was sent to us by the other
1091    ///   account.
1092    pub fn create_inbound_session(
1093        &mut self,
1094        their_identity_key: Curve25519PublicKey,
1095        our_device_keys: DeviceKeys,
1096        message: &PreKeyMessage,
1097    ) -> Result<InboundCreationResult, SessionCreationError> {
1098        Span::current().record("session_id", debug(message.session_id()));
1099        trace!("Creating a new Olm session from a pre-key message");
1100
1101        let result = self.inner.create_inbound_session(their_identity_key, message)?;
1102        let now = SecondsSinceUnixEpoch::now();
1103        let session_id = result.session.session_id();
1104
1105        debug!(session=?result.session, "Decrypted an Olm message from a new Olm session");
1106
1107        let session = Session {
1108            inner: Arc::new(Mutex::new(result.session)),
1109            session_id: session_id.into(),
1110            sender_key: their_identity_key,
1111            our_device_keys,
1112            created_using_fallback_key: false,
1113            creation_time: now,
1114            last_use_time: now,
1115        };
1116
1117        let plaintext = String::from_utf8_lossy(&result.plaintext).to_string();
1118
1119        Ok(InboundCreationResult { session, plaintext })
1120    }
1121
1122    #[cfg(any(test, feature = "testing"))]
1123    #[allow(dead_code)]
1124    /// Testing only helper to create a session for the given Account
1125    pub async fn create_session_for_test_helper(
1126        &mut self,
1127        other: &mut Account,
1128    ) -> (Session, Session) {
1129        use ruma::events::dummy::ToDeviceDummyEventContent;
1130
1131        other.generate_one_time_keys(1);
1132        let one_time_map = other.signed_one_time_keys();
1133        let device = DeviceData::from_account(other);
1134
1135        let mut our_session =
1136            self.create_outbound_session(&device, &one_time_map, self.device_keys()).unwrap();
1137
1138        other.mark_keys_as_published();
1139
1140        let message = our_session
1141            .encrypt(&device, "m.dummy", ToDeviceDummyEventContent::new(), None)
1142            .await
1143            .unwrap()
1144            .deserialize()
1145            .unwrap();
1146
1147        #[cfg(feature = "experimental-algorithms")]
1148        let content = if let ToDeviceEncryptedEventContent::OlmV2Curve25519AesSha2(c) = message {
1149            c
1150        } else {
1151            panic!("Invalid encrypted event algorithm {}", message.algorithm());
1152        };
1153
1154        #[cfg(not(feature = "experimental-algorithms"))]
1155        let ToDeviceEncryptedEventContent::OlmV1Curve25519AesSha2(content) = message else {
1156            panic!("Invalid encrypted event algorithm {}", message.algorithm());
1157        };
1158
1159        let OlmMessage::PreKey(prekey) = content.ciphertext else {
1160            panic!("Wrong Olm message type");
1161        };
1162
1163        let our_device = DeviceData::from_account(self);
1164        let other_session = other
1165            .create_inbound_session(
1166                our_device.curve25519_key().unwrap(),
1167                other.device_keys(),
1168                &prekey,
1169            )
1170            .unwrap();
1171
1172        (our_session, other_session.session)
1173    }
1174
1175    async fn decrypt_olm_helper(
1176        &mut self,
1177        store: &Store,
1178        sender: &UserId,
1179        sender_key: Curve25519PublicKey,
1180        ciphertext: &OlmMessage,
1181        decryption_settings: &DecryptionSettings,
1182    ) -> OlmResult<OlmDecryptionInfo> {
1183        let message_hash = OlmMessageHash::new(sender_key, ciphertext);
1184
1185        match self
1186            .decrypt_and_parse_olm_message(
1187                store,
1188                sender,
1189                sender_key,
1190                ciphertext,
1191                decryption_settings,
1192            )
1193            .await
1194        {
1195            Ok((session, result)) => {
1196                Ok(OlmDecryptionInfo { session, message_hash, result, inbound_group_session: None })
1197            }
1198            Err(OlmError::SessionWedged(user_id, sender_key)) => {
1199                if store.is_message_known(&message_hash).await? {
1200                    info!(?sender_key, "An Olm message got replayed, decryption failed");
1201                    Err(OlmError::ReplayedMessage(user_id, sender_key))
1202                } else {
1203                    Err(OlmError::SessionWedged(user_id, sender_key))
1204                }
1205            }
1206            Err(e) => Err(e),
1207        }
1208    }
1209
1210    #[cfg(feature = "experimental-algorithms")]
1211    async fn decrypt_olm_v2(
1212        &mut self,
1213        store: &Store,
1214        sender: &UserId,
1215        content: &OlmV2Curve25519AesSha2Content,
1216        decryption_settings: &DecryptionSettings,
1217    ) -> OlmResult<OlmDecryptionInfo> {
1218        self.decrypt_olm_helper(
1219            store,
1220            sender,
1221            content.sender_key,
1222            &content.ciphertext,
1223            decryption_settings,
1224        )
1225        .await
1226    }
1227
1228    #[instrument(skip_all, fields(sender, sender_key = ?content.sender_key))]
1229    async fn decrypt_olm_v1(
1230        &mut self,
1231        store: &Store,
1232        sender: &UserId,
1233        content: &OlmV1Curve25519AesSha2Content,
1234        decryption_settings: &DecryptionSettings,
1235    ) -> OlmResult<OlmDecryptionInfo> {
1236        if content.recipient_key != self.static_data.identity_keys.curve25519 {
1237            warn!("Olm event doesn't contain a ciphertext for our key");
1238
1239            Err(EventError::MissingCiphertext.into())
1240        } else {
1241            Box::pin(self.decrypt_olm_helper(
1242                store,
1243                sender,
1244                content.sender_key,
1245                &content.ciphertext,
1246                decryption_settings,
1247            ))
1248            .await
1249        }
1250    }
1251
1252    #[instrument(skip_all, fields(algorithm = ?event.content.algorithm()))]
1253    pub(crate) async fn decrypt_to_device_event(
1254        &mut self,
1255        store: &Store,
1256        event: &EncryptedToDeviceEvent,
1257        decryption_settings: &DecryptionSettings,
1258    ) -> OlmResult<OlmDecryptionInfo> {
1259        trace!("Decrypting a to-device event");
1260
1261        match &event.content {
1262            ToDeviceEncryptedEventContent::OlmV1Curve25519AesSha2(c) => {
1263                self.decrypt_olm_v1(store, &event.sender, c, decryption_settings).await
1264            }
1265            #[cfg(feature = "experimental-algorithms")]
1266            ToDeviceEncryptedEventContent::OlmV2Curve25519AesSha2(c) => {
1267                self.decrypt_olm_v2(store, &event.sender, c, decryption_settings).await
1268            }
1269            ToDeviceEncryptedEventContent::Unknown(_) => {
1270                warn!(
1271                    "Error decrypting an to-device event, unsupported \
1272                    encryption algorithm"
1273                );
1274
1275                Err(EventError::UnsupportedAlgorithm.into())
1276            }
1277        }
1278    }
1279
1280    /// Handles a response to a /keys/upload request.
1281    pub fn receive_keys_upload_response(
1282        &mut self,
1283        response: &upload_keys::v3::Response,
1284    ) -> OlmResult<()> {
1285        if !self.shared() {
1286            debug!("Marking account as shared");
1287        }
1288        self.mark_as_shared();
1289
1290        debug!("Marking one-time keys as published");
1291        // First mark the current keys as published, as updating the key counts might
1292        // generate some new keys if we're still below the limit.
1293        self.mark_keys_as_published();
1294        self.update_key_counts(&response.one_time_key_counts, None);
1295
1296        Ok(())
1297    }
1298
1299    /// Try to decrypt an olm message, creating a new session if necessary.
1300    async fn decrypt_olm_message(
1301        &mut self,
1302        store: &Store,
1303        sender: &UserId,
1304        sender_key: Curve25519PublicKey,
1305        message: &OlmMessage,
1306    ) -> Result<(SessionType, String), OlmError> {
1307        let existing_sessions = store.get_sessions(&sender_key.to_base64()).await?;
1308
1309        match message {
1310            OlmMessage::Normal(_) => {
1311                let mut errors_by_olm_session = Vec::new();
1312
1313                if let Some(sessions) = existing_sessions {
1314                    // Try to decrypt the message using each Session we share with the
1315                    // given curve25519 sender key.
1316                    for session in sessions.lock().await.iter_mut() {
1317                        match session.decrypt(message).await {
1318                            Ok(p) => {
1319                                // success!
1320                                return Ok((SessionType::Existing(session.clone()), p));
1321                            }
1322
1323                            Err(e) => {
1324                                // An error here is completely normal, after all we don't know
1325                                // which session was used to encrypt a message.
1326                                // We keep hold of the error, so that if *all* sessions fail to
1327                                // decrypt, we can log something useful.
1328                                errors_by_olm_session.push((session.session_id().to_owned(), e));
1329                            }
1330                        }
1331                    }
1332                }
1333
1334                warn!(
1335                    ?errors_by_olm_session,
1336                    "Failed to decrypt a non-pre-key message with all available sessions"
1337                );
1338                Err(OlmError::SessionWedged(sender.to_owned(), sender_key))
1339            }
1340
1341            OlmMessage::PreKey(prekey_message) => {
1342                // First try to decrypt using an existing session.
1343                if let Some(sessions) = existing_sessions {
1344                    for session in sessions.lock().await.iter_mut() {
1345                        if prekey_message.session_id() != session.session_id() {
1346                            // wrong session
1347                            continue;
1348                        }
1349
1350                        if let Ok(p) = session.decrypt(message).await {
1351                            // success!
1352                            return Ok((SessionType::Existing(session.clone()), p));
1353                        }
1354
1355                        // The message was intended for this session, but we weren't able to
1356                        // decrypt it.
1357                        //
1358                        // There's no point trying any other sessions, nor should we try to
1359                        // create a new one since we have already previously created a `Session`
1360                        // with the same keys.
1361                        //
1362                        // (Attempts to create a new session would likely fail anyway since the
1363                        // corresponding one-time key would've been already used up in the
1364                        // previous session creation operation. The one exception where this
1365                        // would not be so is if the fallback key was used for creating the
1366                        // session in lieu of an OTK.)
1367
1368                        warn!(
1369                            session_id = session.session_id(),
1370                            "Failed to decrypt a pre-key message with the corresponding session"
1371                        );
1372
1373                        return Err(OlmError::SessionWedged(
1374                            session.our_device_keys.user_id.to_owned(),
1375                            session.sender_key(),
1376                        ));
1377                    }
1378                }
1379
1380                let device_keys = store.get_own_device().await?.as_device_keys().clone();
1381                let result =
1382                    match self.create_inbound_session(sender_key, device_keys, prekey_message) {
1383                        Ok(r) => r,
1384                        Err(e) => {
1385                            warn!(
1386                                "Failed to create a new Olm session from a pre-key message: {e:?}"
1387                            );
1388                            return Err(OlmError::SessionWedged(sender.to_owned(), sender_key));
1389                        }
1390                    };
1391
1392                // We need to add the new session to the session cache, otherwise
1393                // we might try to create the same session again.
1394                // TODO: separate the session cache from the storage so we only add
1395                // it to the cache but don't store it.
1396                let mut changes =
1397                    Changes { sessions: vec![result.session.clone()], ..Default::default() };
1398
1399                // Any new Olm session will bump the Olm wedging index for the
1400                // sender's device, if we have their device, which will cause us
1401                // to re-send existing Megolm sessions to them the next time we
1402                // use the session.  If we don't have their device, this means
1403                // that we haven't tried to send them any Megolm sessions yet,
1404                // so we don't need to worry about it.
1405                if let Some(device) = store.get_device_from_curve_key(sender, sender_key).await? {
1406                    let mut device_data = device.inner;
1407                    device_data.olm_wedging_index.increment();
1408
1409                    changes.devices =
1410                        DeviceChanges { changed: vec![device_data], ..Default::default() };
1411                }
1412
1413                store.save_changes(changes).await?;
1414
1415                Ok((SessionType::New(result.session), result.plaintext))
1416            }
1417        }
1418    }
1419
1420    /// Decrypt an Olm message, creating a new Olm session if necessary, and
1421    /// parse the result.
1422    #[instrument(skip(self, store), fields(session, session_id))]
1423    async fn decrypt_and_parse_olm_message(
1424        &mut self,
1425        store: &Store,
1426        sender: &UserId,
1427        sender_key: Curve25519PublicKey,
1428        message: &OlmMessage,
1429        decryption_settings: &DecryptionSettings,
1430    ) -> OlmResult<(SessionType, DecryptionResult)> {
1431        let (session, plaintext) =
1432            self.decrypt_olm_message(store, sender, sender_key, message).await?;
1433
1434        trace!("Successfully decrypted an Olm message");
1435
1436        match self
1437            .parse_decrypted_to_device_event(
1438                store,
1439                sender,
1440                sender_key,
1441                plaintext,
1442                decryption_settings,
1443            )
1444            .await
1445        {
1446            Ok(result) => Ok((session, result)),
1447            Err(e) => {
1448                // We might have created a new session but decryption might still
1449                // have failed, store it for the error case here, this is fine
1450                // since we don't expect this to happen often or at all.
1451                match session {
1452                    SessionType::New(s) | SessionType::Existing(s) => {
1453                        store.save_sessions(&[s]).await?;
1454                    }
1455                }
1456
1457                warn!(
1458                    error = ?e,
1459                    "A to-device message was successfully decrypted but \
1460                    parsing and checking the event fields failed"
1461                );
1462
1463                Err(e)
1464            }
1465        }
1466    }
1467
1468    /// Parse the decrypted plaintext as JSON and verify that it wasn't
1469    /// forwarded by a third party.
1470    ///
1471    /// These checks are mandated by the spec[1]:
1472    ///
1473    /// > Other properties are included in order to prevent an attacker from
1474    /// > publishing someone else's Curve25519 keys as their own and
1475    /// > subsequently claiming to have sent messages which they didn't.
1476    /// > sender must correspond to the user who sent the event, recipient to
1477    /// > the local user, and recipient_keys to the local Ed25519 key.
1478    ///
1479    /// # Arguments
1480    ///
1481    /// * `sender` -  The `sender` field from the top level of the received
1482    ///   event.
1483    /// * `sender_key` - The `sender_key` from the cleartext `content` of the
1484    ///   received event (which should also have been used to find or establish
1485    ///   the Olm session that was used to decrypt the event -- so it is
1486    ///   guaranteed to be correct).
1487    /// * `plaintext` - The decrypted content of the event.
1488    async fn parse_decrypted_to_device_event(
1489        &self,
1490        store: &Store,
1491        sender: &UserId,
1492        sender_key: Curve25519PublicKey,
1493        plaintext: String,
1494        decryption_settings: &DecryptionSettings,
1495    ) -> OlmResult<DecryptionResult> {
1496        let event: Box<AnyDecryptedOlmEvent> = serde_json::from_str(&plaintext)?;
1497        let identity_keys = &self.static_data.identity_keys;
1498
1499        if event.recipient() != self.static_data.user_id {
1500            Err(EventError::MismatchedSender(
1501                event.recipient().to_owned(),
1502                self.static_data.user_id.clone(),
1503            )
1504            .into())
1505        }
1506        // Check that the `sender` in the decrypted to-device event matches that at the
1507        // top level of the encrypted event.
1508        else if event.sender() != sender {
1509            Err(EventError::MismatchedSender(event.sender().to_owned(), sender.to_owned()).into())
1510        } else if identity_keys.ed25519 != event.recipient_keys().ed25519 {
1511            Err(EventError::MismatchedKeys(
1512                identity_keys.ed25519.into(),
1513                event.recipient_keys().ed25519.into(),
1514            )
1515            .into())
1516        } else {
1517            let sender_device = Self::get_event_sender_device(store, sender_key, &event).await?;
1518            let encryption_info = Self::get_olm_encryption_info(sender_key, sender, &sender_device);
1519
1520            let result = DecryptionResult {
1521                event,
1522                raw_event: Raw::from_json(RawJsonValue::from_string(plaintext)?),
1523                sender_key,
1524                encryption_info,
1525            };
1526
1527            // Return an error if the sender is unverified (and we care)
1528            if !self.is_from_verified_device_or_allowed_type(decryption_settings, &result) {
1529                Err(OlmError::UnverifiedSenderDevice)
1530            } else {
1531                // Sender is ok - return the decrypted event
1532                Ok(result)
1533            }
1534        }
1535    }
1536
1537    /// Look up the [`Device`] that sent us a successfully-decrypted event.
1538    ///
1539    /// We first look for the sender device in our store; if it is found then we
1540    /// return that (having checked that the keys match). If the device is
1541    /// not found in the store, we return the details
1542    /// from `sender_device_keys`, if present. If the device is not in the
1543    /// store, and the event lacks `sender_device_keys`, an error is returned.
1544    ///
1545    /// Also validates the `sender_device_keys` field, if present, regardless of
1546    /// whether it is used.
1547    ///
1548    /// `m.room_key` events are special-cased and return `None`: we look up
1549    /// their devices later on.
1550    async fn get_event_sender_device(
1551        store: &Store,
1552        sender_key: Curve25519PublicKey,
1553        event: &AnyDecryptedOlmEvent,
1554    ) -> OlmResult<Option<Device>> {
1555        // If the event contained sender_device_keys, check them now.
1556        // WARN: If you move or modify this check, ensure that the code below is still
1557        // valid. The processing of the historic room key bundle depends on this being
1558        // here.
1559        let sender_device_keys = Self::check_sender_device_keys(event, sender_key)?;
1560        if let AnyDecryptedOlmEvent::RoomKey(_) = event {
1561            // If this event is an `m.room_key` event, defer the check for
1562            // the Ed25519 key of the sender until we decrypt room events.
1563            // This ensures that we receive the room key even if we don't
1564            // have access to the device.
1565            return Ok(None);
1566        }
1567
1568        // MSC4268 requires room key bundle events to have a `sender_device_keys` field.
1569        // Enforce that now.
1570        if let AnyDecryptedOlmEvent::RoomKeyBundle(_) = event {
1571            sender_device_keys.ok_or(EventError::MissingSigningKey).inspect_err(|_| {
1572                warn!("The room key bundle was missing the sender device keys in the event")
1573            })?;
1574        }
1575
1576        // For event types other than `m.room_key`, we need to look up the device in the
1577        // database irrespective of whether the `sender_device_keys` field is
1578        // present in the event, because it may have been marked as "locally
1579        // trusted" in the database.
1580        let store_device = store.get_device_from_curve_key(event.sender(), sender_key).await?;
1581
1582        match (store_device, sender_device_keys) {
1583            // If the device is in the database, it had better have an Ed25519 key which
1584            // matches that in the event.
1585            (Some(device), _) => {
1586                let key = device.ed25519_key().ok_or(EventError::MissingSigningKey)?;
1587                if key != event.keys().ed25519 {
1588                    return Err(EventError::MismatchedKeys(
1589                        key.into(),
1590                        event.keys().ed25519.into(),
1591                    )
1592                    .into());
1593                }
1594                Ok(Some(device))
1595            }
1596
1597            (None, Some(sender_device_keys)) => {
1598                // We have already validated the signature on `sender_device_keys`, so this
1599                // try_into cannot fail.
1600                let sender_device_data = sender_device_keys.try_into().expect("Conversion of DeviceKeys to DeviceData failed despite the signature already having been checked");
1601                Ok(Some(store.wrap_device_data(sender_device_data).await?))
1602            }
1603
1604            (None, None) => Err(OlmError::EventError(EventError::MissingSigningKey)),
1605        }
1606    }
1607
1608    /// Return true if:
1609    ///
1610    /// * the sending device is verified, or
1611    /// * the event type is one of those we allow to be sent from unverified
1612    ///   devices, or
1613    /// * we are not in "exclude_insecure_devices" mode, so everything is
1614    ///   allowed.
1615    ///
1616    /// Return false if:
1617    ///
1618    /// * we are in "exclude_insecure_devices" mode AND the sending device is
1619    ///   unverified.
1620    fn is_from_verified_device_or_allowed_type(
1621        &self,
1622        decryption_settings: &DecryptionSettings,
1623        result: &DecryptionResult,
1624    ) -> bool {
1625        let event_type = result.event.event_type();
1626
1627        // If we're in "exclude insecure devices" mode, we prevent most
1628        // to-device events with unverified senders from being allowed
1629        // through here, but there are some exceptions:
1630        //
1631        // * m.room_key - we hold on to these until later, so if the sender becomes
1632        //   verified later we can still use the key.
1633        //
1634        // * m.room_key_request, m.room_key.withheld, m.key.verification.*,
1635        //   m.secret.request - these are allowed as plaintext events, so we also allow
1636        //   them encrypted from insecure devices. Note: the list of allowed types here
1637        //   should match with what is allowed in handle_to_device_event.
1638        match event_type {
1639            "m.room_key"
1640            | "m.room_key.withheld"
1641            | "m.room_key_request"
1642            | "m.secret.request"
1643            | "m.key.verification.key"
1644            | "m.key.verification.mac"
1645            | "m.key.verification.done"
1646            | "m.key.verification.ready"
1647            | "m.key.verification.start"
1648            | "m.key.verification.accept"
1649            | "m.key.verification.cancel"
1650            | "m.key.verification.request" => {
1651                // This is one of the exception types - we allow it even if the sender device is
1652                // not verified.
1653                true
1654            }
1655            _ => {
1656                // This is not an exception type - check for "exclude insecure devices" mode,
1657                // and whether the sender is verified.
1658                satisfies_sender_trust_requirement(
1659                    &result.encryption_info,
1660                    &decryption_settings.sender_device_trust_requirement,
1661                )
1662            }
1663        }
1664    }
1665
1666    /// Gets the EncryptionInfo for a successfully decrypted to-device message
1667    /// that have passed the mismatched sender_key/user_id validation.
1668    ///
1669    /// `sender_device` is optional because for some to-device messages we defer
1670    /// the check for the ed25519 key, in that case the
1671    /// `verification_state` will have a `MissingDevice` link problem.
1672    fn get_olm_encryption_info(
1673        sender_key: Curve25519PublicKey,
1674        sender_id: &UserId,
1675        sender_device: &Option<Device>,
1676    ) -> EncryptionInfo {
1677        let verification_state = sender_device
1678            .as_ref()
1679            .map(|device| {
1680                if device.is_verified() {
1681                    // The device is locally verified or signed by a verified user
1682                    VerificationState::Verified
1683                } else if device.is_cross_signed_by_owner() {
1684                    // The device is not verified, but it is signed by its owner
1685                    if device
1686                        .device_owner_identity
1687                        .as_ref()
1688                        .expect("A device cross-signed by the owner must have an owner identity")
1689                        .was_previously_verified()
1690                    {
1691                        VerificationState::Unverified(VerificationLevel::VerificationViolation)
1692                    } else {
1693                        VerificationState::Unverified(VerificationLevel::UnverifiedIdentity)
1694                    }
1695                } else {
1696                    // No identity or not signed
1697                    VerificationState::Unverified(VerificationLevel::UnsignedDevice)
1698                }
1699            })
1700            .unwrap_or(VerificationState::Unverified(VerificationLevel::None(
1701                DeviceLinkProblem::MissingDevice,
1702            )));
1703
1704        EncryptionInfo {
1705            sender: sender_id.to_owned(),
1706            sender_device: sender_device.as_ref().map(|d| d.device_id().to_owned()),
1707            forwarder: None,
1708            algorithm_info: AlgorithmInfo::OlmV1Curve25519AesSha2 {
1709                curve25519_public_key_base64: sender_key.to_base64(),
1710            },
1711            verification_state,
1712        }
1713    }
1714
1715    /// If the plaintext of the decrypted message includes a
1716    /// `sender_device_keys` property per [MSC4147], check that it is valid.
1717    ///
1718    /// In particular, we check that:
1719    ///
1720    ///  * The Curve25519 key in the `sender_device_keys` matches that used to
1721    ///    establish the Olm session that was used to decrypt the event.
1722    ///
1723    ///  * The `sender_device_keys` contains a valid self-signature by the
1724    ///    Ed25519 key in the device data.
1725    ///
1726    ///  * The Ed25519 key in the device data matches that in the `keys` field
1727    ///    in the event, for consistency and sanity.
1728    ///
1729    /// The first two checks are sufficient to bind together the Ed25519 and
1730    /// Curve25519 keys:
1731    ///
1732    ///  * Only the holder of the secret part of the Curve25519 key that was
1733    ///    used to construct the Olm session (the 'owner' of that key) can
1734    ///    encrypt the device data in that Olm session. By including the Ed25519
1735    ///    key in the device data, the owner of the Curve25519 key is claiming
1736    ///    ownership of the Ed25519 key.
1737    ///
1738    ///  * Only the owner of the Ed25519 key can construct the self-signature on
1739    ///    the device data. By including the Curve25519 key in the device data
1740    ///    and then signing it, the owner of the Ed25519 key is claiming
1741    ///    ownership of the Curve25519 key.
1742    ///
1743    ///  * Since we now have claims in both directions, the two key owners must
1744    ///    either be the same entity, or working in sufficiently close
1745    ///    collaboration that they can be treated as such.
1746    ///
1747    /// # Arguments
1748    ///
1749    /// * `event` - The decrypted and deserialized plaintext of the event.
1750    /// * `sender_key` - The Curve25519 key that the sender used to establish
1751    ///   the Olm session that was used to decrypt the event.
1752    ///
1753    /// # Returns
1754    ///
1755    /// A reference to the `sender_device_keys` in the event, if it exists and
1756    /// is valid.
1757    ///
1758    /// [MSC4147]: https://github.com/matrix-org/matrix-spec-proposals/pull/4147
1759    fn check_sender_device_keys(
1760        event: &AnyDecryptedOlmEvent,
1761        sender_key: Curve25519PublicKey,
1762    ) -> OlmResult<Option<&DeviceKeys>> {
1763        let Some(sender_device_keys) = event.sender_device_keys() else {
1764            return Ok(None);
1765        };
1766
1767        // Check the signature within the device_keys structure
1768        sender_device_keys.check_self_signature().map_err(|err| {
1769            warn!(
1770                "Received a to-device message with sender_device_keys with \
1771                 invalid signature: {err:?}",
1772            );
1773            OlmError::EventError(EventError::InvalidSenderDeviceKeys)
1774        })?;
1775
1776        // Check that the Ed25519 key in the sender_device_keys matches the `ed25519`
1777        // key in the `keys` field in the event.
1778        if sender_device_keys.ed25519_key() != Some(event.keys().ed25519) {
1779            warn!(
1780                "Received a to-device message with sender_device_keys with incorrect \
1781                 ed25519 key: expected {:?}, got {:?}",
1782                event.keys().ed25519,
1783                sender_device_keys.ed25519_key(),
1784            );
1785            return Err(OlmError::EventError(EventError::InvalidSenderDeviceKeys));
1786        }
1787
1788        // Check that the Curve25519 key in the sender_device_keys matches the key that
1789        // was used for the Olm session.
1790        if sender_device_keys.curve25519_key() != Some(sender_key) {
1791            warn!(
1792                "Received a to-device message with sender_device_keys with incorrect \
1793                 curve25519 key: expected {sender_key:?}, got {:?}",
1794                sender_device_keys.curve25519_key(),
1795            );
1796            return Err(OlmError::EventError(EventError::InvalidSenderDeviceKeys));
1797        }
1798
1799        Ok(Some(sender_device_keys))
1800    }
1801
1802    /// Internal use only.
1803    ///
1804    /// Cloning should only be done for testing purposes or when we are certain
1805    /// that we don't want the inner state to be shared.
1806    #[doc(hidden)]
1807    pub fn deep_clone(&self) -> Self {
1808        // `vodozemac::Account` isn't really cloneable, but... Don't tell anyone.
1809        Self::from_pickle(self.pickle()).unwrap()
1810    }
1811}
1812
1813impl PartialEq for Account {
1814    fn eq(&self, other: &Self) -> bool {
1815        self.identity_keys() == other.identity_keys() && self.shared() == other.shared()
1816    }
1817}
1818
1819/// Calculate the shared history flag from the history visibility as defined in
1820/// [MSC3061]
1821///
1822/// The MSC defines that the shared history flag should be set to true when the
1823/// history visibility setting is set to `shared` or `world_readable`:
1824///
1825/// > A room key is flagged as having been used for shared history when it was
1826/// > used to encrypt a message while the room's history visibility setting
1827/// > was set to world_readable or shared.
1828///
1829/// In all other cases, even if we encounter a custom history visibility, we
1830/// should return false:
1831///
1832/// > If the client does not have an m.room.history_visibility state event for
1833/// > the room, or its value is not understood, the client should treat it as if
1834/// > its value is joined for the purposes of determining whether the key is
1835/// > used for shared history.
1836///
1837/// [MSC3061]: https://github.com/matrix-org/matrix-spec-proposals/pull/3061
1838pub(crate) fn shared_history_from_history_visibility(
1839    history_visibility: &HistoryVisibility,
1840) -> bool {
1841    match history_visibility {
1842        HistoryVisibility::Shared | HistoryVisibility::WorldReadable => true,
1843        HistoryVisibility::Invited | HistoryVisibility::Joined | _ => false,
1844    }
1845}
1846
1847/// Expand the pickle key for an older version of dehydrated devices
1848///
1849/// The `org.matrix.msc3814.v1.olm` variant of dehydrated devices used the
1850/// libolm Account pickle format for the dehydrated device. The libolm pickle
1851/// encryption scheme uses HKDF to deterministically expand an input key
1852/// material, usually 32 bytes, into a AES key, MAC key, and the initialization
1853/// vector (IV).
1854///
1855/// This means that the same input key material will always end up producing the
1856/// same AES key, and IV.
1857///
1858/// This encryption scheme is used in the Olm double ratchet and was designed to
1859/// minimize the size of the ciphertext. As a tradeof, it requires a unique
1860/// input key material for each plaintext that gets encrypted, otherwise IV
1861/// reuse happens.
1862///
1863/// To combat the IV reuse, we're going to create a per-dehydrated-device unique
1864/// pickle key by expanding the key itself with the device ID used as the salt.
1865fn expand_legacy_pickle_key(key: &[u8; 32], device_id: &DeviceId) -> Box<[u8; 32]> {
1866    let kdf: Hkdf<Sha256> = Hkdf::new(Some(device_id.as_bytes()), key);
1867    let mut key = Box::new([0u8; 32]);
1868
1869    kdf.expand(b"dehydrated-device-pickle-key", key.as_mut_slice())
1870        .expect("We should be able to expand the 32 byte pickle key");
1871
1872    key
1873}
1874
1875/// Does the to-device event satisfy the sender trust requirement from the
1876/// decryption settings?
1877fn satisfies_sender_trust_requirement(
1878    encryption_info: &EncryptionInfo,
1879    trust_requirement: &TrustRequirement,
1880) -> bool {
1881    trace!(
1882        verification_state = ?encryption_info.verification_state,
1883        ?trust_requirement, "check_to_device_sender_trust_requirement",
1884    );
1885
1886    match (&encryption_info.verification_state, trust_requirement) {
1887        // If we don't care, everything is OK.
1888        (_, TrustRequirement::Untrusted) => true,
1889
1890        // Verified is OK whatever our requirements are.
1891        (VerificationState::Verified, _) => true,
1892
1893        // We do care, and we are not fully verified: check more deeply.
1894        // (Note that for to-device messages the legacy trust requirement is not relevant.)
1895        (
1896            VerificationState::Unverified(verification_level),
1897            TrustRequirement::CrossSignedOrLegacy | TrustRequirement::CrossSigned,
1898        ) => match verification_level {
1899            // The device is signed but the identity is only pinned - this is fine.
1900            VerificationLevel::UnverifiedIdentity => true,
1901
1902            // The device is unsigned or missing, or the user is in verification violation,
1903            // or the sender is mismatched: this is not fine.
1904            VerificationLevel::UnsignedDevice
1905            | VerificationLevel::None(_)
1906            | VerificationLevel::VerificationViolation
1907            | VerificationLevel::MismatchedSender => false,
1908        },
1909    }
1910}
1911
1912#[cfg(test)]
1913mod tests {
1914    use std::{
1915        collections::{BTreeMap, BTreeSet},
1916        ops::Deref,
1917        time::Duration,
1918    };
1919
1920    use anyhow::Result;
1921    use matrix_sdk_test::async_test;
1922    use ruma::{
1923        DeviceId, MilliSecondsSinceUnixEpoch, OneTimeKeyAlgorithm, OneTimeKeyId, UserId, device_id,
1924        events::room::history_visibility::HistoryVisibility, room_id, user_id,
1925    };
1926    use serde_json::json;
1927
1928    use super::Account;
1929    use crate::{
1930        DeviceData, EncryptionSettings,
1931        olm::{SignedJsonObject, account::shared_history_from_history_visibility},
1932        types::{DeviceKeys, SignedKey},
1933    };
1934
1935    fn user_id() -> &'static UserId {
1936        user_id!("@alice:localhost")
1937    }
1938
1939    fn device_id() -> &'static DeviceId {
1940        device_id!("DEVICEID")
1941    }
1942
1943    #[test]
1944    fn test_one_time_key_creation() -> Result<()> {
1945        let mut account = Account::with_device_id(user_id(), device_id());
1946
1947        let (_, one_time_keys, _) = account.keys_for_upload();
1948        assert!(!one_time_keys.is_empty());
1949
1950        let (_, second_one_time_keys, _) = account.keys_for_upload();
1951        assert!(!second_one_time_keys.is_empty());
1952
1953        let one_time_key_ids: BTreeSet<&OneTimeKeyId> =
1954            one_time_keys.keys().map(Deref::deref).collect();
1955        let second_one_time_key_ids: BTreeSet<&OneTimeKeyId> =
1956            second_one_time_keys.keys().map(Deref::deref).collect();
1957
1958        assert_eq!(one_time_key_ids, second_one_time_key_ids);
1959
1960        account.mark_keys_as_published();
1961        account.update_uploaded_key_count(50);
1962        account.generate_one_time_keys_if_needed();
1963
1964        let (_, third_one_time_keys, _) = account.keys_for_upload();
1965        assert!(third_one_time_keys.is_empty());
1966
1967        account.update_uploaded_key_count(0);
1968        account.generate_one_time_keys_if_needed();
1969
1970        let (_, fourth_one_time_keys, _) = account.keys_for_upload();
1971        assert!(!fourth_one_time_keys.is_empty());
1972
1973        let fourth_one_time_key_ids: BTreeSet<&OneTimeKeyId> =
1974            fourth_one_time_keys.keys().map(Deref::deref).collect();
1975
1976        assert_ne!(one_time_key_ids, fourth_one_time_key_ids);
1977        Ok(())
1978    }
1979
1980    #[test]
1981    fn test_fallback_key_creation() -> Result<()> {
1982        let mut account = Account::with_device_id(user_id(), device_id());
1983
1984        let (_, _, fallback_keys) = account.keys_for_upload();
1985
1986        // We don't create fallback keys since we don't know if the server
1987        // supports them, we need to receive a sync response to decide if we're
1988        // going to create them or not.
1989        assert!(
1990            fallback_keys.is_empty(),
1991            "We should not upload fallback keys until we know if the server supports them."
1992        );
1993
1994        let one_time_keys = BTreeMap::from([(OneTimeKeyAlgorithm::SignedCurve25519, 50u8.into())]);
1995
1996        // A `None` here means that the server doesn't support fallback keys, no
1997        // fallback key gets uploaded.
1998        account.update_key_counts(&one_time_keys, None);
1999        let (_, _, fallback_keys) = account.keys_for_upload();
2000        assert!(
2001            fallback_keys.is_empty(),
2002            "We should not upload a fallback key if we're certain that the server doesn't support \
2003             them."
2004        );
2005
2006        // The empty array means that the server supports fallback keys but
2007        // there isn't a unused fallback key on the server. This time we upload
2008        // a fallback key.
2009        let unused_fallback_keys = &[];
2010        account.update_key_counts(&one_time_keys, Some(unused_fallback_keys.as_ref()));
2011        let (_, _, fallback_keys) = account.keys_for_upload();
2012        assert!(
2013            !fallback_keys.is_empty(),
2014            "We should upload the initial fallback key if the server supports them."
2015        );
2016        account.mark_keys_as_published();
2017
2018        // There's no unused fallback key on the server, but our initial fallback key
2019        // did not yet expire.
2020        let unused_fallback_keys = &[];
2021        account.update_key_counts(&one_time_keys, Some(unused_fallback_keys.as_ref()));
2022        let (_, _, fallback_keys) = account.keys_for_upload();
2023        assert!(
2024            fallback_keys.is_empty(),
2025            "We should not upload new fallback keys unless our current fallback key expires."
2026        );
2027
2028        let fallback_key_timestamp =
2029            account.fallback_creation_timestamp.unwrap().to_system_time().unwrap()
2030                - Duration::from_secs(3600 * 24 * 30);
2031
2032        account.fallback_creation_timestamp =
2033            Some(MilliSecondsSinceUnixEpoch::from_system_time(fallback_key_timestamp).unwrap());
2034
2035        account.update_key_counts(&one_time_keys, None);
2036        let (_, _, fallback_keys) = account.keys_for_upload();
2037        assert!(
2038            !fallback_keys.is_empty(),
2039            "Now that our fallback key has expired, we should try to upload a new one, even if the \
2040             server supposedly doesn't support fallback keys anymore"
2041        );
2042
2043        Ok(())
2044    }
2045
2046    #[test]
2047    fn test_fallback_key_signing() -> Result<()> {
2048        let key = vodozemac::Curve25519PublicKey::from_base64(
2049            "7PUPP6Ijt5R8qLwK2c8uK5hqCNF9tOzWYgGaAay5JBs",
2050        )?;
2051        let account = Account::with_device_id(user_id(), device_id());
2052
2053        let key = account.sign_key(key, true);
2054
2055        let canonical_key = key.to_canonical_json()?;
2056
2057        assert_eq!(
2058            canonical_key,
2059            "{\"fallback\":true,\"key\":\"7PUPP6Ijt5R8qLwK2c8uK5hqCNF9tOzWYgGaAay5JBs\"}"
2060        );
2061
2062        account
2063            .has_signed_raw(key.signatures(), &canonical_key)
2064            .expect("Couldn't verify signature");
2065
2066        let device = DeviceData::from_account(&account);
2067        device.verify_one_time_key(&key).expect("The device can verify its own signature");
2068
2069        Ok(())
2070    }
2071
2072    #[test]
2073    fn test_account_and_device_creation_timestamp() -> Result<()> {
2074        let now = MilliSecondsSinceUnixEpoch::now();
2075        let account = Account::with_device_id(user_id(), device_id());
2076        let then = MilliSecondsSinceUnixEpoch::now();
2077
2078        assert!(account.creation_local_time() >= now);
2079        assert!(account.creation_local_time() <= then);
2080
2081        let device = DeviceData::from_account(&account);
2082        assert_eq!(account.creation_local_time(), device.first_time_seen_ts());
2083
2084        Ok(())
2085    }
2086
2087    #[async_test]
2088    async fn test_fallback_key_signature_verification() -> Result<()> {
2089        let fallback_key = json!({
2090            "fallback": true,
2091            "key": "XPFqtLvBepBmW6jSAbBuJbhEpprBhQOX1IjUu+cnMF4",
2092            "signatures": {
2093                "@dkasak_c:matrix.org": {
2094                    "ed25519:EXPDYDPWZH": "RJCBMJPL5hvjxgq8rmLmqkNOuPsaan7JeL1wsE+gW6R39G894lb2sBmzapHeKCn/KFjmkonPLkICApRDS+zyDw"
2095                }
2096            }
2097        });
2098
2099        let device_keys = json!({
2100            "algorithms": [
2101                "m.olm.v1.curve25519-aes-sha2",
2102                "m.megolm.v1.aes-sha2"
2103            ],
2104            "device_id": "EXPDYDPWZH",
2105            "keys": {
2106                "curve25519:EXPDYDPWZH": "k7f3igo0Vrdm88JSSA5d3OCuUfHYELChB2b57aOROB8",
2107                "ed25519:EXPDYDPWZH": "GdjYI8fxs175gSpYRJkyN6FRfvcyTsNOhJ2OR/Ggp+E"
2108            },
2109            "signatures": {
2110                "@dkasak_c:matrix.org": {
2111                    "ed25519:EXPDYDPWZH": "kzrtfQMbJXWXQ1uzhybtwFnGk0JJBS4Mg8VPMusMu6U8MPJccwoHVZKo5+owuHTzIodI+GZYqLmMSzvfvsChAA"
2112                }
2113            },
2114            "user_id": "@dkasak_c:matrix.org",
2115            "unsigned": {}
2116        });
2117
2118        let device_keys: DeviceKeys = serde_json::from_value(device_keys).unwrap();
2119        let device = DeviceData::try_from(&device_keys).unwrap();
2120        let fallback_key: SignedKey = serde_json::from_value(fallback_key).unwrap();
2121
2122        device
2123            .verify_one_time_key(&fallback_key)
2124            .expect("The fallback key should pass the signature verification");
2125
2126        Ok(())
2127    }
2128
2129    #[test]
2130    fn test_shared_history_flag_from_history_visibility() {
2131        assert!(
2132            shared_history_from_history_visibility(&HistoryVisibility::WorldReadable),
2133            "The world readable visibility should set the shared history flag to true"
2134        );
2135
2136        assert!(
2137            shared_history_from_history_visibility(&HistoryVisibility::Shared),
2138            "The shared visibility should set the shared history flag to true"
2139        );
2140
2141        assert!(
2142            !shared_history_from_history_visibility(&HistoryVisibility::Joined),
2143            "The joined visibility should set the shared history flag to false"
2144        );
2145
2146        assert!(
2147            !shared_history_from_history_visibility(&HistoryVisibility::Invited),
2148            "The invited visibility should set the shared history flag to false"
2149        );
2150
2151        let visibility = HistoryVisibility::from("custom_visibility");
2152        assert!(
2153            !shared_history_from_history_visibility(&visibility),
2154            "A custom visibility should set the shared history flag to false"
2155        );
2156    }
2157
2158    #[async_test]
2159    async fn test_shared_history_set_when_creating_group_sessions() {
2160        let account = Account::new(user_id());
2161        let room_id = room_id!("!room:id");
2162        let settings = EncryptionSettings {
2163            history_visibility: HistoryVisibility::Shared,
2164            ..Default::default()
2165        };
2166
2167        let (_, session) = account
2168            .create_group_session_pair(room_id, settings, Default::default())
2169            .await
2170            .expect("We should be able to create a group session pair");
2171
2172        assert!(
2173            session.shared_history(),
2174            "The shared history flag should have been set when we created the new session"
2175        );
2176    }
2177}