Skip to main content

matrix_sdk_common/
deserialized_responses.rs

1// Copyright 2023 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::{collections::BTreeMap, fmt, ops::Not, sync::Arc};
16
17use ruma::{
18    DeviceKeyAlgorithm, EventId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedEventId,
19    OwnedUserId,
20    events::{
21        AnySyncMessageLikeEvent, AnySyncTimelineEvent, AnyTimelineEvent, AnyToDeviceEvent,
22        MessageLikeEventType, room::encrypted::EncryptedEventScheme,
23    },
24    push::Action,
25    serde::{
26        AsRefStr, AsStrAsRefStr, DebugAsRefStr, DeserializeFromCowStr, FromString, JsonObject, Raw,
27        SerializeAsRefStr,
28    },
29};
30use serde::{Deserialize, Serialize};
31use tracing::warn;
32#[cfg(target_family = "wasm")]
33use wasm_bindgen::prelude::*;
34
35use crate::{
36    debug::{DebugRawEvent, DebugStructExt},
37    serde_helpers::{extract_bundled_thread, extract_timestamp},
38};
39
40const AUTHENTICITY_NOT_GUARANTEED: &str =
41    "The authenticity of this encrypted message can't be guaranteed on this device.";
42const UNVERIFIED_IDENTITY: &str = "Encrypted by an unverified user.";
43const VERIFICATION_VIOLATION: &str =
44    "Encrypted by a previously-verified user who is no longer verified.";
45const UNSIGNED_DEVICE: &str = "Encrypted by a device not verified by its owner.";
46const UNKNOWN_DEVICE: &str = "Encrypted by an unknown or deleted device.";
47const MISMATCHED_SENDER: &str = "\
48    The sender of the event does not match the owner of the device \
49    that created the Megolm session.";
50
51/// Represents the state of verification for a decrypted message sent by a
52/// device.
53#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
54#[serde(from = "OldVerificationStateHelper")]
55pub enum VerificationState {
56    /// This message is guaranteed to be authentic as it is coming from a device
57    /// belonging to a user that we have verified.
58    ///
59    /// This is the only state where authenticity can be guaranteed.
60    Verified,
61
62    /// The message could not be linked to a verified device.
63    ///
64    /// For more detailed information on why the message is considered
65    /// unverified, refer to the VerificationLevel sub-enum.
66    Unverified(VerificationLevel),
67}
68
69// TODO: Remove this once we're confident that everybody that serialized these
70// states uses the new enum.
71#[derive(Clone, Debug, Deserialize)]
72enum OldVerificationStateHelper {
73    Untrusted,
74    UnknownDevice,
75    #[serde(alias = "Trusted")]
76    Verified,
77    Unverified(VerificationLevel),
78}
79
80impl From<OldVerificationStateHelper> for VerificationState {
81    fn from(value: OldVerificationStateHelper) -> Self {
82        match value {
83            // This mapping isn't strictly correct but we don't know which part in the old
84            // `VerificationState` enum was unverified.
85            OldVerificationStateHelper::Untrusted => {
86                VerificationState::Unverified(VerificationLevel::UnsignedDevice)
87            }
88            OldVerificationStateHelper::UnknownDevice => {
89                Self::Unverified(VerificationLevel::None(DeviceLinkProblem::MissingDevice))
90            }
91            OldVerificationStateHelper::Verified => Self::Verified,
92            OldVerificationStateHelper::Unverified(l) => Self::Unverified(l),
93        }
94    }
95}
96
97impl VerificationState {
98    /// Convert the `VerificationState` into a `ShieldState` which can be
99    /// directly used to decorate messages in the recommended way.
100    ///
101    /// This method decorates messages using a strict ruleset, for a more lax
102    /// variant of this method take a look at
103    /// [`VerificationState::to_shield_state_lax()`].
104    pub fn to_shield_state_strict(&self) -> ShieldState {
105        match self {
106            VerificationState::Verified => ShieldState::None,
107            VerificationState::Unverified(level) => match level {
108                VerificationLevel::UnverifiedIdentity
109                | VerificationLevel::VerificationViolation
110                | VerificationLevel::UnsignedDevice => ShieldState::Red {
111                    code: ShieldStateCode::UnverifiedIdentity,
112                    message: UNVERIFIED_IDENTITY,
113                },
114                VerificationLevel::None(link) => match link {
115                    DeviceLinkProblem::MissingDevice => ShieldState::Red {
116                        code: ShieldStateCode::UnknownDevice,
117                        message: UNKNOWN_DEVICE,
118                    },
119                    DeviceLinkProblem::InsecureSource => ShieldState::Red {
120                        code: ShieldStateCode::AuthenticityNotGuaranteed,
121                        message: AUTHENTICITY_NOT_GUARANTEED,
122                    },
123                },
124                VerificationLevel::MismatchedSender => ShieldState::Red {
125                    code: ShieldStateCode::MismatchedSender,
126                    message: MISMATCHED_SENDER,
127                },
128            },
129        }
130    }
131
132    /// Convert the `VerificationState` into a `ShieldState` which can be used
133    /// to decorate messages in the recommended way.
134    ///
135    /// This implements a legacy, lax decoration mode.
136    ///
137    /// For a more strict variant of this method take a look at
138    /// [`VerificationState::to_shield_state_strict()`].
139    pub fn to_shield_state_lax(&self) -> ShieldState {
140        match self {
141            VerificationState::Verified => ShieldState::None,
142            VerificationState::Unverified(level) => match level {
143                VerificationLevel::UnverifiedIdentity => {
144                    // If you didn't show interest in verifying that user we don't
145                    // nag you with an error message.
146                    ShieldState::None
147                }
148                VerificationLevel::VerificationViolation => {
149                    // This is a high warning. The sender was previously
150                    // verified, but changed their identity.
151                    ShieldState::Red {
152                        code: ShieldStateCode::VerificationViolation,
153                        message: VERIFICATION_VIOLATION,
154                    }
155                }
156                VerificationLevel::UnsignedDevice => {
157                    // This is a high warning. The sender hasn't verified his own device.
158                    ShieldState::Red {
159                        code: ShieldStateCode::UnsignedDevice,
160                        message: UNSIGNED_DEVICE,
161                    }
162                }
163                VerificationLevel::None(link) => match link {
164                    DeviceLinkProblem::MissingDevice => {
165                        // Have to warn as it could have been a temporary injected device.
166                        // Notice that the device might just not be known at this time, so callers
167                        // should retry when there is a device change for that user.
168                        ShieldState::Red {
169                            code: ShieldStateCode::UnknownDevice,
170                            message: UNKNOWN_DEVICE,
171                        }
172                    }
173                    DeviceLinkProblem::InsecureSource => {
174                        // In legacy mode, we tone down this warning as it is quite common and
175                        // mostly noise (due to legacy backup and lack of trusted forwards).
176                        ShieldState::Grey {
177                            code: ShieldStateCode::AuthenticityNotGuaranteed,
178                            message: AUTHENTICITY_NOT_GUARANTEED,
179                        }
180                    }
181                },
182                VerificationLevel::MismatchedSender => ShieldState::Red {
183                    code: ShieldStateCode::MismatchedSender,
184                    message: MISMATCHED_SENDER,
185                },
186            },
187        }
188    }
189}
190
191/// The sub-enum containing detailed information on why a message is considered
192/// to be unverified.
193#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
194pub enum VerificationLevel {
195    /// The message was sent by a user identity we have not verified.
196    UnverifiedIdentity,
197
198    /// The message was sent by a user identity we have not verified, but the
199    /// user was previously verified.
200    #[serde(alias = "PreviouslyVerified")]
201    VerificationViolation,
202
203    /// The message was sent by a device not linked to (signed by) any user
204    /// identity.
205    UnsignedDevice,
206
207    /// We weren't able to link the message back to any device. This might be
208    /// because the message claims to have been sent by a device which we have
209    /// not been able to obtain (for example, because the device was since
210    /// deleted) or because the key to decrypt the message was obtained from
211    /// an insecure source.
212    None(DeviceLinkProblem),
213
214    /// The `sender` field on the event does not match the owner of the device
215    /// that established the Megolm session.
216    MismatchedSender,
217}
218
219impl fmt::Display for VerificationLevel {
220    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
221        let display = match self {
222            VerificationLevel::UnverifiedIdentity => "The sender's identity was not verified",
223            VerificationLevel::VerificationViolation => {
224                "The sender's identity was previously verified but has changed"
225            }
226            VerificationLevel::UnsignedDevice => {
227                "The sending device was not signed by the user's identity"
228            }
229            VerificationLevel::None(..) => "The sending device is not known",
230            VerificationLevel::MismatchedSender => MISMATCHED_SENDER,
231        };
232        write!(f, "{display}")
233    }
234}
235
236/// The sub-enum containing detailed information on why we were not able to link
237/// a message back to a device.
238#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
239pub enum DeviceLinkProblem {
240    /// The device is missing, either because it was deleted, or you haven't
241    /// yet downoaled it or the server is erroneously omitting it (federation
242    /// lag).
243    MissingDevice,
244    /// The key was obtained from an insecure source: imported from a file,
245    /// obtained from a legacy (asymmetric) backup, unsafe key forward, etc.
246    InsecureSource,
247}
248
249/// Recommended decorations for decrypted messages, representing the message's
250/// authenticity properties.
251#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
252pub enum ShieldState {
253    /// A red shield with a tooltip containing the associated message should be
254    /// presented.
255    Red {
256        /// A machine-readable representation.
257        code: ShieldStateCode,
258        /// A human readable description.
259        message: &'static str,
260    },
261    /// A grey shield with a tooltip containing the associated message should be
262    /// presented.
263    Grey {
264        /// A machine-readable representation.
265        code: ShieldStateCode,
266        /// A human readable description.
267        message: &'static str,
268    },
269    /// No shield should be presented.
270    None,
271}
272
273/// A machine-readable representation of the authenticity for a `ShieldState`.
274#[derive(Clone, Copy, Debug, Deserialize, Serialize, Eq, PartialEq)]
275#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
276#[cfg_attr(target_family = "wasm", wasm_bindgen)]
277pub enum ShieldStateCode {
278    /// Not enough information available to check the authenticity.
279    AuthenticityNotGuaranteed,
280    /// The sending device isn't yet known by the Client.
281    UnknownDevice,
282    /// The sending device hasn't been verified by the sender.
283    UnsignedDevice,
284    /// The sender hasn't been verified by the Client's user.
285    UnverifiedIdentity,
286    /// The sender was previously verified but changed their identity.
287    #[serde(alias = "PreviouslyVerified")]
288    VerificationViolation,
289    /// The `sender` field on the event does not match the owner of the device
290    /// that established the Megolm session.
291    MismatchedSender,
292}
293
294/// The algorithm specific information of a decrypted event.
295#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
296pub enum AlgorithmInfo {
297    /// The info if the event was encrypted using m.megolm.v1.aes-sha2
298    MegolmV1AesSha2 {
299        /// The curve25519 key of the device that created the megolm decryption
300        /// key originally.
301        curve25519_key: String,
302        /// The signing keys that have created the megolm key that was used to
303        /// decrypt this session. This map will usually contain a single ed25519
304        /// key.
305        sender_claimed_keys: BTreeMap<DeviceKeyAlgorithm, String>,
306
307        /// The Megolm session ID that was used to encrypt this event, or None
308        /// if this info was stored before we collected this data.
309        #[serde(default, skip_serializing_if = "Option::is_none")]
310        session_id: Option<String>,
311    },
312
313    /// The info if the event was encrypted using m.olm.v1.curve25519-aes-sha2
314    OlmV1Curve25519AesSha2 {
315        // The sender device key, base64 encoded
316        curve25519_public_key_base64: String,
317    },
318}
319
320/// Struct containing information on the forwarder of the keys used to decrypt
321/// an event.
322#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
323pub struct ForwarderInfo {
324    /// The user ID of the forwarder.
325    pub user_id: OwnedUserId,
326    /// The device ID of the forwarder.
327    pub device_id: OwnedDeviceId,
328}
329
330/// Struct containing information on how an event was decrypted.
331#[derive(Clone, Debug, PartialEq, Serialize)]
332pub struct EncryptionInfo {
333    /// The user ID of the event sender, note this is untrusted data unless the
334    /// `verification_state` is `Verified` as well.
335    pub sender: OwnedUserId,
336    /// The device ID of the device that sent us the event, note this is
337    /// untrusted data unless `verification_state` is `Verified` as well.
338    pub sender_device: Option<OwnedDeviceId>,
339    /// If the keys for this message were shared-on-invite as part of an
340    /// [MSC4268] key bundle, information about the forwarder.
341    ///
342    /// [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268
343    pub forwarder: Option<ForwarderInfo>,
344    /// Information about the algorithm that was used to encrypt the event.
345    pub algorithm_info: AlgorithmInfo,
346    /// The verification state of the device that sent us the event, note this
347    /// is the state of the device at the time of decryption. It may change in
348    /// the future if a device gets verified or deleted.
349    ///
350    /// Callers that persist this should mark the state as dirty when a device
351    /// change is received down the sync.
352    pub verification_state: VerificationState,
353}
354
355impl EncryptionInfo {
356    /// Helper to get the megolm session id used to encrypt.
357    pub fn session_id(&self) -> Option<&str> {
358        if let AlgorithmInfo::MegolmV1AesSha2 { session_id, .. } = &self.algorithm_info {
359            session_id.as_deref()
360        } else {
361            None
362        }
363    }
364}
365
366impl<'de> Deserialize<'de> for EncryptionInfo {
367    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
368    where
369        D: serde::Deserializer<'de>,
370    {
371        // Backwards compatibility: Capture session_id at root if exists. In legacy
372        // EncryptionInfo the session_id was not in AlgorithmInfo
373        #[derive(Deserialize)]
374        struct Helper {
375            pub sender: OwnedUserId,
376            pub sender_device: Option<OwnedDeviceId>,
377            pub forwarder: Option<ForwarderInfo>,
378            pub algorithm_info: AlgorithmInfo,
379            pub verification_state: VerificationState,
380            #[serde(rename = "session_id")]
381            pub old_session_id: Option<String>,
382        }
383
384        let Helper {
385            sender,
386            sender_device,
387            forwarder,
388            algorithm_info,
389            verification_state,
390            old_session_id,
391        } = Helper::deserialize(deserializer)?;
392
393        let algorithm_info = match algorithm_info {
394            AlgorithmInfo::MegolmV1AesSha2 { curve25519_key, sender_claimed_keys, session_id } => {
395                AlgorithmInfo::MegolmV1AesSha2 {
396                    // Migration, merge the old_session_id in algorithm_info
397                    session_id: session_id.or(old_session_id),
398                    curve25519_key,
399                    sender_claimed_keys,
400                }
401            }
402            other => other,
403        };
404
405        Ok(EncryptionInfo { sender, sender_device, forwarder, algorithm_info, verification_state })
406    }
407}
408
409/// A simplified thread summary.
410///
411/// A thread summary contains useful information pertaining to a thread, and
412/// that would be usually attached in clients to a thread root event (i.e. the
413/// first event from which the thread originated), along with links into the
414/// thread's view. This summary may include, for instance:
415///
416/// - the number of replies to the thread,
417/// - the full event of the latest reply to the thread,
418/// - whether the user participated or not to this thread.
419#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
420pub struct ThreadSummary {
421    /// The event id for the latest reply to the thread.
422    #[serde(skip_serializing_if = "Option::is_none")]
423    pub latest_reply: Option<OwnedEventId>,
424
425    /// The number of replies to the thread.
426    ///
427    /// This doesn't include the thread root event itself. It can be zero if no
428    /// events in the thread are considered to be meaningful (or they've all
429    /// been redacted).
430    pub num_replies: u32,
431}
432
433/// The status of a thread summary.
434#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
435pub enum ThreadSummaryStatus {
436    /// We don't know if the event has a thread summary.
437    #[default]
438    Unknown,
439    /// The event has no thread summary.
440    None,
441    /// The event has a thread summary, which is bundled in the event itself.
442    Some(ThreadSummary),
443}
444
445impl ThreadSummaryStatus {
446    /// Create a [`ThreadSummaryStatus`] from an optional thread summary.
447    pub fn from_opt(summary: Option<ThreadSummary>) -> Self {
448        match summary {
449            None => ThreadSummaryStatus::None,
450            Some(summary) => ThreadSummaryStatus::Some(summary),
451        }
452    }
453
454    /// Is the thread status of this event unknown?
455    fn is_unknown(&self) -> bool {
456        matches!(self, ThreadSummaryStatus::Unknown)
457    }
458
459    /// Transforms the [`ThreadSummaryStatus`] into an optional thread summary,
460    /// for cases where we don't care about distinguishing unknown and none.
461    pub fn summary(&self) -> Option<&ThreadSummary> {
462        match self {
463            ThreadSummaryStatus::Unknown | ThreadSummaryStatus::None => None,
464            ThreadSummaryStatus::Some(thread_summary) => Some(thread_summary),
465        }
466    }
467}
468
469/// Represents a matrix room event that has been returned from a Matrix
470/// client-server API endpoint such as `/sync` or `/messages`, after initial
471/// processing.
472///
473/// The "initial processing" includes an attempt to decrypt encrypted events, so
474/// the main thing this adds over [`AnyTimelineEvent`] is information on
475/// encryption.
476//
477// 🚨 Note about this type, please read! 🚨
478//
479// `TimelineEvent` is heavily used across the SDK crates. In some cases, we
480// are reaching a [`recursion_limit`] when the compiler is trying to figure out
481// if `TimelineEvent` implements `Sync` when it's embedded in other types.
482//
483// We want to help the compiler so that one doesn't need to increase the
484// `recursion_limit`. We stop the recursive check by (un)safely implement `Sync`
485// and `Send` on `TimelineEvent` directly.
486//
487// See
488// https://github.com/matrix-org/matrix-rust-sdk/pull/3749#issuecomment-2312939823
489// which has addressed this issue first
490//
491// [`recursion_limit`]: https://doc.rust-lang.org/reference/attributes/limits.html#the-recursion_limit-attribute
492#[derive(Clone, Debug, Serialize)]
493pub struct TimelineEvent {
494    /// The event ID (cached from `Self::kind`).
495    ///
496    /// This field contains a copy of `TimelineEventKind::parse_event_id`. Why?
497    /// Because reading the event ID is done **a lot** in the SDK.
498    /// `TimelineEventKind::parse_event_id` implies parsing/deserializing the
499    /// JSON payload looking for the event ID. It has a non-negligible cost.
500    /// Hence this cache.
501    #[serde(skip)]
502    event_id: Option<OwnedEventId>,
503
504    /// The event itself, together with any information on decryption.
505    pub kind: TimelineEventKind,
506
507    /// The timestamp of the event. It's the `origin_server_ts` value (if any),
508    /// corrected if detected as malicious.
509    ///
510    /// It can be `None` if the event has been serialised before the addition of
511    /// this field, or if parsing the `origin_server_ts` value failed.
512    pub timestamp: Option<MilliSecondsSinceUnixEpoch>,
513
514    /// The push actions associated with this event.
515    ///
516    /// If it's set to `None`, then it means we couldn't compute those actions,
517    /// or that they could be computed but there were none.
518    #[serde(skip_serializing_if = "skip_serialize_push_actions")]
519    push_actions: Option<Vec<Action>>,
520
521    /// If the event is part of a thread, a thread summary.
522    #[serde(default, skip_serializing_if = "ThreadSummaryStatus::is_unknown")]
523    pub thread_summary: ThreadSummaryStatus,
524}
525
526// Don't serialize push actions if they're `None` or an empty vec.
527fn skip_serialize_push_actions(push_actions: &Option<Vec<Action>>) -> bool {
528    push_actions.as_ref().is_none_or(|v| v.is_empty())
529}
530
531// See https://github.com/matrix-org/matrix-rust-sdk/pull/3749#issuecomment-2312939823.
532#[cfg(not(feature = "test-send-sync"))]
533unsafe impl Send for TimelineEvent {}
534
535// See https://github.com/matrix-org/matrix-rust-sdk/pull/3749#issuecomment-2312939823.
536#[cfg(not(feature = "test-send-sync"))]
537unsafe impl Sync for TimelineEvent {}
538
539#[cfg(feature = "test-send-sync")]
540#[test]
541// See https://github.com/matrix-org/matrix-rust-sdk/pull/3749#issuecomment-2312939823.
542fn test_send_sync_for_sync_timeline_event() {
543    fn assert_send_sync<T: crate::SendOutsideWasm + crate::SyncOutsideWasm>() {}
544
545    assert_send_sync::<TimelineEvent>();
546}
547
548impl TimelineEvent {
549    /// Create a new [`TimelineEvent`] from the given raw event.
550    ///
551    /// This is a convenience constructor for a plaintext event when you don't
552    /// need to set `push_action`, for example inside a test.
553    pub fn from_plaintext(event: Raw<AnySyncTimelineEvent>) -> Self {
554        Self::from_plaintext_with_max_timestamp(event, MilliSecondsSinceUnixEpoch::now())
555    }
556
557    /// Like [`TimelineEvent::from_plaintext`] but with a given `max_timestamp`.
558    pub fn from_plaintext_with_max_timestamp(
559        event: Raw<AnySyncTimelineEvent>,
560        max_timestamp: MilliSecondsSinceUnixEpoch,
561    ) -> Self {
562        Self::new(TimelineEventKind::PlainText { event }, None, max_timestamp)
563    }
564
565    /// Create a new [`TimelineEvent`] from a decrypted event.
566    pub fn from_decrypted(
567        decrypted: DecryptedRoomEvent,
568        push_actions: Option<Vec<Action>>,
569    ) -> Self {
570        Self::from_decrypted_with_max_timestamp(
571            decrypted,
572            push_actions,
573            MilliSecondsSinceUnixEpoch::now(),
574        )
575    }
576
577    /// Like [`TimelineEvent::from_decrypted`] but with a given `max_timestamp`.
578    pub fn from_decrypted_with_max_timestamp(
579        decrypted: DecryptedRoomEvent,
580        push_actions: Option<Vec<Action>>,
581        max_timestamp: MilliSecondsSinceUnixEpoch,
582    ) -> Self {
583        Self::new(TimelineEventKind::Decrypted(decrypted), push_actions, max_timestamp)
584    }
585
586    /// Create a new [`TimelineEvent`] to represent the given decryption
587    /// failure.
588    pub fn from_utd(event: Raw<AnySyncTimelineEvent>, utd_info: UnableToDecryptInfo) -> Self {
589        Self::from_utd_with_max_timestamp(event, utd_info, MilliSecondsSinceUnixEpoch::now())
590    }
591
592    /// Like [`TimelineEvent::from_utd`] but with a given `max_timestamp`.
593    pub fn from_utd_with_max_timestamp(
594        event: Raw<AnySyncTimelineEvent>,
595        utd_info: UnableToDecryptInfo,
596        max_timestamp: MilliSecondsSinceUnixEpoch,
597    ) -> Self {
598        Self::new(TimelineEventKind::UnableToDecrypt { event, utd_info }, None, max_timestamp)
599    }
600
601    /// Internal only: helps extracting a thread summary and latest thread event
602    /// when creating a new [`TimelineEvent`].
603    ///
604    /// Build the `timestamp` value by using `now()` as the max value.
605    fn new(
606        kind: TimelineEventKind,
607        push_actions: Option<Vec<Action>>,
608        max_timestamp: MilliSecondsSinceUnixEpoch,
609    ) -> Self {
610        let raw = kind.raw();
611
612        let bundled_thread = extract_bundled_thread(raw);
613        let timestamp = extract_timestamp(raw, max_timestamp);
614
615        Self {
616            event_id: kind.parse_event_id(),
617            kind,
618            push_actions,
619            timestamp,
620            thread_summary: match bundled_thread {
621                Some(bundled_thread) => ThreadSummaryStatus::Some(ThreadSummary {
622                    latest_reply: bundled_thread
623                        .latest_event
624                        .get_field::<OwnedEventId>("event_id")
625                        .ok()
626                        .flatten(),
627                    num_replies: bundled_thread.count.try_into().unwrap_or(u32::MAX),
628                }),
629                None => ThreadSummaryStatus::None,
630            },
631        }
632    }
633
634    /// Transform this [`TimelineEvent`] into another [`TimelineEvent`] with the
635    /// [`TimelineEventKind::Decrypted`] kind.
636    ///
637    /// ## Panics
638    ///
639    /// It panics (on debug builds only) if the kind already is
640    /// [`TimelineEventKind::Decrypted`].
641    pub fn to_decrypted(
642        &self,
643        decrypted: DecryptedRoomEvent,
644        push_actions: Option<Vec<Action>>,
645    ) -> Self {
646        debug_assert!(
647            matches!(self.kind, TimelineEventKind::Decrypted(_)).not(),
648            "`TimelineEvent::to_decrypted` has been called on an already decrypted `TimelineEvent`."
649        );
650
651        let kind = TimelineEventKind::Decrypted(decrypted);
652
653        Self {
654            // We could clone `self.event_id`, but we prefer to re-parse the event ID from
655            // `decrypted` in case it has changed (it MUST NOT happen, but we never know).
656            event_id: kind.parse_event_id(),
657            kind,
658            timestamp: self.timestamp,
659            push_actions,
660            thread_summary: self.thread_summary.clone(),
661        }
662    }
663
664    /// Transform this [`TimelineEvent`] into another [`TimelineEvent`] with the
665    /// [`TimelineEventKind::Decrypted`] kind.
666    ///
667    /// ## Panics
668    ///
669    /// It panics (on debug builds only) if the kind already is
670    /// [`TimelineEventKind::Decrypted`].
671    pub fn to_utd(&self, utd_info: UnableToDecryptInfo) -> Self {
672        debug_assert!(
673            matches!(self.kind, TimelineEventKind::UnableToDecrypt { .. }).not(),
674            "`TimelineEvent::to_utd` has been called on an already UTD `TimelineEvent`."
675        );
676
677        Self {
678            event_id: self.event_id.clone(),
679            kind: TimelineEventKind::UnableToDecrypt { event: self.raw().clone(), utd_info },
680            timestamp: self.timestamp,
681            push_actions: None,
682            thread_summary: self.thread_summary.clone(),
683        }
684    }
685
686    /// Try to create a new [`TimelineEvent`] for the bundled latest thread
687    /// event, if we have enough information about the encryption status for it.
688    fn from_bundled_latest_event(
689        kind: &TimelineEventKind,
690        latest_event: Raw<AnySyncMessageLikeEvent>,
691        max_timestamp: MilliSecondsSinceUnixEpoch,
692    ) -> Option<Self> {
693        match kind {
694            TimelineEventKind::Decrypted(decrypted) => {
695                if let Some(unsigned_decryption_result) =
696                    decrypted.unsigned_encryption_info.as_ref().and_then(|unsigned_map| {
697                        unsigned_map.get(&UnsignedEventLocation::RelationsThreadLatestEvent)
698                    })
699                {
700                    match unsigned_decryption_result {
701                        UnsignedDecryptionResult::Decrypted(encryption_info) => {
702                            // The bundled event was encrypted, and we could decrypt it: pass that
703                            // information around.
704                            return Some(TimelineEvent::from_decrypted_with_max_timestamp(
705                                DecryptedRoomEvent {
706                                    // Safety: A decrypted event always includes a room_id in
707                                    // its payload.
708                                    event: latest_event.cast_unchecked(),
709                                    encryption_info: encryption_info.clone(),
710                                    // A bundled latest event is never a thread root. It could
711                                    // have
712                                    // a replacement event, but we don't carry this information
713                                    // around.
714                                    unsigned_encryption_info: None,
715                                },
716                                None,
717                                max_timestamp,
718                            ));
719                        }
720
721                        UnsignedDecryptionResult::UnableToDecrypt(utd_info) => {
722                            // The bundled event was a UTD; store that information.
723                            return Some(TimelineEvent::from_utd_with_max_timestamp(
724                                latest_event.cast(),
725                                utd_info.clone(),
726                                max_timestamp,
727                            ));
728                        }
729                    }
730                }
731            }
732
733            TimelineEventKind::UnableToDecrypt { .. } | TimelineEventKind::PlainText { .. } => {
734                // Figure based on the event type below.
735            }
736        }
737
738        match latest_event.get_field::<MessageLikeEventType>("type") {
739            Ok(None) => {
740                let event_id = latest_event.get_field::<OwnedEventId>("event_id").ok().flatten();
741                warn!(
742                    ?event_id,
743                    "couldn't deserialize bundled latest thread event: missing `type` field \
744                     in bundled latest thread event"
745                );
746                None
747            }
748
749            Ok(Some(MessageLikeEventType::RoomEncrypted)) => {
750                // The bundled latest thread event is encrypted, but we didn't have any
751                // information about it in the unsigned map. Try to fetch the information from
752                // the content instead.
753                let session_id = if let Some(content) =
754                    latest_event.get_field::<EncryptedEventScheme>("content").ok().flatten()
755                {
756                    match content {
757                        EncryptedEventScheme::MegolmV1AesSha2(content) => Some(content.session_id),
758                        _ => None,
759                    }
760                } else {
761                    None
762                };
763
764                Some(TimelineEvent::from_utd_with_max_timestamp(
765                    latest_event.cast(),
766                    UnableToDecryptInfo { session_id, reason: UnableToDecryptReason::Unknown },
767                    max_timestamp,
768                ))
769            }
770
771            Ok(_) => Some(TimelineEvent::from_plaintext_with_max_timestamp(
772                latest_event.cast(),
773                max_timestamp,
774            )),
775
776            Err(err) => {
777                let event_id = latest_event.get_field::<OwnedEventId>("event_id").ok().flatten();
778                warn!(?event_id, "couldn't deserialize bundled latest thread event's type: {err}");
779                None
780            }
781        }
782    }
783
784    /// Read the current push actions.
785    ///
786    /// Returns `None` if they were never computed, or if they could not be
787    /// computed.
788    pub fn push_actions(&self) -> Option<&[Action]> {
789        self.push_actions.as_deref()
790    }
791
792    /// Set the push actions for this event.
793    pub fn set_push_actions(&mut self, push_actions: Vec<Action>) {
794        self.push_actions = Some(push_actions);
795    }
796
797    /// Get the (cached) event ID of this [`TimelineEvent`] if the event has
798    /// any valid ID.
799    pub fn event_id(&self) -> Option<&EventId> {
800        self.event_id.as_deref()
801    }
802
803    /// Get the sender of this [`TimelineEvent`] if the event has one.
804    pub fn sender(&self) -> Option<OwnedUserId> {
805        self.kind.parse_sender()
806    }
807
808    /// Returns a reference to the (potentially decrypted) Matrix event inside
809    /// this [`TimelineEvent`].
810    pub fn raw(&self) -> &Raw<AnySyncTimelineEvent> {
811        self.kind.raw()
812    }
813
814    /// Replace the raw event included in this item by another one.
815    pub fn replace_raw(&mut self, replacement: Raw<AnyTimelineEvent>) {
816        match &mut self.kind {
817            TimelineEventKind::Decrypted(decrypted) => decrypted.event = replacement,
818            TimelineEventKind::UnableToDecrypt { event, .. }
819            | TimelineEventKind::PlainText { event } => {
820                // It's safe to cast `AnyMessageLikeEvent` into `AnySyncMessageLikeEvent`,
821                // because the former contains a superset of the fields included in the latter.
822                *event = replacement.cast();
823            }
824        }
825
826        self.event_id = self.kind.parse_event_id();
827    }
828
829    /// Get the timestamp.
830    ///
831    /// If the timestamp is missing (most likely because the event has been
832    /// created before the addition of the [`TimelineEvent::timestamp`] field),
833    /// this method will try to extract it from the `origin_server_ts` value. If
834    /// the `origin_server_ts` value is malicious, it will be capped to
835    /// [`MilliSecondsSinceUnixEpoch::now`]. It means that the returned value
836    /// might not be constant.
837    pub fn timestamp(&self) -> Option<MilliSecondsSinceUnixEpoch> {
838        self.timestamp.or_else(|| {
839            warn!("`TimelineEvent::timestamp` is parsing the raw event to extract the `timestamp`");
840
841            extract_timestamp(self.raw(), MilliSecondsSinceUnixEpoch::now())
842        })
843    }
844
845    /// Get the timestamp value, without trying to backfill it if `None`.
846    pub fn timestamp_raw(&self) -> Option<MilliSecondsSinceUnixEpoch> {
847        self.timestamp
848    }
849
850    /// If the event was a decrypted event that was successfully decrypted, get
851    /// its encryption info. Otherwise, `None`.
852    pub fn encryption_info(&self) -> Option<&Arc<EncryptionInfo>> {
853        self.kind.encryption_info()
854    }
855
856    /// Takes ownership of this [`TimelineEvent`], returning the (potentially
857    /// decrypted) Matrix event within.
858    pub fn into_raw(self) -> Raw<AnySyncTimelineEvent> {
859        self.kind.into_raw()
860    }
861
862    /// If this event is a thread root, find and create the latest event of the
863    /// thread.
864    ///
865    /// The latest event comes bundled with this event, if it was provided in
866    /// the unsigned relations of this event.
867    pub fn bundled_latest_thread_event(&self) -> Option<Self> {
868        let bundled_thread = extract_bundled_thread(self.raw())?;
869
870        Self::from_bundled_latest_event(
871            &self.kind,
872            bundled_thread.latest_event,
873            self.timestamp_raw().unwrap_or_else(MilliSecondsSinceUnixEpoch::now),
874        )
875    }
876}
877
878impl<'de> Deserialize<'de> for TimelineEvent {
879    /// Custom deserializer for [`TimelineEvent`], to support older formats.
880    ///
881    /// Ideally we might use an untagged enum and then convert from that;
882    /// however, that doesn't work due to a [serde bug](https://github.com/serde-rs/json/issues/497).
883    ///
884    /// Instead, we first deserialize into an unstructured JSON map, and then
885    /// inspect the json to figure out which format we have.
886    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
887    where
888        D: serde::Deserializer<'de>,
889    {
890        use serde_json::{Map, Value};
891
892        // First, deserialize to an unstructured JSON map
893        let value = Map::<String, Value>::deserialize(deserializer)?;
894
895        // If we have a top-level `event`, it's V0
896        if value.contains_key("event") {
897            let v0: SyncTimelineEventDeserializationHelperV0 =
898                serde_json::from_value(Value::Object(value)).map_err(|e| {
899                    serde::de::Error::custom(format!(
900                        "Unable to deserialize V0-format TimelineEvent: {e}",
901                    ))
902                })?;
903            Ok(v0.into())
904        }
905        // Otherwise, it's V1
906        else {
907            let v1: SyncTimelineEventDeserializationHelperV1 =
908                serde_json::from_value(Value::Object(value)).map_err(|e| {
909                    serde::de::Error::custom(format!(
910                        "Unable to deserialize V1-format TimelineEvent: {e}",
911                    ))
912                })?;
913            Ok(v1.into())
914        }
915    }
916}
917
918/// The event within a [`TimelineEvent`], together with encryption data.
919#[derive(Clone, Serialize, Deserialize)]
920pub enum TimelineEventKind {
921    /// A successfully-decrypted encrypted event.
922    Decrypted(DecryptedRoomEvent),
923
924    /// An encrypted event which could not be decrypted.
925    UnableToDecrypt {
926        /// The `m.room.encrypted` event. Depending on the source of the event,
927        /// it could actually be an [`AnyTimelineEvent`] (i.e., it may
928        /// have a `room_id` property).
929        event: Raw<AnySyncTimelineEvent>,
930
931        /// Information on the reason we failed to decrypt
932        utd_info: UnableToDecryptInfo,
933    },
934
935    /// An unencrypted event.
936    PlainText {
937        /// The actual event. Depending on the source of the event, it could
938        /// actually be a [`AnyTimelineEvent`] (which differs from
939        /// [`AnySyncTimelineEvent`] by the addition of a `room_id` property).
940        event: Raw<AnySyncTimelineEvent>,
941    },
942}
943
944impl TimelineEventKind {
945    /// Returns a reference to the (potentially decrypted) Matrix event inside
946    /// this `TimelineEvent`.
947    pub fn raw(&self) -> &Raw<AnySyncTimelineEvent> {
948        match self {
949            // It is safe to cast from an `AnyMessageLikeEvent` (i.e. JSON which does
950            // *not* contain a `state_key` and *does* contain a `room_id`) into an
951            // `AnySyncTimelineEvent` (i.e. JSON which *may* contain a `state_key` and is *not*
952            // expected to contain a `room_id`). It just means that the `room_id` will be ignored
953            // in a future deserialization.
954            TimelineEventKind::Decrypted(d) => d.event.cast_ref(),
955            TimelineEventKind::UnableToDecrypt { event, .. } => event,
956            TimelineEventKind::PlainText { event } => event,
957        }
958    }
959
960    /// Parse the event ID of this `TimelineEventKind` if the event has any
961    /// valid id.
962    pub fn parse_event_id(&self) -> Option<OwnedEventId> {
963        self.raw().get_field::<OwnedEventId>("event_id").ok().flatten()
964    }
965
966    /// Parse the sender of this [`TimelineEventKind`] if the event has one.
967    pub fn parse_sender(&self) -> Option<OwnedUserId> {
968        self.raw().get_field::<OwnedUserId>("sender").ok().flatten()
969    }
970
971    /// Whether we could not decrypt the event (i.e. it is a UTD).
972    pub fn is_utd(&self) -> bool {
973        matches!(self, TimelineEventKind::UnableToDecrypt { .. })
974    }
975
976    /// If the event was a decrypted event that was successfully decrypted, get
977    /// its encryption info. Otherwise, `None`.
978    pub fn encryption_info(&self) -> Option<&Arc<EncryptionInfo>> {
979        match self {
980            TimelineEventKind::Decrypted(d) => Some(&d.encryption_info),
981            TimelineEventKind::UnableToDecrypt { .. } | TimelineEventKind::PlainText { .. } => None,
982        }
983    }
984
985    /// If the event was a decrypted event that was successfully decrypted, get
986    /// the map of decryption metadata related to the bundled events.
987    pub fn unsigned_encryption_map(
988        &self,
989    ) -> Option<&BTreeMap<UnsignedEventLocation, UnsignedDecryptionResult>> {
990        match self {
991            TimelineEventKind::Decrypted(d) => d.unsigned_encryption_info.as_ref(),
992            TimelineEventKind::UnableToDecrypt { .. } | TimelineEventKind::PlainText { .. } => None,
993        }
994    }
995
996    /// Takes ownership of this `TimelineEvent`, returning the (potentially
997    /// decrypted) Matrix event within.
998    pub fn into_raw(self) -> Raw<AnySyncTimelineEvent> {
999        match self {
1000            // It is safe to cast from an `AnyMessageLikeEvent` (i.e. JSON which does
1001            // *not* contain a `state_key` and *does* contain a `room_id`) into an
1002            // `AnySyncTimelineEvent` (i.e. JSON which *may* contain a `state_key` and is *not*
1003            // expected to contain a `room_id`). It just means that the `room_id` will be ignored
1004            // in a future deserialization.
1005            TimelineEventKind::Decrypted(d) => d.event.cast(),
1006            TimelineEventKind::UnableToDecrypt { event, .. } => event,
1007            TimelineEventKind::PlainText { event } => event,
1008        }
1009    }
1010
1011    /// The Megolm session ID that was used to send this event, if it was
1012    /// encrypted.
1013    pub fn session_id(&self) -> Option<&str> {
1014        match self {
1015            TimelineEventKind::Decrypted(decrypted_room_event) => {
1016                decrypted_room_event.encryption_info.session_id()
1017            }
1018            TimelineEventKind::UnableToDecrypt { utd_info, .. } => utd_info.session_id.as_deref(),
1019            TimelineEventKind::PlainText { .. } => None,
1020        }
1021    }
1022
1023    /// Parse the event type of this event.
1024    ///
1025    /// Returns `None` if there isn't an event type or if the event failed to be
1026    /// deserialized.
1027    pub fn event_type(&self) -> Option<String> {
1028        self.raw().get_field("type").ok().flatten()
1029    }
1030}
1031
1032#[cfg(not(tarpaulin_include))]
1033impl fmt::Debug for TimelineEventKind {
1034    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1035        match &self {
1036            Self::PlainText { event } => f
1037                .debug_struct("TimelineEventKind::PlainText")
1038                .field("event", &DebugRawEvent(event))
1039                .finish(),
1040
1041            Self::UnableToDecrypt { event, utd_info } => f
1042                .debug_struct("TimelineEventKind::UnableToDecrypt")
1043                .field("event", &DebugRawEvent(event))
1044                .field("utd_info", &utd_info)
1045                .finish(),
1046
1047            Self::Decrypted(decrypted) => {
1048                f.debug_tuple("TimelineEventKind::Decrypted").field(decrypted).finish()
1049            }
1050        }
1051    }
1052}
1053
1054/// A successfully-decrypted encrypted event.
1055#[derive(Clone, Serialize, Deserialize)]
1056pub struct DecryptedRoomEvent {
1057    /// The decrypted event.
1058    ///
1059    /// Note: it's not an error that this contains an [`AnyTimelineEvent`]
1060    /// (as opposed to an [`AnySyncTimelineEvent`]): an
1061    /// encrypted payload *always contains* a room id, by the [spec].
1062    ///
1063    /// [spec]: https://spec.matrix.org/v1.12/client-server-api/#mmegolmv1aes-sha2
1064    pub event: Raw<AnyTimelineEvent>,
1065
1066    /// The encryption info about the event.
1067    pub encryption_info: Arc<EncryptionInfo>,
1068
1069    /// The encryption info about the events bundled in the `unsigned`
1070    /// object.
1071    ///
1072    /// Will be `None` if no bundled event was encrypted.
1073    #[serde(skip_serializing_if = "Option::is_none")]
1074    pub unsigned_encryption_info: Option<BTreeMap<UnsignedEventLocation, UnsignedDecryptionResult>>,
1075}
1076
1077#[cfg(not(tarpaulin_include))]
1078impl fmt::Debug for DecryptedRoomEvent {
1079    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1080        let DecryptedRoomEvent { event, encryption_info, unsigned_encryption_info } = self;
1081
1082        f.debug_struct("DecryptedRoomEvent")
1083            .field("event", &DebugRawEvent(event))
1084            .field("encryption_info", encryption_info)
1085            .maybe_field("unsigned_encryption_info", unsigned_encryption_info)
1086            .finish()
1087    }
1088}
1089
1090/// The location of an event bundled in an `unsigned` object.
1091#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
1092pub enum UnsignedEventLocation {
1093    /// An event at the `m.replace` key of the `m.relations` object, that is a
1094    /// bundled replacement.
1095    RelationsReplace,
1096    /// An event at the `latest_event` key of the `m.thread` object of the
1097    /// `m.relations` object, that is the latest event of a thread.
1098    RelationsThreadLatestEvent,
1099}
1100
1101impl UnsignedEventLocation {
1102    /// Find the mutable JSON value at this location in the given unsigned
1103    /// object.
1104    ///
1105    /// # Arguments
1106    ///
1107    /// * `unsigned` - The `unsigned` property of an event as a JSON object.
1108    pub fn find_mut<'a>(&self, unsigned: &'a mut JsonObject) -> Option<&'a mut serde_json::Value> {
1109        let relations = unsigned.get_mut("m.relations")?.as_object_mut()?;
1110
1111        match self {
1112            Self::RelationsReplace => relations.get_mut("m.replace"),
1113            Self::RelationsThreadLatestEvent => {
1114                relations.get_mut("m.thread")?.as_object_mut()?.get_mut("latest_event")
1115            }
1116        }
1117    }
1118}
1119
1120/// The result of the decryption of an event bundled in an `unsigned` object.
1121#[derive(Debug, Clone, Serialize, Deserialize)]
1122pub enum UnsignedDecryptionResult {
1123    /// The event was successfully decrypted.
1124    Decrypted(Arc<EncryptionInfo>),
1125    /// The event failed to be decrypted.
1126    UnableToDecrypt(UnableToDecryptInfo),
1127}
1128
1129impl UnsignedDecryptionResult {
1130    /// Returns the encryption info for this bundled event if it was
1131    /// successfully decrypted.
1132    pub fn encryption_info(&self) -> Option<&Arc<EncryptionInfo>> {
1133        match self {
1134            Self::Decrypted(info) => Some(info),
1135            Self::UnableToDecrypt(_) => None,
1136        }
1137    }
1138}
1139
1140/// Metadata about an event that could not be decrypted.
1141#[derive(Debug, Clone, Serialize, Deserialize)]
1142pub struct UnableToDecryptInfo {
1143    /// The ID of the session used to encrypt the message, if it used the
1144    /// `m.megolm.v1.aes-sha2` algorithm.
1145    #[serde(skip_serializing_if = "Option::is_none")]
1146    pub session_id: Option<String>,
1147
1148    /// Reason code for the decryption failure
1149    #[serde(default = "unknown_utd_reason", deserialize_with = "deserialize_utd_reason")]
1150    pub reason: UnableToDecryptReason,
1151}
1152
1153fn unknown_utd_reason() -> UnableToDecryptReason {
1154    UnableToDecryptReason::Unknown
1155}
1156
1157/// Provides basic backward compatibility for deserializing older serialized
1158/// `UnableToDecryptReason` values.
1159pub fn deserialize_utd_reason<'de, D>(d: D) -> Result<UnableToDecryptReason, D::Error>
1160where
1161    D: serde::Deserializer<'de>,
1162{
1163    // Start by deserializing as to an untyped JSON value.
1164    let v: serde_json::Value = Deserialize::deserialize(d)?;
1165    // Backwards compatibility: `MissingMegolmSession` used to be stored without the
1166    // withheld code.
1167    if v.as_str().is_some_and(|s| s == "MissingMegolmSession") {
1168        return Ok(UnableToDecryptReason::MissingMegolmSession { withheld_code: None });
1169    }
1170    // Otherwise, use the derived deserialize impl to turn the JSON into a
1171    // UnableToDecryptReason
1172    serde_json::from_value::<UnableToDecryptReason>(v).map_err(serde::de::Error::custom)
1173}
1174
1175/// Reason code for a decryption failure
1176#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1177pub enum UnableToDecryptReason {
1178    /// The reason for the decryption failure is unknown. This is only intended
1179    /// for use when deserializing old UnableToDecryptInfo instances.
1180    #[doc(hidden)]
1181    Unknown,
1182
1183    /// The `m.room.encrypted` event that should have been decrypted is
1184    /// malformed in some way (e.g. unsupported algorithm, missing fields,
1185    /// unknown megolm message type).
1186    MalformedEncryptedEvent,
1187
1188    /// Decryption failed because we're missing the megolm session that was used
1189    /// to encrypt the event.
1190    MissingMegolmSession {
1191        /// If the key was withheld on purpose, the associated code. `None`
1192        /// means no withheld code was received.
1193        withheld_code: Option<WithheldCode>,
1194    },
1195
1196    /// Decryption failed because, while we have the megolm session that was
1197    /// used to encrypt the message, it is ratcheted too far forward.
1198    UnknownMegolmMessageIndex,
1199
1200    /// We found the Megolm session, but were unable to decrypt the event using
1201    /// that session for some reason (e.g. incorrect MAC).
1202    ///
1203    /// This represents all `vodozemac::megolm::DecryptionError`s, except
1204    /// `UnknownMessageIndex`, which is represented as
1205    /// `UnknownMegolmMessageIndex`.
1206    MegolmDecryptionFailure,
1207
1208    /// The event could not be deserialized after decryption.
1209    PayloadDeserializationFailure,
1210
1211    /// Decryption failed because of a mismatch between the identity keys of the
1212    /// device we received the room key from and the identity keys recorded in
1213    /// the plaintext of the room key to-device message.
1214    MismatchedIdentityKeys,
1215
1216    /// An encrypted message wasn't decrypted, because the sender's
1217    /// cross-signing identity did not satisfy the requested
1218    /// `TrustRequirement`.
1219    SenderIdentityNotTrusted(VerificationLevel),
1220
1221    /// The outer state key could not be verified against the inner encrypted
1222    /// state key and type.
1223    #[cfg(feature = "experimental-encrypted-state-events")]
1224    StateKeyVerificationFailed,
1225}
1226
1227impl UnableToDecryptReason {
1228    /// Returns true if this UTD is due to a missing room key (and hence might
1229    /// resolve itself if we wait a bit.)
1230    pub fn is_missing_room_key(&self) -> bool {
1231        // In case of MissingMegolmSession with a withheld code we return false here
1232        // given that this API is used to decide if waiting a bit will help.
1233        matches!(
1234            self,
1235            Self::MissingMegolmSession { withheld_code: None } | Self::UnknownMegolmMessageIndex
1236        )
1237    }
1238}
1239
1240/// A machine-readable code for why a Megolm key was not sent.
1241///
1242/// Normally sent as the payload of an [`m.room_key.withheld`](https://spec.matrix.org/v1.12/client-server-api/#mroom_keywithheld) to-device message.
1243#[derive(
1244    Clone,
1245    PartialEq,
1246    Eq,
1247    Hash,
1248    AsStrAsRefStr,
1249    AsRefStr,
1250    FromString,
1251    DebugAsRefStr,
1252    SerializeAsRefStr,
1253    DeserializeFromCowStr,
1254)]
1255pub enum WithheldCode {
1256    /// the user/device was blacklisted.
1257    #[ruma_enum(rename = "m.blacklisted")]
1258    Blacklisted,
1259
1260    /// the user/devices is unverified.
1261    #[ruma_enum(rename = "m.unverified")]
1262    Unverified,
1263
1264    /// The user/device is not allowed have the key. For example, this would
1265    /// usually be sent in response to a key request if the user was not in
1266    /// the room when the message was sent.
1267    #[ruma_enum(rename = "m.unauthorised")]
1268    Unauthorised,
1269
1270    /// Sent in reply to a key request if the device that the key is requested
1271    /// from does not have the requested key.
1272    #[ruma_enum(rename = "m.unavailable")]
1273    Unavailable,
1274
1275    /// An olm session could not be established.
1276    /// This may happen, for example, if the sender was unable to obtain a
1277    /// one-time key from the recipient.
1278    #[ruma_enum(rename = "m.no_olm")]
1279    NoOlm,
1280
1281    /// Normally used when sharing history, per [MSC4268]: indicates
1282    /// that the session was not marked as "shared_history".
1283    ///
1284    /// [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268
1285    #[ruma_enum(rename = "m.history_not_shared", alias = "io.element.msc4268.history_not_shared")]
1286    HistoryNotShared,
1287
1288    #[doc(hidden)]
1289    _Custom(PrivOwnedStr),
1290}
1291
1292impl fmt::Display for WithheldCode {
1293    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1294        let string = match self {
1295            WithheldCode::Blacklisted => "The sender has blocked you.",
1296            WithheldCode::Unverified => "The sender has disabled encrypting to unverified devices.",
1297            WithheldCode::Unauthorised => "You are not authorised to read the message.",
1298            WithheldCode::Unavailable => "The requested key was not found.",
1299            WithheldCode::NoOlm => "Unable to establish a secure channel.",
1300            WithheldCode::HistoryNotShared => "The sender disabled sharing encrypted history.",
1301            _ => self.as_str(),
1302        };
1303
1304        f.write_str(string)
1305    }
1306}
1307
1308// The Ruma macro expects the type to have this name.
1309// The payload is counter intuitively made public in order to avoid having
1310// multiple copies of this struct.
1311#[doc(hidden)]
1312#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1313pub struct PrivOwnedStr(pub Box<str>);
1314
1315#[cfg(not(tarpaulin_include))]
1316impl fmt::Debug for PrivOwnedStr {
1317    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1318        self.0.fmt(f)
1319    }
1320}
1321
1322/// Deserialization helper for [`TimelineEvent`], for the modern format.
1323///
1324/// This has the exact same fields as [`TimelineEvent`] itself, but has a
1325/// regular `Deserialize` implementation.
1326#[derive(Debug, Deserialize)]
1327struct SyncTimelineEventDeserializationHelperV1 {
1328    /// The event itself, together with any information on decryption.
1329    kind: TimelineEventKind,
1330
1331    /// The timestamp of the event. It's the `origin_server_ts` value (if any),
1332    /// corrected if detected as malicious.
1333    #[serde(default)]
1334    timestamp: Option<MilliSecondsSinceUnixEpoch>,
1335
1336    /// The push actions associated with this event.
1337    #[serde(default)]
1338    push_actions: Vec<Action>,
1339
1340    /// If the event is part of a thread, a thread summary.
1341    #[serde(default)]
1342    thread_summary: ThreadSummaryStatus,
1343}
1344
1345impl From<SyncTimelineEventDeserializationHelperV1> for TimelineEvent {
1346    fn from(value: SyncTimelineEventDeserializationHelperV1) -> Self {
1347        let SyncTimelineEventDeserializationHelperV1 {
1348            kind,
1349            timestamp,
1350            push_actions,
1351            thread_summary,
1352        } = value;
1353
1354        // If `timestamp` is `None`, it is very likely that the event was serialised
1355        // before the addition of the `timestamp` field. We _could_ compute it here, but
1356        // if the `timestamp` was malicious, it means we are going to _cap_ the
1357        // `timestamp` to `now()` for every deserialisation. It is annoying because it
1358        // means the event is no longer deterministic, it's not constant.
1359        // We don't want that. Consequently, we keep `None` here, and we let
1360        // [`TimelineEvent::timestamp`] to handle that case for us.
1361
1362        TimelineEvent {
1363            event_id: kind.parse_event_id(),
1364            kind,
1365            timestamp,
1366            push_actions: Some(push_actions),
1367            thread_summary,
1368        }
1369    }
1370}
1371
1372/// Deserialization helper for [`TimelineEvent`], for an older format.
1373#[derive(Deserialize)]
1374struct SyncTimelineEventDeserializationHelperV0 {
1375    /// The actual event.
1376    event: Raw<AnySyncTimelineEvent>,
1377
1378    /// The encryption info about the event.
1379    ///
1380    /// Will be `None` if the event was not encrypted.
1381    encryption_info: Option<Arc<EncryptionInfo>>,
1382
1383    /// The push actions associated with this event.
1384    #[serde(default)]
1385    push_actions: Vec<Action>,
1386
1387    /// The encryption info about the events bundled in the `unsigned`
1388    /// object.
1389    ///
1390    /// Will be `None` if no bundled event was encrypted.
1391    unsigned_encryption_info: Option<BTreeMap<UnsignedEventLocation, UnsignedDecryptionResult>>,
1392}
1393
1394impl From<SyncTimelineEventDeserializationHelperV0> for TimelineEvent {
1395    fn from(value: SyncTimelineEventDeserializationHelperV0) -> Self {
1396        let SyncTimelineEventDeserializationHelperV0 {
1397            event,
1398            encryption_info,
1399            push_actions,
1400            unsigned_encryption_info,
1401        } = value;
1402
1403        // We do not compute the `timestamp` value here because if the `timestamp` is
1404        // malicious, it means we are going to _cap_ the `timestamp` to `now()` for
1405        // every deserialisation. It is annoying because it means the event is no longer
1406        // deterministic, it's not constant. We don't want that. Consequently, we keep
1407        // `None` here, and we let [`TimelineEvent::timestamp`] to handle that case for
1408        // us.
1409        let timestamp = None;
1410
1411        let kind = match encryption_info {
1412            Some(encryption_info) => {
1413                TimelineEventKind::Decrypted(DecryptedRoomEvent {
1414                    // We cast from `Raw<AnySyncTimelineEvent>` to
1415                    // `Raw<AnyMessageLikeEvent>`, which means
1416                    // we are asserting that it contains a room_id.
1417                    // That *should* be ok, because if this is genuinely a decrypted
1418                    // room event (as the encryption_info indicates), then it will have
1419                    // a room_id.
1420                    event: event.cast_unchecked(),
1421                    encryption_info,
1422                    unsigned_encryption_info,
1423                })
1424            }
1425
1426            None => TimelineEventKind::PlainText { event },
1427        };
1428
1429        TimelineEvent {
1430            event_id: kind.parse_event_id(),
1431            kind,
1432            timestamp,
1433            push_actions: Some(push_actions),
1434            // No serialized events had a thread summary at this version of the struct.
1435            thread_summary: ThreadSummaryStatus::Unknown,
1436        }
1437    }
1438}
1439
1440/// Reason code for a to-device decryption failure
1441#[derive(Debug, Clone, PartialEq)]
1442pub enum ToDeviceUnableToDecryptReason {
1443    /// An error occurred while encrypting the event. This covers all
1444    /// `OlmError` types.
1445    DecryptionFailure,
1446
1447    /// We refused to decrypt the message because the sender's device is not
1448    /// verified, or more generally, the sender's identity did not match the
1449    /// trust requirement we were asked to provide.
1450    UnverifiedSenderDevice,
1451
1452    /// We have no `OlmMachine`. This should not happen unless we forget to set
1453    /// things up by calling `OlmMachine::activate()`.
1454    NoOlmMachine,
1455
1456    /// The Matrix SDK was compiled without encryption support.
1457    EncryptionIsDisabled,
1458}
1459
1460/// Metadata about a to-device event that could not be decrypted.
1461#[derive(Clone, Debug)]
1462pub struct ToDeviceUnableToDecryptInfo {
1463    /// Reason code for the decryption failure
1464    pub reason: ToDeviceUnableToDecryptReason,
1465}
1466
1467/// Represents a to-device event after it has been processed by the Olm machine.
1468#[derive(Clone, Debug)]
1469pub enum ProcessedToDeviceEvent {
1470    /// A successfully-decrypted encrypted event.
1471    /// Contains the raw decrypted event and encryption info
1472    Decrypted {
1473        /// The raw decrypted event
1474        raw: Raw<AnyToDeviceEvent>,
1475        /// The Olm encryption info
1476        encryption_info: EncryptionInfo,
1477    },
1478
1479    /// An encrypted event which could not be decrypted.
1480    UnableToDecrypt {
1481        encrypted_event: Raw<AnyToDeviceEvent>,
1482        utd_info: ToDeviceUnableToDecryptInfo,
1483    },
1484
1485    /// An unencrypted event.
1486    PlainText(Raw<AnyToDeviceEvent>),
1487
1488    /// An invalid to device event that was ignored because it is missing some
1489    /// required information to be processed (like no event `type` for
1490    /// example)
1491    Invalid(Raw<AnyToDeviceEvent>),
1492}
1493
1494impl ProcessedToDeviceEvent {
1495    /// Converts a ProcessedToDeviceEvent to the `Raw<AnyToDeviceEvent>` it
1496    /// encapsulates
1497    pub fn to_raw(&self) -> Raw<AnyToDeviceEvent> {
1498        match self {
1499            ProcessedToDeviceEvent::Decrypted { raw, .. } => raw.clone(),
1500            ProcessedToDeviceEvent::UnableToDecrypt { encrypted_event, .. } => {
1501                encrypted_event.clone()
1502            }
1503            ProcessedToDeviceEvent::PlainText(event) => event.clone(),
1504            ProcessedToDeviceEvent::Invalid(event) => event.clone(),
1505        }
1506    }
1507
1508    /// Gets the raw to-device event.
1509    pub fn as_raw(&self) -> &Raw<AnyToDeviceEvent> {
1510        match self {
1511            ProcessedToDeviceEvent::Decrypted { raw, .. } => raw,
1512            ProcessedToDeviceEvent::UnableToDecrypt { encrypted_event, .. } => encrypted_event,
1513            ProcessedToDeviceEvent::PlainText(event) => event,
1514            ProcessedToDeviceEvent::Invalid(event) => event,
1515        }
1516    }
1517}
1518
1519#[cfg(test)]
1520mod tests {
1521    use std::{collections::BTreeMap, sync::Arc};
1522
1523    use assert_matches::assert_matches;
1524    use assert_matches2::assert_let;
1525    use insta::{assert_json_snapshot, with_settings};
1526    use ruma::{
1527        DeviceKeyAlgorithm, MilliSecondsSinceUnixEpoch, UInt, event_id,
1528        events::{AnySyncTimelineEvent, room::message::RoomMessageEventContent},
1529        owned_device_id, owned_user_id,
1530        serde::Raw,
1531    };
1532    use serde::Deserialize;
1533    use serde_json::json;
1534
1535    use super::{
1536        AlgorithmInfo, DecryptedRoomEvent, DeviceLinkProblem, EncryptionInfo, ShieldState,
1537        ShieldStateCode, TimelineEvent, TimelineEventKind, UnableToDecryptInfo,
1538        UnableToDecryptReason, UnsignedDecryptionResult, UnsignedEventLocation, VerificationLevel,
1539        VerificationState, WithheldCode,
1540    };
1541    use crate::deserialized_responses::{ThreadSummary, ThreadSummaryStatus};
1542
1543    fn example_event() -> serde_json::Value {
1544        json!({
1545            "content": RoomMessageEventContent::text_plain("secret"),
1546            "type": "m.room.message",
1547            "event_id": "$xxxxx:example.org",
1548            "room_id": "!someroom:example.com",
1549            "origin_server_ts": 2189,
1550            "sender": "@carl:example.com",
1551        })
1552    }
1553
1554    #[test]
1555    fn sync_timeline_debug_content() {
1556        let room_event =
1557            TimelineEvent::from_plaintext(Raw::new(&example_event()).unwrap().cast_unchecked());
1558        let debug_s = format!("{room_event:?}");
1559        assert!(
1560            !debug_s.contains("secret"),
1561            "Debug representation contains event content!\n{debug_s}"
1562        );
1563    }
1564
1565    #[test]
1566    fn old_verification_state_to_new_migration() {
1567        #[derive(Deserialize)]
1568        struct State {
1569            state: VerificationState,
1570        }
1571
1572        let state = json!({
1573            "state": "Trusted",
1574        });
1575        let deserialized: State =
1576            serde_json::from_value(state).expect("We can deserialize the old trusted value");
1577        assert_eq!(deserialized.state, VerificationState::Verified);
1578
1579        let state = json!({
1580            "state": "UnknownDevice",
1581        });
1582
1583        let deserialized: State =
1584            serde_json::from_value(state).expect("We can deserialize the old unknown device value");
1585
1586        assert_eq!(
1587            deserialized.state,
1588            VerificationState::Unverified(VerificationLevel::None(
1589                DeviceLinkProblem::MissingDevice
1590            ))
1591        );
1592
1593        let state = json!({
1594            "state": "Untrusted",
1595        });
1596        let deserialized: State =
1597            serde_json::from_value(state).expect("We can deserialize the old trusted value");
1598
1599        assert_eq!(
1600            deserialized.state,
1601            VerificationState::Unverified(VerificationLevel::UnsignedDevice)
1602        );
1603    }
1604
1605    #[test]
1606    fn test_verification_level_deserializes() {
1607        // Given a JSON VerificationLevel
1608        #[derive(Deserialize)]
1609        struct Container {
1610            verification_level: VerificationLevel,
1611        }
1612        let container = json!({ "verification_level": "VerificationViolation" });
1613
1614        // When we deserialize it
1615        let deserialized: Container = serde_json::from_value(container)
1616            .expect("We can deserialize the old PreviouslyVerified value");
1617
1618        // Then it is populated correctly
1619        assert_eq!(deserialized.verification_level, VerificationLevel::VerificationViolation);
1620    }
1621
1622    #[test]
1623    fn test_verification_level_deserializes_from_old_previously_verified_value() {
1624        // Given a JSON VerificationLevel with the old value PreviouslyVerified
1625        #[derive(Deserialize)]
1626        struct Container {
1627            verification_level: VerificationLevel,
1628        }
1629        let container = json!({ "verification_level": "PreviouslyVerified" });
1630
1631        // When we deserialize it
1632        let deserialized: Container = serde_json::from_value(container)
1633            .expect("We can deserialize the old PreviouslyVerified value");
1634
1635        // Then it is migrated to the new value
1636        assert_eq!(deserialized.verification_level, VerificationLevel::VerificationViolation);
1637    }
1638
1639    #[test]
1640    fn test_shield_state_code_deserializes() {
1641        // Given a JSON ShieldStateCode with value VerificationViolation
1642        #[derive(Deserialize)]
1643        struct Container {
1644            shield_state_code: ShieldStateCode,
1645        }
1646        let container = json!({ "shield_state_code": "VerificationViolation" });
1647
1648        // When we deserialize it
1649        let deserialized: Container = serde_json::from_value(container)
1650            .expect("We can deserialize the old PreviouslyVerified value");
1651
1652        // Then it is populated correctly
1653        assert_eq!(deserialized.shield_state_code, ShieldStateCode::VerificationViolation);
1654    }
1655
1656    #[test]
1657    fn test_shield_state_code_deserializes_from_old_previously_verified_value() {
1658        // Given a JSON ShieldStateCode with the old value PreviouslyVerified
1659        #[derive(Deserialize)]
1660        struct Container {
1661            shield_state_code: ShieldStateCode,
1662        }
1663        let container = json!({ "shield_state_code": "PreviouslyVerified" });
1664
1665        // When we deserialize it
1666        let deserialized: Container = serde_json::from_value(container)
1667            .expect("We can deserialize the old PreviouslyVerified value");
1668
1669        // Then it is migrated to the new value
1670        assert_eq!(deserialized.shield_state_code, ShieldStateCode::VerificationViolation);
1671    }
1672
1673    #[test]
1674    fn sync_timeline_event_serialisation() {
1675        let kind = TimelineEventKind::Decrypted(DecryptedRoomEvent {
1676            event: Raw::new(&example_event()).unwrap().cast_unchecked(),
1677            encryption_info: Arc::new(EncryptionInfo {
1678                sender: owned_user_id!("@sender:example.com"),
1679                sender_device: None,
1680                forwarder: None,
1681                algorithm_info: AlgorithmInfo::MegolmV1AesSha2 {
1682                    curve25519_key: "xxx".to_owned(),
1683                    sender_claimed_keys: Default::default(),
1684                    session_id: Some("xyz".to_owned()),
1685                },
1686                verification_state: VerificationState::Verified,
1687            }),
1688            unsigned_encryption_info: Some(BTreeMap::from([(
1689                UnsignedEventLocation::RelationsReplace,
1690                UnsignedDecryptionResult::UnableToDecrypt(UnableToDecryptInfo {
1691                    session_id: Some("xyz".to_owned()),
1692                    reason: UnableToDecryptReason::MalformedEncryptedEvent,
1693                }),
1694            )])),
1695        });
1696        let room_event = TimelineEvent {
1697            event_id: kind.parse_event_id(),
1698            kind,
1699            timestamp: Some(MilliSecondsSinceUnixEpoch(UInt::new_saturating(2189))),
1700            push_actions: Default::default(),
1701            thread_summary: ThreadSummaryStatus::Unknown,
1702        };
1703
1704        let serialized = serde_json::to_value(&room_event).unwrap();
1705
1706        // Test that the serialization is as expected
1707        assert_eq!(
1708            serialized,
1709            json!({
1710                "kind": {
1711                    "Decrypted": {
1712                        "event": {
1713                            "content": {"body": "secret", "msgtype": "m.text"},
1714                            "event_id": "$xxxxx:example.org",
1715                            "origin_server_ts": 2189,
1716                            "room_id": "!someroom:example.com",
1717                            "sender": "@carl:example.com",
1718                            "type": "m.room.message",
1719                        },
1720                        "encryption_info": {
1721                            "sender": "@sender:example.com",
1722                            "sender_device": null,
1723                            "forwarder": null,
1724                            "algorithm_info": {
1725                                "MegolmV1AesSha2": {
1726                                    "curve25519_key": "xxx",
1727                                    "sender_claimed_keys": {},
1728                                    "session_id": "xyz",
1729                                }
1730                            },
1731                            "verification_state": "Verified",
1732                        },
1733                        "unsigned_encryption_info": {
1734                            "RelationsReplace": {"UnableToDecrypt": {
1735                                "session_id": "xyz",
1736                                "reason": "MalformedEncryptedEvent",
1737                            }}
1738                        }
1739                    }
1740                },
1741                "timestamp": 2189,
1742            })
1743        );
1744
1745        // And it can be properly deserialized from the new format.
1746        let event: TimelineEvent = serde_json::from_value(serialized).unwrap();
1747        assert_eq!(event.event_id.as_deref(), Some(event_id!("$xxxxx:example.org")));
1748        assert_eq!(event.event_id.as_deref(), event.event_id());
1749        assert_matches!(
1750            event.encryption_info().unwrap().algorithm_info,
1751            AlgorithmInfo::MegolmV1AesSha2 { .. }
1752        );
1753        assert_eq!(event.timestamp(), Some(MilliSecondsSinceUnixEpoch(UInt::new_saturating(2189))));
1754        assert_eq!(event.timestamp(), event.timestamp_raw());
1755
1756        // Test that the previous format can also be deserialized.
1757        let serialized = json!({
1758            "event": {
1759                "content": {"body": "secret", "msgtype": "m.text"},
1760                "event_id": "$xxxxx:example.org",
1761                "origin_server_ts": 2189,
1762                "room_id": "!someroom:example.com",
1763                "sender": "@carl:example.com",
1764                "type": "m.room.message",
1765            },
1766            "encryption_info": {
1767                "sender": "@sender:example.com",
1768                "sender_device": null,
1769                "algorithm_info": {
1770                    "MegolmV1AesSha2": {
1771                        "curve25519_key": "xxx",
1772                        "sender_claimed_keys": {}
1773                    }
1774                },
1775                "verification_state": "Verified",
1776            },
1777        });
1778        let event: TimelineEvent = serde_json::from_value(serialized).unwrap();
1779        assert_eq!(event.event_id(), Some(event_id!("$xxxxx:example.org")));
1780        assert_matches!(
1781            event.encryption_info().unwrap().algorithm_info,
1782            AlgorithmInfo::MegolmV1AesSha2 { session_id: None, .. }
1783        );
1784        assert_eq!(event.timestamp(), Some(MilliSecondsSinceUnixEpoch(UInt::new_saturating(2189))));
1785        assert!(event.timestamp_raw().is_none());
1786
1787        // Test that the previous format, with an undecryptable unsigned event, can also
1788        // be deserialized.
1789        let serialized = json!({
1790            "event": {
1791                "content": {"body": "secret", "msgtype": "m.text"},
1792                "event_id": "$xxxxx:example.org",
1793                "origin_server_ts": 2189,
1794                "room_id": "!someroom:example.com",
1795                "sender": "@carl:example.com",
1796                "type": "m.room.message",
1797            },
1798            "encryption_info": {
1799                "sender": "@sender:example.com",
1800                "sender_device": null,
1801                "algorithm_info": {
1802                    "MegolmV1AesSha2": {
1803                        "curve25519_key": "xxx",
1804                        "sender_claimed_keys": {}
1805                    }
1806                },
1807                "verification_state": "Verified",
1808            },
1809            "unsigned_encryption_info": {
1810                "RelationsReplace": {"UnableToDecrypt": {"session_id": "xyz"}}
1811            }
1812        });
1813        let event: TimelineEvent = serde_json::from_value(serialized).unwrap();
1814        assert_eq!(event.event_id.as_deref(), event.event_id());
1815        assert_eq!(event.event_id.as_deref(), Some(event_id!("$xxxxx:example.org")));
1816        assert_matches!(
1817            event.encryption_info().unwrap().algorithm_info,
1818            AlgorithmInfo::MegolmV1AesSha2 { .. }
1819        );
1820        assert_eq!(event.timestamp(), Some(MilliSecondsSinceUnixEpoch(UInt::new_saturating(2189))));
1821        assert!(event.timestamp_raw().is_none());
1822        assert_matches!(event.kind, TimelineEventKind::Decrypted(decrypted) => {
1823            assert_matches!(decrypted.unsigned_encryption_info, Some(map) => {
1824                assert_eq!(map.len(), 1);
1825                let (location, result) = map.into_iter().next().unwrap();
1826                assert_eq!(location, UnsignedEventLocation::RelationsReplace);
1827                assert_matches!(result, UnsignedDecryptionResult::UnableToDecrypt(utd_info) => {
1828                    assert_eq!(utd_info.session_id, Some("xyz".to_owned()));
1829                    assert_eq!(utd_info.reason, UnableToDecryptReason::Unknown);
1830                })
1831            });
1832        });
1833    }
1834
1835    #[test]
1836    fn test_creating_or_deserializing_an_event_extracts_summary() {
1837        let event = json!({
1838            "event_id": "$eid:example.com",
1839            "type": "m.room.message",
1840            "sender": "@alice:example.com",
1841            "origin_server_ts": 42,
1842            "content": {
1843                "body": "Hello, world!",
1844            },
1845            "unsigned": {
1846                "m.relations": {
1847                    "m.thread": {
1848                        "latest_event": {
1849                            "event_id": "$latest_event:example.com",
1850                            "type": "m.room.message",
1851                            "sender": "@bob:example.com",
1852                            "origin_server_ts": 42,
1853                            "content": {
1854                                "body": "Hello to you too!",
1855                                "msgtype": "m.text",
1856                            }
1857                        },
1858                        "count": 2,
1859                        "current_user_participated": true,
1860                    }
1861                }
1862            }
1863        });
1864
1865        let raw = Raw::new(&event).unwrap().cast_unchecked();
1866
1867        // When creating a timeline event from a raw event, the thread summary is always
1868        // extracted, if available.
1869        let timeline_event = TimelineEvent::from_plaintext(raw);
1870        assert_matches!(timeline_event.thread_summary, ThreadSummaryStatus::Some(ThreadSummary { num_replies, latest_reply }) => {
1871            assert_eq!(num_replies, 2);
1872            assert_eq!(latest_reply.as_deref(), Some(event_id!("$latest_event:example.com")));
1873        });
1874
1875        // When deserializing an old serialized timeline event, the thread summary is
1876        // also extracted, if it wasn't serialized.
1877        let serialized_timeline_item = json!({
1878            "kind": {
1879                "PlainText": {
1880                    "event": event
1881                }
1882            }
1883        });
1884
1885        let timeline_event: TimelineEvent =
1886            serde_json::from_value(serialized_timeline_item).unwrap();
1887        assert_matches!(timeline_event.thread_summary, ThreadSummaryStatus::Unknown);
1888    }
1889
1890    #[test]
1891    fn sync_timeline_event_deserialisation_migration_for_withheld() {
1892        // Old serialized version was
1893        //    "utd_info": {
1894        //         "reason": "MissingMegolmSession",
1895        //         "session_id": "session000"
1896        //       }
1897
1898        // The new version would be
1899        //      "utd_info": {
1900        //         "reason": {
1901        //           "MissingMegolmSession": {
1902        //              "withheld_code": null
1903        //           }
1904        //         },
1905        //         "session_id": "session000"
1906        //       }
1907
1908        let serialized = json!({
1909             "kind": {
1910                "UnableToDecrypt": {
1911                  "event": {
1912                    "content": {
1913                      "algorithm": "m.megolm.v1.aes-sha2",
1914                      "ciphertext": "AwgAEoABzL1JYhqhjW9jXrlT3M6H8mJ4qffYtOQOnPuAPNxsuG20oiD/Fnpv6jnQGhU6YbV9pNM+1mRnTvxW3CbWOPjLKqCWTJTc7Q0vDEVtYePg38ncXNcwMmfhgnNAoW9S7vNs8C003x3yUl6NeZ8bH+ci870BZL+kWM/lMl10tn6U7snNmSjnE3ckvRdO+11/R4//5VzFQpZdf4j036lNSls/WIiI67Fk9iFpinz9xdRVWJFVdrAiPFwb8L5xRZ8aX+e2JDMlc1eW8gk",
1915                      "device_id": "SKCGPNUWAU",
1916                      "sender_key": "Gim/c7uQdSXyrrUbmUOrBT6sMC0gO7QSLmOK6B7NOm0",
1917                      "session_id": "hgLyeSqXfb8vc5AjQLsg6TSHVu0HJ7HZ4B6jgMvxkrs"
1918                    },
1919                    "event_id": "$xxxxx:example.org",
1920                    "origin_server_ts": 2189,
1921                    "room_id": "!someroom:example.com",
1922                    "sender": "@carl:example.com",
1923                    "type": "m.room.message"
1924                  },
1925                  "utd_info": {
1926                    "reason": "MissingMegolmSession",
1927                    "session_id": "session000"
1928                  }
1929                }
1930              }
1931        });
1932
1933        let result = serde_json::from_value(serialized);
1934        assert!(result.is_ok());
1935
1936        // should have migrated to the new format
1937        let event: TimelineEvent = result.unwrap();
1938        assert_matches!(
1939            event.kind,
1940            TimelineEventKind::UnableToDecrypt { utd_info, .. }=> {
1941                assert_matches!(
1942                    utd_info.reason,
1943                    UnableToDecryptReason::MissingMegolmSession { withheld_code: None }
1944                );
1945            }
1946        )
1947    }
1948
1949    #[test]
1950    fn unable_to_decrypt_info_migration_for_withheld() {
1951        let old_format = json!({
1952            "reason": "MissingMegolmSession",
1953            "session_id": "session000"
1954        });
1955
1956        let deserialized = serde_json::from_value::<UnableToDecryptInfo>(old_format).unwrap();
1957        let session_id = Some("session000".to_owned());
1958
1959        assert_eq!(deserialized.session_id, session_id);
1960        assert_eq!(
1961            deserialized.reason,
1962            UnableToDecryptReason::MissingMegolmSession { withheld_code: None },
1963        );
1964
1965        let new_format = json!({
1966             "session_id": "session000",
1967              "reason": {
1968                "MissingMegolmSession": {
1969                  "withheld_code": null
1970                }
1971              }
1972        });
1973
1974        let deserialized = serde_json::from_value::<UnableToDecryptInfo>(new_format).unwrap();
1975
1976        assert_eq!(
1977            deserialized.reason,
1978            UnableToDecryptReason::MissingMegolmSession { withheld_code: None },
1979        );
1980        assert_eq!(deserialized.session_id, session_id);
1981    }
1982
1983    #[test]
1984    fn unable_to_decrypt_reason_is_missing_room_key() {
1985        let reason = UnableToDecryptReason::MissingMegolmSession { withheld_code: None };
1986        assert!(reason.is_missing_room_key());
1987
1988        let reason = UnableToDecryptReason::MissingMegolmSession {
1989            withheld_code: Some(WithheldCode::Blacklisted),
1990        };
1991        assert!(!reason.is_missing_room_key());
1992
1993        let reason = UnableToDecryptReason::UnknownMegolmMessageIndex;
1994        assert!(reason.is_missing_room_key());
1995    }
1996
1997    #[test]
1998    fn snapshot_test_verification_level() {
1999        with_settings!({ prepend_module_to_snapshot => false }, {
2000            assert_json_snapshot!(VerificationLevel::VerificationViolation);
2001            assert_json_snapshot!(VerificationLevel::UnsignedDevice);
2002            assert_json_snapshot!(VerificationLevel::None(DeviceLinkProblem::InsecureSource));
2003            assert_json_snapshot!(VerificationLevel::None(DeviceLinkProblem::MissingDevice));
2004            assert_json_snapshot!(VerificationLevel::UnverifiedIdentity);
2005        });
2006    }
2007
2008    #[test]
2009    fn snapshot_test_verification_states() {
2010        with_settings!({ prepend_module_to_snapshot => false }, {
2011            assert_json_snapshot!(VerificationState::Unverified(VerificationLevel::UnsignedDevice));
2012            assert_json_snapshot!(VerificationState::Unverified(
2013                VerificationLevel::VerificationViolation
2014            ));
2015            assert_json_snapshot!(VerificationState::Unverified(VerificationLevel::None(
2016                DeviceLinkProblem::InsecureSource,
2017            )));
2018            assert_json_snapshot!(VerificationState::Unverified(VerificationLevel::None(
2019                DeviceLinkProblem::MissingDevice,
2020            )));
2021            assert_json_snapshot!(VerificationState::Verified);
2022        });
2023    }
2024
2025    #[test]
2026    fn snapshot_test_shield_states() {
2027        with_settings!({ prepend_module_to_snapshot => false }, {
2028            assert_json_snapshot!(ShieldState::None);
2029            assert_json_snapshot!(ShieldState::Red {
2030                code: ShieldStateCode::UnverifiedIdentity,
2031                message: "a message"
2032            });
2033            assert_json_snapshot!(ShieldState::Grey {
2034                code: ShieldStateCode::AuthenticityNotGuaranteed,
2035                message: "authenticity of this message cannot be guaranteed",
2036            });
2037        });
2038    }
2039
2040    #[test]
2041    fn snapshot_test_shield_codes() {
2042        with_settings!({ prepend_module_to_snapshot => false }, {
2043            assert_json_snapshot!(ShieldStateCode::AuthenticityNotGuaranteed);
2044            assert_json_snapshot!(ShieldStateCode::UnknownDevice);
2045            assert_json_snapshot!(ShieldStateCode::UnsignedDevice);
2046            assert_json_snapshot!(ShieldStateCode::UnverifiedIdentity);
2047            assert_json_snapshot!(ShieldStateCode::VerificationViolation);
2048        });
2049    }
2050
2051    #[test]
2052    fn snapshot_test_algorithm_info() {
2053        let mut map = BTreeMap::new();
2054        map.insert(DeviceKeyAlgorithm::Curve25519, "claimedclaimedcurve25519".to_owned());
2055        map.insert(DeviceKeyAlgorithm::Ed25519, "claimedclaimeded25519".to_owned());
2056        let info = AlgorithmInfo::MegolmV1AesSha2 {
2057            curve25519_key: "curvecurvecurve".into(),
2058            sender_claimed_keys: BTreeMap::from([
2059                (DeviceKeyAlgorithm::Curve25519, "claimedclaimedcurve25519".to_owned()),
2060                (DeviceKeyAlgorithm::Ed25519, "claimedclaimeded25519".to_owned()),
2061            ]),
2062            session_id: None,
2063        };
2064
2065        with_settings!({ prepend_module_to_snapshot => false }, {
2066            assert_json_snapshot!(info);
2067        });
2068    }
2069
2070    #[test]
2071    fn test_encryption_info_migration() {
2072        // In the old format the session_id was in the EncryptionInfo, now
2073        // it is moved to the `algorithm_info` struct.
2074        let old_format = json!({
2075          "sender": "@alice:localhost",
2076          "sender_device": "ABCDEFGH",
2077          "algorithm_info": {
2078            "MegolmV1AesSha2": {
2079              "curve25519_key": "curvecurvecurve",
2080              "sender_claimed_keys": {}
2081            }
2082          },
2083          "verification_state": "Verified",
2084          "session_id": "mysessionid76"
2085        });
2086
2087        let deserialized = serde_json::from_value::<EncryptionInfo>(old_format).unwrap();
2088        let expected_session_id = Some("mysessionid76".to_owned());
2089
2090        assert_let!(
2091            AlgorithmInfo::MegolmV1AesSha2 { session_id, .. } = deserialized.algorithm_info.clone()
2092        );
2093        assert_eq!(session_id, expected_session_id);
2094
2095        assert_json_snapshot!(deserialized);
2096    }
2097
2098    #[test]
2099    fn snapshot_test_encryption_info() {
2100        let info = EncryptionInfo {
2101            sender: owned_user_id!("@alice:localhost"),
2102            sender_device: Some(owned_device_id!("ABCDEFGH")),
2103            forwarder: None,
2104            algorithm_info: AlgorithmInfo::MegolmV1AesSha2 {
2105                curve25519_key: "curvecurvecurve".into(),
2106                sender_claimed_keys: Default::default(),
2107                session_id: Some("mysessionid76".to_owned()),
2108            },
2109            verification_state: VerificationState::Verified,
2110        };
2111
2112        with_settings!({ sort_maps => true, prepend_module_to_snapshot => false }, {
2113            assert_json_snapshot!(info);
2114        })
2115    }
2116
2117    #[test]
2118    fn snapshot_test_sync_timeline_event() {
2119        let kind = TimelineEventKind::Decrypted(DecryptedRoomEvent {
2120            event: Raw::new(&example_event()).unwrap().cast_unchecked(),
2121            encryption_info: Arc::new(EncryptionInfo {
2122                sender: owned_user_id!("@sender:example.com"),
2123                sender_device: Some(owned_device_id!("ABCDEFGHIJ")),
2124                forwarder: None,
2125                algorithm_info: AlgorithmInfo::MegolmV1AesSha2 {
2126                    curve25519_key: "xxx".to_owned(),
2127                    sender_claimed_keys: BTreeMap::from([
2128                        (
2129                            DeviceKeyAlgorithm::Ed25519,
2130                            "I3YsPwqMZQXHkSQbjFNEs7b529uac2xBpI83eN3LUXo".to_owned(),
2131                        ),
2132                        (
2133                            DeviceKeyAlgorithm::Curve25519,
2134                            "qzdW3F5IMPFl0HQgz5w/L5Oi/npKUFn8Um84acIHfPY".to_owned(),
2135                        ),
2136                    ]),
2137                    session_id: Some("mysessionid112".to_owned()),
2138                },
2139                verification_state: VerificationState::Verified,
2140            }),
2141            unsigned_encryption_info: Some(BTreeMap::from([(
2142                UnsignedEventLocation::RelationsThreadLatestEvent,
2143                UnsignedDecryptionResult::UnableToDecrypt(UnableToDecryptInfo {
2144                    session_id: Some("xyz".to_owned()),
2145                    reason: UnableToDecryptReason::MissingMegolmSession {
2146                        withheld_code: Some(WithheldCode::Unverified),
2147                    },
2148                }),
2149            )])),
2150        });
2151        let room_event = TimelineEvent {
2152            event_id: kind.parse_event_id(),
2153            kind,
2154            timestamp: Some(MilliSecondsSinceUnixEpoch(UInt::new_saturating(2189))),
2155            push_actions: Default::default(),
2156            thread_summary: ThreadSummaryStatus::Some(ThreadSummary {
2157                num_replies: 2,
2158                latest_reply: None,
2159            }),
2160        };
2161
2162        with_settings!({ sort_maps => true, prepend_module_to_snapshot => false }, {
2163            // We use directly the serde_json formatter here, because of a bug in insta
2164            // not serializing custom BTreeMap key enum https://github.com/mitsuhiko/insta/issues/689
2165            assert_json_snapshot! {
2166                serde_json::to_value(&room_event).unwrap(),
2167            }
2168        });
2169    }
2170
2171    #[test]
2172    fn test_from_bundled_latest_event_keeps_session_id() {
2173        let session_id = "hgLyeSqXfb8vc5AjQLsg6TSHVu0HJ7HZ4B6jgMvxkrs";
2174        let serialized = json!({
2175            "content": {
2176              "algorithm": "m.megolm.v1.aes-sha2",
2177              "ciphertext": "AwgAEoABzL1JYhqhjW9jXrlT3M6H8mJ4qffYtOQOnPuAPNxsuG20oiD/Fnpv6jnQGhU6YbV9pNM+1mRnTvxW3CbWOPjLKqCWTJTc7Q0vDEVtYePg38ncXNcwMmfhgnNAoW9S7vNs8C003x3yUl6NeZ8bH+ci870BZL+kWM/lMl10tn6U7snNmSjnE3ckvRdO+11/R4//5VzFQpZdf4j036lNSls/WIiI67Fk9iFpinz9xdRVWJFVdrAiPFwb8L5xRZ8aX+e2JDMlc1eW8gk",
2178              "device_id": "SKCGPNUWAU",
2179              "sender_key": "Gim/c7uQdSXyrrUbmUOrBT6sMC0gO7QSLmOK6B7NOm0",
2180              "session_id": session_id,
2181            },
2182            "event_id": "$xxxxx:example.org",
2183            "origin_server_ts": 2189,
2184            "room_id": "!someroom:example.com",
2185            "sender": "@carl:example.com",
2186            "type": "m.room.encrypted"
2187        });
2188        let json = serialized.to_string();
2189        let value = Raw::<AnySyncTimelineEvent>::from_json_string(json).unwrap();
2190
2191        let kind = TimelineEventKind::UnableToDecrypt {
2192            event: value.clone(),
2193            utd_info: UnableToDecryptInfo {
2194                session_id: None,
2195                reason: UnableToDecryptReason::Unknown,
2196            },
2197        };
2198        let result = TimelineEvent::from_bundled_latest_event(
2199            &kind,
2200            value.cast_unchecked(),
2201            MilliSecondsSinceUnixEpoch::now(),
2202        )
2203        .expect("Could not get bundled latest event");
2204
2205        assert_let!(TimelineEventKind::UnableToDecrypt { utd_info, .. } = result.kind);
2206        assert!(utd_info.session_id.is_some());
2207        assert_eq!(utd_info.session_id.unwrap(), session_id);
2208    }
2209
2210    #[test]
2211    fn test_timeline_event_replace_raw_update_the_event_id() {
2212        let mut timeline_event = TimelineEvent::from_plaintext(
2213            Raw::new(&json!({
2214                "event_id": "$ev0",
2215                "type": "m.room.message",
2216                "sender": "@alice",
2217                "origin_server_ts": 42,
2218                "content": {
2219                    "body": "Hello, World!",
2220                },
2221                "unsigned": {},
2222            }))
2223            .unwrap()
2224            .cast_unchecked(),
2225        );
2226
2227        assert_eq!(timeline_event.event_id(), Some(event_id!("$ev0")));
2228
2229        timeline_event.replace_raw(
2230            Raw::new(&json!({
2231                "event_id": "$ev1",
2232                "type": "m.room.message",
2233                "sender": "@bob",
2234                "origin_server_ts": 153,
2235                "content": {
2236                    "body": "Bonjour !",
2237                },
2238                "unsigned": {},
2239            }))
2240            .unwrap()
2241            .cast_unchecked(),
2242        );
2243
2244        assert_eq!(timeline_event.event_id(), Some(event_id!("$ev1")));
2245    }
2246}