Skip to main content

matrix_sdk/event_cache/
redecryptor.rs

1// Copyright 2025 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The Redecryptor (affectionately known as R2D2) is a layer and long-running
16//! background task which handles redecryption of events in case we couldn't
17//! decrypt them immediately.
18//!
19//! There are various reasons why a room key might not be available immediately
20//! when the event becomes available:
21//!     - The to-device message containing the room key just arrives late, i.e.
22//!       after the room event.
23//!     - The event is a historic event and we need to first download the room
24//!       key from the backup.
25//!     - The event is a historic event in a previously unjoined room, we need
26//!       to receive historic room keys as defined in [MSC3061].
27//!
28//! R2D2 listens to the [`OlmMachine`] for received room keys and new
29//! m.room_key.withheld events.
30//!
31//! If a new room key has been received, it attempts to find any UTDs in the
32//! [`EventCache`]. If R2D2 decrypts any UTDs from the event cache, it will
33//! replace the events in the cache and send out new [`RoomEventCacheUpdate`]s
34//! to any of its listeners.
35//!
36//! If a new withheld info has been received, it attempts to find any relevant
37//! events and updates the [`EncryptionInfo`] of an event.
38//!
39//! There's an additional gotcha: the [`OlmMachine`] might get recreated by
40//! calls to [`BaseClient::regenerate_olm()`]. When this happens, we will
41//! receive a `None` on the room keys stream and we need to re-listen to it.
42//!
43//! Another gotcha is that room keys might be received on another process if the
44//! [`Client`] is operating on a Apple iOS device. A separate process is used
45//! in this case to receive push notifications. In this case, the room key will
46//! be received and R2D2 won't get notified about it. To work around this,
47//! decryption requests can be explicitly sent to R2D2.
48//!
49//! The final gotcha is that a room key might be received just in between the
50//! time the event was initially tried to be decrypted and the time it took to
51//! persist it in the event cache. To handle this race condition, R2D2 listens
52//! to the event cache and attempts to decrypt any UTDs the event cache
53//! persists.
54//!
55//! In the graph below, the Timeline block is meant to be the `Timeline` from
56//! the `matrix-sdk-ui` crate, but it could be any other listener that
57//! subscribes to [`RedecryptorReport`] stream.
58//!
59//! ```markdown
60//! 
61//!      .----------------------.
62//!     |                        |
63//!     |      Beeb, boop!       |
64//!     |                        .
65//!      ----------------------._ \
66//!                               -;  _____
67//!                                 .`/L|__`.
68//!                                / =[_]O|` \
69//!                                |"+_____":|
70//!                              __:='|____`-:__
71//!                             ||[] ||====|| []||
72//!                             ||[] ||====|| []||
73//!                             |:== ||====|| ==:|
74//!                             ||[] ||====|| []||
75//!                             ||[] ||====|| []||
76//!                            _||_  ||====||  _||_
77//!                           (====) |:====:| (====)
78//!                            }--{  | |  | |  }--{
79//!                           (____) |_|  |_| (____)
80//!
81//!                              ┌─────────────┐
82//!                              │             │
83//!                  ┌───────────┤   Timeline  │◄────────────┐
84//!                  │           │             │             │
85//!                  │           └──────▲──────┘             │
86//!                  │                  │                    │
87//!                  │                  │                    │
88//!                  │                  │                    │
89//!              Decryption             │                Redecryptor
90//!                request              │                  report
91//!                  │        RoomEventCacheUpdates          │
92//!                  │                  │                    │
93//!                  │                  │                    │
94//!                  │      ┌───────────┴───────────┐        │
95//!                  │      │                       │        │
96//!                  └──────►         R2D2          │────────┘
97//!                         │                       │
98//!                         └──▲─────────────────▲──┘
99//!                            │                 │
100//!                            │                 │
101//!                            │                 │
102//!                         Received        Received room
103//!                          events          keys stream
104//!                            │                 │
105//!                            │                 │
106//!                            │                 │
107//!                    ┌───────┴──────┐  ┌───────┴──────┐
108//!                    │              │  │              │
109//!                    │  Event Cache │  │  OlmMachine  │
110//!                    │              │  │              │
111//!                    └──────────────┘  └──────────────┘
112//! ```
113//!
114//! [MSC3061]: https://github.com/matrix-org/matrix-spec/pull/1655#issuecomment-2213152255
115
116use std::{
117    borrow::Cow,
118    collections::{BTreeMap, BTreeSet, VecDeque},
119    mem,
120    pin::pin,
121    sync::{Arc, Weak},
122};
123
124use as_variant::as_variant;
125use futures_core::Stream;
126use futures_util::{StreamExt, future::try_join_all};
127#[cfg(feature = "e2e-encryption")]
128use matrix_sdk_base::deserialized_responses::UnableToDecryptReason;
129#[cfg(doc)]
130use matrix_sdk_base::{BaseClient, crypto::OlmMachine};
131use matrix_sdk_base::{
132    crypto::{
133        store::types::{RoomKeyInfo, RoomKeyWithheldInfo},
134        types::events::room::encrypted::EncryptedEvent,
135    },
136    deserialized_responses::{DecryptedRoomEvent, TimelineEvent, TimelineEventKind},
137    locks::Mutex,
138    task_monitor::BackgroundTaskHandle,
139    timer,
140};
141#[cfg(doc)]
142use matrix_sdk_common::deserialized_responses::EncryptionInfo;
143use ruma::{
144    OwnedEventId, OwnedRoomId, RoomId,
145    events::{AnySyncTimelineEvent, room::encrypted::OriginalSyncRoomEncryptedEvent},
146    push::Action,
147    serde::Raw,
148};
149use tokio::sync::{
150    Notify,
151    broadcast::{self, Sender},
152    mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel},
153};
154use tokio_stream::wrappers::{
155    BroadcastStream, UnboundedReceiverStream, errors::BroadcastStreamRecvError,
156};
157use tracing::{info, instrument, trace, warn};
158
159#[cfg(doc)]
160use super::RoomEventCache;
161use super::{
162    EventCache, EventCacheError, EventCacheInner, EventsOrigin, RoomEventCacheGenericUpdate,
163    RoomEventCacheUpdate, TimelineVectorDiffs,
164    caches::{
165        EventLocation,
166        event_linked_chunk::EventLinkedChunk,
167        room::{LinkedChunkUpdateSender, RoomEventCacheLinkedChunkUpdate},
168    },
169};
170use crate::{Client, Result, Room, encryption::backups::BackupState, room::PushContext};
171
172type SessionId<'a> = &'a str;
173type OwnedSessionId = String;
174
175type EventIdAndUtd = (OwnedEventId, Raw<AnySyncTimelineEvent>);
176type EventIdAndEvent = (OwnedEventId, DecryptedRoomEvent);
177
178#[derive(Clone)]
179pub(super) struct ResolvedUtd {
180    pub event_id: OwnedEventId,
181    decrypted_event: DecryptedRoomEvent,
182    actions: Option<Vec<Action>>,
183}
184
185#[derive(Clone)]
186pub(super) enum MaybeResolvedEvent {
187    NotYet(ResolvedUtd),
188    Resolved(TimelineEvent),
189}
190
191impl MaybeResolvedEvent {
192    pub fn try_resolve_event(self, mut unresolved_event: TimelineEvent) -> Self {
193        match self {
194            Self::NotYet(resolved_utd) => {
195                // There is a race between the multiple sources of updates. It's
196                // possible that two sources trigger a decryption for the same
197                // event (for example, the room key stream and the event cache
198                // updates). It is then likely that the event has been already
199                // resolved. This race is fine, but we should avoid to replace
200                // an event that has already been resolved as it is a
201                // non-negligible operation.
202                //
203                // Note that a simple check like “event's kind is
204                // `UnableToDecrypt`” is not enough. The event can already be
205                // decrypted but its encryption info can change. So we must
206                // ensure they are also different.
207                if matches!(unresolved_event.kind, TimelineEventKind::UnableToDecrypt { .. })
208                    || unresolved_event.encryption_info()
209                        != Some(&resolved_utd.decrypted_event.encryption_info)
210                {
211                    unresolved_event.kind =
212                        TimelineEventKind::Decrypted(resolved_utd.decrypted_event);
213
214                    if let Some(actions) = resolved_utd.actions {
215                        unresolved_event.set_push_actions(actions);
216                    }
217
218                    // The unresolved event becomes resolved :-].
219                    Self::Resolved(unresolved_event)
220                } else {
221                    Self::NotYet(resolved_utd)
222                }
223            }
224
225            Self::Resolved(event) => Self::Resolved(event),
226        }
227    }
228
229    pub fn as_resolved(&self) -> Option<&TimelineEvent> {
230        if let Self::Resolved(event) = self { Some(event) } else { None }
231    }
232}
233
234/// Internal trait to resolve events on a `&[MaybeResolvedEvent]` with the help
235/// of `Cow` to avoid copying if no event is newly resolved.
236pub(super) trait TryResolveEvents {
237    fn try_resolve_events(
238        &self,
239        event_linked_chunk: &EventLinkedChunk,
240    ) -> Cow<'_, [MaybeResolvedEvent]>;
241}
242
243impl TryResolveEvents for [MaybeResolvedEvent] {
244    fn try_resolve_events(
245        &self,
246        event_linked_chunk: &EventLinkedChunk,
247    ) -> Cow<'_, [MaybeResolvedEvent]> {
248        let mut new_resolved_events = Cow::Borrowed(self);
249
250        for (nth, resolved_event) in self.iter().enumerate() {
251            match resolved_event {
252                MaybeResolvedEvent::NotYet(resolved_utd) => {
253                    // Event has not been resolved. Let's try to locate the
254                    // corresponding event with the provided `EventLinkedChunk`
255                    // and try to resolve it.
256
257                    if let Some((_location, event)) =
258                        event_linked_chunk.find_event(&resolved_utd.event_id)
259                    {
260                        let new_resolved_event = MaybeResolvedEvent::NotYet(resolved_utd.clone())
261                            .try_resolve_event(event);
262
263                        if matches!(new_resolved_event, MaybeResolvedEvent::Resolved(_)) {
264                            // Use `slice::get_unchecked_mut` to avoid a bounds
265                            // check.
266                            //
267                            // SAFETY: `self` and `new_resolved_events` have the
268                            // same size and represent the same data. Thus, the
269                            // index `nth` exists in `new_resolved_events`.
270                            unsafe {
271                                *new_resolved_events.to_mut().get_unchecked_mut(nth) =
272                                    new_resolved_event;
273                            }
274                        }
275                    }
276                }
277
278                MaybeResolvedEvent::Resolved(_event) => {
279                    // Event has already been resolved. Nothing to do.
280                }
281            }
282        }
283
284        new_resolved_events
285    }
286}
287
288/// The information sent across the channel to the long-running task requesting
289/// that the supplied set of sessions be retried.
290#[derive(Debug, Clone)]
291pub struct DecryptionRetryRequest {
292    /// The room ID of the room the events belong to.
293    pub room_id: OwnedRoomId,
294    /// Events that are not decrypted.
295    pub utd_session_ids: BTreeSet<OwnedSessionId>,
296    /// Events that are decrypted but might need to have their
297    /// [`EncryptionInfo`] refreshed.
298    pub refresh_info_session_ids: BTreeSet<OwnedSessionId>,
299}
300
301/// A report coming from the redecryptor.
302#[derive(Debug, Clone)]
303pub enum RedecryptorReport {
304    /// Events which we were able to decrypt.
305    ResolvedUtds {
306        /// The room ID of the room the events belong to.
307        room_id: OwnedRoomId,
308        /// The list of event IDs of the decrypted events.
309        events: BTreeSet<OwnedEventId>,
310    },
311    /// The redecryptor might have missed some room keys so it might not have
312    /// re-decrypted events that are now decryptable.
313    Lagging,
314    /// A room key backup has become available.
315    ///
316    /// This means that components might want to tell R2D2 about events they
317    /// care about to attempt a decryption.
318    BackupAvailable,
319}
320
321pub(super) struct RedecryptorChannels {
322    utd_reporter: Sender<RedecryptorReport>,
323    pub(super) decryption_request_sender: UnboundedSender<DecryptionRetryRequest>,
324    pub(super) decryption_request_receiver:
325        Mutex<Option<UnboundedReceiver<DecryptionRetryRequest>>>,
326}
327
328impl RedecryptorChannels {
329    pub(super) fn new() -> Self {
330        let (utd_reporter, _) = broadcast::channel(100);
331        let (decryption_request_sender, decryption_request_receiver) = unbounded_channel();
332
333        Self {
334            utd_reporter,
335            decryption_request_sender,
336            decryption_request_receiver: Mutex::new(Some(decryption_request_receiver)),
337        }
338    }
339}
340
341/// A function which can be used to filter and map [`TimelineEvent`]s into a
342/// tuple of event ID and raw [`AnySyncTimelineEvent`].
343///
344/// The tuple can be used to attempt to redecrypt events.
345fn filter_timeline_event_to_utd(
346    event: TimelineEvent,
347) -> Option<(OwnedEventId, Raw<AnySyncTimelineEvent>)> {
348    let event_id = event.event_id().map(ToOwned::to_owned);
349
350    // Only pick out events that are UTDs, get just the Raw event as this is
351    // what the OlmMachine needs.
352    let event = as_variant!(event.kind, TimelineEventKind::UnableToDecrypt { event, .. } => event);
353    // Zip the event ID and event together so we don't have to pick out the
354    // event ID again. We need the event ID to replace the event in the cache.
355    event_id.zip(event)
356}
357
358/// A function which can be used to filter an map [`TimelineEvent`]s into a
359/// tuple of event ID and [`DecryptedRoomEvent`].
360///
361/// The tuple can be used to attempt to update the encryption info of the
362/// decrypted event.
363fn filter_timeline_event_to_decrypted(
364    event: TimelineEvent,
365) -> Option<(OwnedEventId, DecryptedRoomEvent)> {
366    let event_id = event.event_id().map(ToOwned::to_owned);
367
368    let event = as_variant!(event.kind, TimelineEventKind::Decrypted(event) => event);
369    // Zip the event ID and event together so we don't have to pick out the
370    // event ID again. We need the event ID to replace the event in the cache.
371    event_id.zip(event)
372}
373
374impl EventCacheInner {
375    /// Retrieve a set of events that we weren't able to decrypt.
376    ///
377    /// # Arguments
378    ///
379    /// - `room_id` - The ID of the room where the events were sent to.
380    /// - `session_id` - The unique ID of the room key that was used to encrypt
381    ///   the event.
382    async fn all_encrypted_events(
383        &self,
384        room_id: &RoomId,
385        session_id: SessionId<'_>,
386    ) -> Result<Vec<EventIdAndUtd>, EventCacheError> {
387        let caches = self.all_caches_for_room(room_id).await?;
388
389        Ok(caches
390            .all_events_of_type(Some("m.room.encrypted"), Some(session_id))
391            .await?
392            .filter_map(filter_timeline_event_to_utd)
393            .collect())
394    }
395
396    /// Retrieve a set of events that we weren't able to decrypt from the memory
397    /// of the event cache.
398    async fn all_in_memory_encrypted_events(&self) -> BTreeMap<OwnedRoomId, Vec<EventIdAndUtd>> {
399        let mut utds = BTreeMap::new();
400
401        for (room_id, caches) in self.by_room.read().await.iter() {
402            let room_utds: Vec<_> = caches
403                .all_in_memory_events()
404                .await
405                .into_iter()
406                .flatten()
407                .filter_map(filter_timeline_event_to_utd)
408                .collect();
409
410            utds.insert(room_id.to_owned(), room_utds);
411        }
412
413        utds
414    }
415
416    async fn all_decrypted_events(
417        &self,
418        room_id: &RoomId,
419        session_id: SessionId<'_>,
420    ) -> Result<Vec<EventIdAndEvent>, EventCacheError> {
421        let caches = self.all_caches_for_room(room_id).await?;
422
423        Ok(caches
424            .all_events_of_type(None, Some(session_id))
425            .await?
426            .filter_map(filter_timeline_event_to_decrypted)
427            .collect())
428    }
429
430    async fn all_in_memory_decrypted_events(&self) -> BTreeMap<OwnedRoomId, Vec<EventIdAndEvent>> {
431        let mut decrypted_events = BTreeMap::new();
432
433        for (room_id, caches) in self.by_room.read().await.iter() {
434            let room_utds: Vec<_> = caches
435                .all_in_memory_events()
436                .await
437                .into_iter()
438                .flatten()
439                .filter_map(filter_timeline_event_to_decrypted)
440                .collect();
441
442            decrypted_events.insert(room_id.to_owned(), room_utds);
443        }
444
445        decrypted_events
446    }
447
448    /// Handle a chunk of events that we were previously unable to decrypt but
449    /// have now successfully decrypted.
450    ///
451    /// This function will replace the existing UTD events in memory and the
452    /// store and send out a [`RoomEventCacheUpdate`] for the newly decrypted
453    /// events.
454    ///
455    /// # Arguments
456    ///
457    /// - `room_id` - The ID of the room where the events were sent to.
458    /// - `events` - A chunk of events that were successfully decrypted.
459    #[instrument(skip_all, fields(room_id))]
460    async fn on_resolved_utds(
461        &self,
462        room_id: &RoomId,
463        resolved_utds: Vec<ResolvedUtd>,
464    ) -> Result<(), EventCacheError> {
465        if resolved_utds.is_empty() {
466            trace!("No events were redecrypted or updated, nothing to replace");
467            return Ok(());
468        }
469
470        timer!("Resolving UTDs");
471
472        let event_ids: BTreeSet<_> =
473            resolved_utds.iter().map(|resolved_utd| resolved_utd.event_id.clone()).collect();
474
475        let all_caches = self.all_caches_for_room(room_id).await?;
476        let mut maybe_resolved_events = Vec::with_capacity(resolved_utds.len());
477
478        // # Room cache, thread caches, and pinned-event cache
479        //
480        // For each resolved UTD, find the corresponding event (either in-store
481        // or in-memory of the room cache), build the resolved event, and
482        // replace it in the store. We use the room cache for that because it
483        // contains all events (there is an exception with the event-focused
484        // cache, see below).
485        //
486        // # Event-focused cache
487        //
488        // Events received by the sync or pagination are not forwarded to the
489        // event-focused cache: it handles its own set of events. All of them
490        // live in-memory, there are not put in the store by any cache. So this
491        // cache will miss all UTD resolutions. To address that, the
492        // event-focused cache resolves UTD on its own, without the general
493        // logic described above.
494        {
495            let room_cache = &all_caches.room;
496            let mut state = room_cache.state().write().await?;
497
498            let mut maybe_resolved_in_memory_events = Vec::new();
499
500            for resolved_utd in resolved_utds {
501                // Try to locate the event (either in-store or in-memory).
502                if let Some((location, event)) = state.find_event(&resolved_utd.event_id).await? {
503                    let maybe_resolved_event =
504                        MaybeResolvedEvent::NotYet(resolved_utd).try_resolve_event(event);
505
506                    // It is an in-memory event, let's keep it apart to replace
507                    // in-memory UTDs.
508                    if matches!(location, EventLocation::Memory(_)) {
509                        maybe_resolved_in_memory_events.push(maybe_resolved_event.clone());
510                    }
511
512                    // Even is known, let's keep it for later, even if
513                    // unresolved.
514                    maybe_resolved_events.push(maybe_resolved_event);
515                } else {
516                    // Event is unknown by the room cache, the thread caches,
517                    // nor the pinned-events cache. However, it might be known
518                    // by an event-focused cache! So let's keep it for later.
519                    maybe_resolved_events.push(MaybeResolvedEvent::NotYet(resolved_utd));
520                }
521            }
522
523            // Replace all resolved events in the store.
524            state
525                .save_events(
526                    maybe_resolved_events
527                        .iter()
528                        .filter_map(|resolved_event| resolved_event.as_resolved())
529                        .cloned(),
530                )
531                .await?;
532
533            // Saving events doesn't notify the linked chunk update observers,
534            // so index the resolved events explicitly.
535            #[cfg(feature = "experimental-search")]
536            self.linked_chunk_update_sender.send_to_search_index(
537                room_id.to_owned(),
538                maybe_resolved_events
539                    .iter()
540                    .filter_map(|resolved_event| resolved_event.as_resolved())
541                    .cloned()
542                    .collect(),
543            );
544
545            // Now, replace the in-memory events.
546            let timeline_event_diffs = state
547                .replace_in_memory_utds(&maybe_resolved_in_memory_events)
548                .await?
549                .unwrap_or_default();
550
551            if !timeline_event_diffs.is_empty() {
552                state.update_sender.send(
553                    RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs {
554                        diffs: timeline_event_diffs,
555                        origin: EventsOrigin::Cache,
556                    }),
557                    Some(RoomEventCacheGenericUpdate { room_id: room_id.to_owned() }),
558                );
559            }
560        }
561
562        // Resolve in-memory UTDs on the thread caches.
563        {
564            // TODO: This ain't great for performance; there shouldn't be that
565            // many thread caches alive at the same time, but they could
566            // accumulate over time. Consider keeping track of which linked
567            // chunk contains which event ID, to avoid doing the linear searches
568            // here.
569
570            // Replaces UTDs in each thread, and maybe update the thread
571            // summary.
572            for (thread_id, thread_cache) in try_join_all(
573                all_caches.threads.read().await.iter().map(|(thread_id, thread_cache)| async {
574                    Result::<_, EventCacheError>::Ok(
575                        // If at least one event has been replaced, return the
576                        // `thread_id` and the `thread_cache` to update the
577                        // thread summary later.
578                        thread_cache
579                            .replace_in_memory_utds(&maybe_resolved_events)
580                            .await?
581                            .then(|| (thread_id.clone(), thread_cache.clone())),
582                    )
583                }),
584            )
585            .await?
586            .into_iter()
587            // Filter out results that are `None`, i.e. a thread where no UTD has been replaced.
588            .flatten()
589            {
590                let new_thread_summary = thread_cache.update_thread_summary().await?;
591
592                all_caches.room.update_thread_summary(&thread_id, new_thread_summary)?;
593            }
594        }
595
596        // Resolve in-memory UTDs on the pinned-events cache.
597        if let Some(pinned_events_cache) = all_caches.pinned_events.get() {
598            pinned_events_cache.replace_in_memory_utds(&maybe_resolved_events).await?;
599        }
600
601        // Resolve in-memory UTDs on the event-focused caches.
602        {
603            // TODO: This ain't great for performance; there shouldn't be that
604            // many event-focused caches alive at the same time, but they could
605            // accumulate over time. Consider keeping track of which linked
606            // chunk contains which event ID, to avoid doing the linear searches
607            // here.
608            try_join_all(all_caches.event_focused.read().await.values().map(
609                |event_focused_cache| {
610                    event_focused_cache.replace_in_memory_utds(&maybe_resolved_events)
611                },
612            ))
613            .await?;
614        }
615
616        let report =
617            RedecryptorReport::ResolvedUtds { room_id: room_id.to_owned(), events: event_ids };
618        let _ = self.redecryption_channels.utd_reporter.send(report);
619
620        Ok(())
621    }
622
623    /// Attempt to decrypt a single event.
624    async fn decrypt_event(
625        &self,
626        room_id: &RoomId,
627        room: Option<&Room>,
628        push_context: Option<&PushContext>,
629        event: &Raw<EncryptedEvent>,
630    ) -> Option<(DecryptedRoomEvent, Option<Vec<Action>>)> {
631        if let Some(room) = room {
632            match room
633                .decrypt_event(
634                    event.cast_ref_unchecked::<OriginalSyncRoomEncryptedEvent>(),
635                    push_context,
636                )
637                .await
638            {
639                Ok(maybe_decrypted) => {
640                    let actions = maybe_decrypted.push_actions().map(|a| a.to_vec());
641
642                    if let TimelineEventKind::Decrypted(decrypted) = maybe_decrypted.kind {
643                        Some((decrypted, actions))
644                    } else {
645                        warn!(
646                            "Failed to redecrypt an event despite receiving a room key or request to redecrypt"
647                        );
648                        None
649                    }
650                }
651                Err(e) => {
652                    warn!(
653                        "Failed to redecrypt an event despite receiving a room key or request to redecrypt {e:?}"
654                    );
655                    None
656                }
657            }
658        } else {
659            let client = self.client().ok()?;
660            let machine = client.olm_machine().await;
661            let machine = machine.as_ref()?;
662
663            match machine.decrypt_room_event(event, room_id, client.decryption_settings()).await {
664                Ok(decrypted) => Some((decrypted, None)),
665                Err(e) => {
666                    warn!(
667                        "Failed to redecrypt an event despite receiving a room key or a request to redecrypt {e:?}"
668                    );
669                    None
670                }
671            }
672        }
673    }
674
675    /// Attempt to redecrypt events after a room key with the given session ID
676    /// has been received.
677    #[instrument(skip_all, fields(room_id, session_id))]
678    async fn retry_decryption(
679        &self,
680        room_id: &RoomId,
681        session_id: SessionId<'_>,
682    ) -> Result<(), EventCacheError> {
683        // Get all the relevant UTDs.
684        let events = self.all_encrypted_events(room_id, session_id).await?;
685        self.retry_decryption_for_events(room_id, events).await
686    }
687
688    /// Attempt to redecrypt events that were persisted in the event cache.
689    #[instrument(skip_all, fields(updates.linked_chunk_id))]
690    async fn retry_decryption_for_event_cache_updates(
691        &self,
692        updates: RoomEventCacheLinkedChunkUpdate,
693    ) -> Result<(), EventCacheError> {
694        let room_id = updates.linked_chunk_id.room_id();
695        let events: Vec<_> = updates
696            .updates
697            .into_iter()
698            .flat_map(|updates| updates.into_items())
699            .filter_map(filter_timeline_event_to_utd)
700            .collect();
701
702        self.retry_decryption_for_events(room_id, events).await
703    }
704
705    async fn retry_decryption_for_in_memory_events(&self) {
706        let utds = self.all_in_memory_encrypted_events().await;
707
708        for (room_id, utds) in utds.into_iter() {
709            if let Err(e) = self.retry_decryption_for_events(&room_id, utds).await {
710                warn!(%room_id, "Failed to redecrypt in-memory events {e:?}");
711            }
712        }
713    }
714
715    /// Attempt to redecrypt a chunk of UTDs.
716    #[instrument(skip_all, fields(room_id, session_id))]
717    async fn retry_decryption_for_events(
718        &self,
719        room_id: &RoomId,
720        events: Vec<EventIdAndUtd>,
721    ) -> Result<(), EventCacheError> {
722        trace!("Retrying to decrypt");
723
724        if events.is_empty() {
725            trace!("No relevant events found.");
726            return Ok(());
727        }
728
729        let room = self.client().ok().and_then(|client| client.get_room(room_id));
730        let push_context =
731            if let Some(room) = &room { room.push_context().await.ok().flatten() } else { None };
732
733        // Let's attempt to decrypt them them.
734        let mut decrypted_events = Vec::with_capacity(events.len());
735
736        for (event_id, event) in events {
737            // If we managed to decrypt the event, and we should have to since
738            // we received the room key for this specific event, then replace
739            // the event.
740            if let Some((decrypted_event, actions)) = self
741                .decrypt_event(
742                    room_id,
743                    room.as_ref(),
744                    push_context.as_ref(),
745                    event.cast_ref_unchecked(),
746                )
747                .await
748            {
749                decrypted_events.push(ResolvedUtd { event_id, decrypted_event, actions });
750            }
751        }
752
753        if !decrypted_events.is_empty() && tracing::level_enabled!(tracing::Level::TRACE) {
754            let event_ids: BTreeSet<_> =
755                decrypted_events.iter().map(|resolved_utd| &resolved_utd.event_id).collect();
756
757            trace!(?event_ids, "Successfully redecrypted events");
758        }
759
760        // Replace the events and notify listeners that UTDs have been replaced
761        // with decrypted events.
762        self.on_resolved_utds(room_id, decrypted_events).await?;
763
764        Ok(())
765    }
766
767    /// Attempt to update the encryption info for the given list of events.
768    async fn update_encryption_info_for_events(
769        &self,
770        room: &Room,
771        events: Vec<EventIdAndEvent>,
772    ) -> Result<(), EventCacheError> {
773        // Let's attempt to update their encryption info.
774        let mut updated_events = Vec::with_capacity(events.len());
775
776        for (event_id, mut event) in events {
777            if let Some(session_id) = event.encryption_info.session_id() {
778                let new_encryption_info =
779                    room.get_encryption_info(session_id, &event.encryption_info.sender).await;
780
781                // Only create a replacement if the encryption info actually
782                // changed.
783                if let Some(new_encryption_info) = new_encryption_info
784                    && event.encryption_info != new_encryption_info
785                {
786                    event.encryption_info = new_encryption_info;
787                    updated_events.push(ResolvedUtd {
788                        event_id,
789                        decrypted_event: event,
790                        actions: None,
791                    });
792                }
793            }
794        }
795
796        if !updated_events.is_empty() && tracing::level_enabled!(tracing::Level::TRACE) {
797            let event_ids: BTreeSet<_> =
798                updated_events.iter().map(|resolved_utd| &resolved_utd.event_id).collect();
799
800            trace!(?event_ids, "Replacing the encryption info of some events");
801        }
802
803        self.on_resolved_utds(room.room_id(), updated_events).await
804    }
805
806    #[instrument(skip_all, fields(room_id, session_id))]
807    async fn update_encryption_info(
808        &self,
809        room_id: &RoomId,
810        session_id: SessionId<'_>,
811    ) -> Result<(), EventCacheError> {
812        trace!("Updating encryption info");
813
814        let Ok(client) = self.client() else {
815            return Ok(());
816        };
817
818        let Some(room) = client.get_room(room_id) else {
819            return Ok(());
820        };
821
822        // Get all the relevant events.
823        let events = self.all_decrypted_events(room_id, session_id).await?;
824
825        if events.is_empty() {
826            trace!("No relevant events found.");
827            return Ok(());
828        }
829
830        // Let's attempt to update their encryption info.
831        self.update_encryption_info_for_events(&room, events).await
832    }
833
834    async fn retry_update_encryption_info_for_in_memory_events(&self) {
835        let decrypted_events = self.all_in_memory_decrypted_events().await;
836
837        for (room_id, events) in decrypted_events.into_iter() {
838            let Some(room) = self.client().ok().and_then(|c| c.get_room(&room_id)) else {
839                continue;
840            };
841
842            if let Err(e) = self.update_encryption_info_for_events(&room, events).await {
843                warn!(
844                    %room_id,
845                    "Failed to replace the encryption info for in-memory events {e:?}"
846                );
847            }
848        }
849    }
850
851    /// Retry to decrypt and update the encryption info of all the events
852    /// contained in the memory part of the event cache.
853    ///
854    /// This list of events will map one-to-one to the events components
855    /// subscribed to the event cache are have received and are keeping cached.
856    ///
857    /// If components subscribed to the event cache are doing additional
858    /// caching, they'll need to listen to [`RedecryptorReport`]s and explicitly
859    /// request redecryption attempts using [`EventCache::request_decryption`].
860    async fn retry_in_memory_events(&self) {
861        self.retry_decryption_for_in_memory_events().await;
862        self.retry_update_encryption_info_for_in_memory_events().await;
863    }
864}
865
866impl EventCache {
867    /// Explicitly request the redecryption of a set of events.
868    ///
869    /// The redecryption logic in the event cache might sometimes miss that a
870    /// room key has become available and that a certain set of events has
871    /// become decryptable.
872    ///
873    /// This might happen because some room keys might arrive in a separate
874    /// process handling push notifications or if a room key arrives but the
875    /// process shuts down before we could have decrypted the events.
876    ///
877    /// For this reason it is useful to tell the event cache explicitly that
878    /// some events should be retried to be redecrypted.
879    ///
880    /// This method allows you to do so. The events that get decrypted, if any,
881    /// will be advertised over the usual event cache subscription mechanism
882    /// which can be accessed using the [`RoomEventCache::subscribe()`] method.
883    ///
884    /// # Examples
885    ///
886    /// ```no_run
887    /// # use matrix_sdk::{Client, event_cache::DecryptionRetryRequest};
888    /// # use url::Url;
889    /// # use ruma::owned_room_id;
890    /// # use std::collections::BTreeSet;
891    /// # async {
892    /// # let homeserver = Url::parse("http://localhost:8080")?;
893    /// # let client = Client::new(homeserver).await?;
894    /// let event_cache = client.event_cache().unwrap();
895    /// let room_id = owned_room_id!("!my_room:localhost");
896    ///
897    /// let request = DecryptionRetryRequest {
898    ///     room_id,
899    ///     utd_session_ids: BTreeSet::from(["session_id".into()]),
900    ///     refresh_info_session_ids: BTreeSet::new(),
901    /// };
902    ///
903    /// event_cache.request_decryption(request);
904    /// # anyhow::Ok(()) };
905    /// ```
906    pub fn request_decryption(&self, request: DecryptionRetryRequest) {
907        let _ =
908            self.inner.redecryption_channels.decryption_request_sender.send(request).inspect_err(
909                |_| warn!("Requesting a decryption while the redecryption task has been shut down"),
910            );
911    }
912
913    /// Subscribe to reports that the redecryptor generates.
914    ///
915    /// The redecryption logic in the event cache might sometimes miss that a
916    /// room key has become available and that a certain set of events has
917    /// become decryptable.
918    ///
919    /// This might happen because some room keys might arrive in a separate
920    /// process handling push notifications or if room keys arrive faster than
921    /// we can handle them.
922    ///
923    /// This stream can be used to get notified about such situations as well as
924    /// a general channel where the event cache reports which events got
925    /// successfully redecrypted.
926    ///
927    /// # Examples
928    ///
929    /// ```no_run
930    /// # use matrix_sdk::{Client, event_cache::RedecryptorReport};
931    /// # use url::Url;
932    /// # use tokio_stream::StreamExt;
933    /// # async {
934    /// # let homeserver = Url::parse("http://localhost:8080")?;
935    /// # let client = Client::new(homeserver).await?;
936    /// let event_cache = client.event_cache().unwrap();
937    ///
938    /// let mut stream = event_cache.subscribe_to_decryption_reports();
939    ///
940    /// while let Some(Ok(report)) = stream.next().await {
941    ///     match report {
942    ///         RedecryptorReport::Lagging => {
943    ///             // The event cache might have missed to redecrypt some events. We should tell
944    ///             // it which events we care about, i.e. which events we're displaying to the
945    ///             // user, and let it redecrypt things with an explicit request.
946    ///         }
947    ///         RedecryptorReport::BackupAvailable => {
948    ///             // A backup has become available. We can, just like in the Lagging case, tell
949    ///             // the event cache to attempt to redecrypt some events.
950    ///             //
951    ///             // This is only necessary with the BackupDownloadStrategy::OnDecryptionFailure
952    ///             // as the decryption attempt in this case will trigger the download of the
953    ///             // room key from the backup.
954    ///         }
955    ///         RedecryptorReport::ResolvedUtds { .. } => {
956    ///             // This may be interesting for statistical reasons or in case we'd like to
957    ///             // fetch and inspect these events in some manner.
958    ///         }
959    ///     }
960    /// }
961    /// # anyhow::Ok(()) };
962    /// ```
963    pub fn subscribe_to_decryption_reports(
964        &self,
965    ) -> impl Stream<Item = Result<RedecryptorReport, BroadcastStreamRecvError>> + use<> {
966        BroadcastStream::new(self.inner.redecryption_channels.utd_reporter.subscribe())
967    }
968}
969
970/// Struct holding the state of the room key collation task. Holds keys
971/// received from the [`OlmMachine`] in arrival order, *without* deduplication.
972/// These are passed to the main task for redecryption whenever it is available
973/// to do work.
974#[derive(Default)]
975struct RoomKeyCollator {
976    /// A list of sessions we received room keys for in arrival order.
977    room_keys: VecDeque<RoomKeyInfo>,
978    /// A list of sessions for which we received withheld info in arrival order.
979    withheld: VecDeque<RoomKeyWithheldInfo>,
980    /// A flag denoting if the room key stream lagged.
981    pub lagged: bool,
982}
983
984impl RoomKeyCollator {
985    /// The default maximum size of the lists of stored room keys and withheld
986    /// keys. If we are asked to add more than this number of either, we
987    /// throw away the oldest to make room.
988    #[cfg(not(test))]
989    const CAPACITY: usize = 10_000;
990    /// Use a reduced capacity for tests to reduce running times.
991    #[cfg(test)]
992    const CAPACITY: usize = 100;
993
994    /// An iterator over all collated room keys in arrival order.
995    pub fn room_keys_iter(&self) -> impl Iterator<Item = &RoomKeyInfo> {
996        self.room_keys.iter()
997    }
998
999    /// Append `key` to the collator state so the main task can process it
1000    /// later without giving the OlmMachine's room key withheld info stream to
1001    /// exceed its internal capacity.
1002    pub fn add_key(&mut self, key: RoomKeyInfo) {
1003        // If we are about to exceed the capacity, pop the front of the queue.
1004        if self.room_keys.len() == Self::CAPACITY {
1005            self.room_keys.pop_front();
1006            self.lagged = true;
1007        }
1008        self.room_keys.push_back(key);
1009    }
1010
1011    /// An iterator over all collated withheld info in arrival order.
1012    pub fn withheld_iter(&self) -> impl Iterator<Item = &RoomKeyWithheldInfo> {
1013        self.withheld.iter()
1014    }
1015
1016    /// Append `info` to the collator state so the main task can process it
1017    /// later without giving the OlmMachine's room key withheld info stream to
1018    /// exceed its internal capacity.
1019    pub fn add_withheld(&mut self, info: RoomKeyWithheldInfo) {
1020        // If we are about to exceed the capacity, pop the front of the queue.
1021        if self.withheld.len() == Self::CAPACITY {
1022            self.withheld.pop_front();
1023            // TODO: is it necessary to trigger re-decryption if we can't
1024            // process withheld info?
1025            self.lagged = true;
1026        }
1027        self.withheld.push_back(info);
1028    }
1029}
1030
1031async fn send_report_and_retry_memory_events(
1032    cache: &Weak<EventCacheInner>,
1033    report: RedecryptorReport,
1034) -> Result<(), ()> {
1035    let Some(cache) = cache.upgrade() else {
1036        return Err(());
1037    };
1038
1039    cache.retry_in_memory_events().await;
1040    let _ = cache.redecryption_channels.utd_reporter.send(report);
1041
1042    Ok(())
1043}
1044
1045/// Struct holding on to the redecryption task.
1046///
1047/// This struct implements the bulk of the redecryption task. It listens to the
1048/// various streams that should trigger redecryption attempts.
1049///
1050/// For more info see the [module level docs](self).
1051pub(crate) struct Redecryptor {
1052    main_task: BackgroundTaskHandle,
1053    collator_task: BackgroundTaskHandle,
1054}
1055
1056impl Redecryptor {
1057    /// Stop the redecryption tasks for good.
1058    pub(super) fn abort(&self) {
1059        self.main_task.abort();
1060        self.collator_task.abort();
1061    }
1062
1063    /// Create a new [`Redecryptor`].
1064    ///
1065    /// This creates a task that listens to various streams and attempts to
1066    /// redecrypt UTDs that can be found inside the [`EventCache`].
1067    pub(super) fn new(
1068        client: &Client,
1069        cache: Weak<EventCacheInner>,
1070        receiver: UnboundedReceiver<DecryptionRetryRequest>,
1071        linked_chunk_update_sender: &LinkedChunkUpdateSender,
1072    ) -> Self {
1073        let linked_chunk_stream = BroadcastStream::new(linked_chunk_update_sender.subscribe());
1074        let backup_state_stream = client.encryption().backups().state_stream();
1075
1076        // Process the room key stream in a separate task so we collect them
1077        // even if the main task is slow. There are two tasks involved:
1078        //
1079        // - The collator task, which pushes room keys and withheld info
1080        //   received from the OlmMachine into a queue, and notifies the main
1081        //   task when this occurs; and
1082        // - The main redecryption task, which pulls from both queues when it is
1083        //   able to do work.
1084        //
1085        // The collator state is shared between the collator and redecryptor
1086        // tasks, so needs to be behind a shared Mutex.
1087        let collator = Arc::new(Mutex::new(RoomKeyCollator::default()));
1088        let collator_notify = Arc::new(Notify::new());
1089        let collator_task = client
1090            .task_monitor()
1091            .spawn_infinite_task(
1092                "event_cache::redecryptor::collator",
1093                Self::room_key_collator_task(
1094                    cache.clone(),
1095                    collator.clone(),
1096                    collator_notify.clone(),
1097                ),
1098            )
1099            .abort_on_drop();
1100
1101        let main_task = client
1102            .task_monitor()
1103            .spawn_infinite_task("event_cache::redecryptor", async {
1104                let request_redecryption_stream = UnboundedReceiverStream::new(receiver);
1105
1106                Self::main_redecryptor_task(
1107                    cache,
1108                    request_redecryption_stream,
1109                    linked_chunk_stream,
1110                    backup_state_stream,
1111                    collator,
1112                    collator_notify,
1113                )
1114                .await;
1115            })
1116            .abort_on_drop();
1117
1118        Self { main_task, collator_task }
1119    }
1120
1121    /// (Re)-subscribe to the room key stream from the [`OlmMachine`].
1122    ///
1123    /// This needs to happen any time this stream returns a `None` meaning that
1124    /// the sending part of the stream has been dropped.
1125    async fn subscribe_to_room_key_stream(
1126        cache: &Weak<EventCacheInner>,
1127    ) -> Option<(
1128        impl Stream<Item = Result<Vec<RoomKeyInfo>, BroadcastStreamRecvError>>,
1129        impl Stream<Item = Vec<RoomKeyWithheldInfo>>,
1130    )> {
1131        let event_cache = cache.upgrade()?;
1132        let client = event_cache.client().ok()?;
1133        let machine = client.olm_machine().await;
1134
1135        if machine.is_none() {
1136            warn!("No encryption session found. Did you subscribe to the event cache too early?");
1137        }
1138
1139        machine.as_ref().map(|m| {
1140            (m.store().room_keys_received_stream(), m.store().room_keys_withheld_received_stream())
1141        })
1142    }
1143
1144    async fn main_redecryptor_task(
1145        cache: Weak<EventCacheInner>,
1146        decryption_request_stream: UnboundedReceiverStream<DecryptionRetryRequest>,
1147        events_stream: BroadcastStream<RoomEventCacheLinkedChunkUpdate>,
1148        backup_state_stream: impl Stream<Item = Result<BackupState, BroadcastStreamRecvError>>,
1149        collator: Arc<Mutex<RoomKeyCollator>>,
1150        collator_notify: Arc<Notify>,
1151    ) {
1152        // We pin the decryption request stream here we don't want to miss
1153        // messages coming from the stream while recreating it unnecessarily.
1154        let mut decryption_request_stream = pin!(decryption_request_stream);
1155        let mut events_stream = pin!(events_stream);
1156        let mut backup_state_stream = pin!(backup_state_stream);
1157
1158        loop {
1159            tokio::select! {
1160                // An explicit request, presumably from the timeline, has been
1161                // received to decrypt events that were encrypted with a certain
1162                // room key.
1163                Some(request) = decryption_request_stream.next() => {
1164                        let Some(cache) = cache.upgrade() else {
1165                            // The event cache has gone away - we assume this
1166                            // is during shutdown, so we should tear
1167                            // ourselves down too.
1168                            break;
1169                        };
1170
1171                        trace!(?request, "Received a redecryption request");
1172
1173                        for session_id in request.utd_session_ids {
1174                            let _ = cache
1175                                .retry_decryption(&request.room_id, &session_id)
1176                                .await
1177                                .inspect_err(|e| warn!("Error redecrypting after an explicit request was received {e:?}"));
1178                        }
1179
1180                        for session_id in request.refresh_info_session_ids {
1181                            let _ = cache.update_encryption_info(&request.room_id, &session_id).await.inspect_err(|e|
1182                                warn!(
1183                                    room_id = %request.room_id,
1184                                    session_id = session_id,
1185                                    "Unable to update the encryption info {e:?}",
1186                            ));
1187                        }
1188                }
1189
1190                // The room key collation task has notified us we have room
1191                // keys to process.
1192                _ = collator_notify.notified() => {
1193                    // Lock the collator mutex and take ownership of its
1194                    // contents, replacing it with an empty one. This
1195                    // allows us to work through all the keys that have been
1196                    // collected while the collator task can resume with a
1197                    // fresh collector without us blocking it.
1198                    let collator = mem::take(&mut *collator.lock());
1199
1200                    if collator.lagged {
1201                        // We missed some room keys, we need to report this in
1202                        // case a listener has and idea which UTDs we should
1203                        // attempt to redecrypt.
1204                        //
1205                        // This would most likely be the timeline from the UI
1206                        // crate. The timeline might attempt to redecrypt all
1207                        // UTDs it is showing to the user.
1208                        warn!("The room key stream lagged, reporting the lag to our listeners");
1209                        if send_report_and_retry_memory_events(&cache, RedecryptorReport::Lagging).await.is_err() {
1210                            // Sending the report failed - something is bad
1211                            // so bail out entirely.
1212                            break;
1213                        }
1214                    }
1215
1216                    // Alright, some room keys were received and persisted in
1217                    // our store, let's attempt to redecrypt events that were
1218                    // encrypted using these room keys.
1219                    let Some(cache) = cache.upgrade() else {
1220                        // Event cache is gone -  presume we are in shutdown.
1221                        break;
1222                    };
1223
1224                    if !collator.room_keys.is_empty() {
1225                        trace!(?collator.room_keys, "Received new room keys");
1226
1227                        for key in collator.room_keys_iter() {
1228                            let _ = cache
1229                                .retry_decryption(&key.room_id, &key.session_id)
1230                                .await
1231                                .inspect_err(|e| warn!("Error redecrypting {e:?}"));
1232                        }
1233
1234                        for key in collator.room_keys_iter() {
1235                            let _ = cache.update_encryption_info(&key.room_id, &key.session_id).await.inspect_err(|e|
1236                                warn!(
1237                                    room_id = %key.room_id,
1238                                    session_id = key.session_id,
1239                                    "Unable to update the encryption info {e:?}",
1240                                ));
1241                            }
1242                    }
1243
1244                    if !collator.withheld.is_empty() {
1245                        trace!(?collator.withheld, "Received new withheld infos");
1246
1247                        for RoomKeyWithheldInfo { room_id, session_id, .. } in collator.withheld_iter() {
1248                            let _ = cache.update_encryption_info(room_id, session_id).await.inspect_err(|e|
1249                                warn!(
1250                                    room_id = %room_id,
1251                                    session_id = session_id,
1252                                    "Unable to update the encryption info {e:?}",
1253                                ));
1254                        }
1255                    }
1256                },
1257                // Events that the event cache handled. If the event cache
1258                // received any UTDs, let's attempt to redecrypt them in case
1259                // the room key was received before the event cache was able to
1260                // return them using `get_utds()`.
1261                Some(event_updates) = events_stream.next() => {
1262                    match event_updates {
1263                        Ok(updates) => {
1264                            let Some(cache) = cache.upgrade() else {
1265                                break;
1266                            };
1267
1268                            let linked_chunk_id = updates.linked_chunk_id.to_owned();
1269
1270                            let _ = cache.retry_decryption_for_event_cache_updates(updates).await.inspect_err(|e|
1271                                warn!(
1272                                    %linked_chunk_id,
1273                                    "Unable to handle UTDs from event cache updates {e:?}",
1274                                )
1275                            );
1276                        }
1277                        Err(_) => {
1278                            if send_report_and_retry_memory_events(&cache, RedecryptorReport::Lagging).await.is_err() {
1279                                break;
1280                            }
1281                        }
1282                    }
1283                }
1284                Some(backup_state_update) = backup_state_stream.next() => {
1285                    match backup_state_update {
1286                        Ok(state) => {
1287                            match state {
1288                                BackupState::Unknown |
1289                                BackupState::Creating |
1290                                BackupState::Enabling |
1291                                BackupState::Resuming |
1292                                BackupState::Downloading |
1293                                BackupState::Disabling => {
1294                                    // Those states aren't particularly
1295                                    // interesting to components listening to
1296                                    // R2D2 reports.
1297                                }
1298                                BackupState::Enabled => {
1299                                    // Alright, the backup got enabled, we might
1300                                    // or might not have downloaded the room
1301                                    // keys from the backup. In case they get
1302                                    // downloaded on-demand, let's try to
1303                                    // decrypt all the events we have cached
1304                                    // in-memory.
1305                                    if send_report_and_retry_memory_events(&cache, RedecryptorReport::BackupAvailable).await.is_err() {
1306                                        break;
1307                                    }
1308                                }
1309                            }
1310                        }
1311                        Err(_) => {
1312                            if send_report_and_retry_memory_events(&cache, RedecryptorReport::Lagging).await.is_err() {
1313                                break;
1314                            }
1315                        }
1316                    }
1317                }
1318                else => break,
1319            }
1320        }
1321
1322        info!("Shutting down the event cache redecryptor");
1323    }
1324
1325    /// Listens for new room keys and withheld info broadcast by the
1326    /// [`OlmMachine`] and collates them into a convenient struct the main
1327    /// task can process when it is available to do work.
1328    async fn room_key_collator_task(
1329        cache: Weak<EventCacheInner>,
1330        collator: Arc<Mutex<RoomKeyCollator>>,
1331        notify: Arc<Notify>,
1332    ) {
1333        // The OlmMachine occasionally drops and re-sets up its streams, after
1334        // which our existing streams will return `None`. We loop and
1335        // re-subscribe when this happen.
1336        'resubscribe: loop {
1337            let Some((room_key_stream, withheld_stream)) =
1338                Self::subscribe_to_room_key_stream(&cache).await
1339            else {
1340                // We failed to re-subscribe, meaning the OlmMachine is gone
1341                // entirely - presume shutdown, so bail out.
1342                break;
1343            };
1344
1345            let mut room_key_stream = pin!(room_key_stream);
1346            let mut withheld_stream = pin!(withheld_stream);
1347
1348            loop {
1349                tokio::select! {
1350                    room_keys = room_key_stream.next() => {
1351                        match room_keys {
1352                            Some(Ok(room_keys)) => {
1353                                trace!(?room_keys, "Received new room keys");
1354
1355                                let mut collator = collator.lock();
1356
1357                                for key in room_keys {
1358                                    collator.add_key(key);
1359                                }
1360                            },
1361                            Some(Err(_)) => {
1362                                // The room key stream lagged, but calling `send_report_and_retry_memory_events` here
1363                                // would take too long and may lag the stream further. Instead, let's notify the main
1364                                // task that this happened.
1365                                warn!("The room key stream lagged, notifying the main task");
1366                                collator.lock().lagged = true;
1367                            }
1368                            None => {
1369                                // The sender was dropped - resubscribe.
1370                                continue 'resubscribe
1371                            }
1372                        }
1373                        // Regardless of whether the stream lagged or not, we should notify the main task it has work to do.
1374                        notify.notify_one();
1375                    },
1376                    withheld = withheld_stream.next() => match withheld {
1377                        Some(withheld) => {
1378                            trace!(?withheld, "Received new withheld info");
1379
1380                            let mut collator = collator.lock();
1381
1382                            for info in withheld {
1383                                collator.add_withheld(info);
1384                            }
1385
1386                            // Notify the main task it has work to do.
1387                            notify.notify_one();
1388                        },
1389                        None => {
1390                            // Report that the stream got recreated so
1391                            // listeners know about it, at the same time retry
1392                            // to decrypt anything we have cached in memory.
1393                            collator.lock().lagged = true;
1394                            notify.notify_one();
1395                            continue 'resubscribe
1396                        }
1397                    }
1398                }
1399            }
1400        }
1401    }
1402}
1403
1404/// Helper method used by `RoomEventCacheState` and `ThreadEventCacheState` to
1405/// attempt to decrypt a bundled thread event we haven't tried to decrypt yet.
1406pub(super) async fn try_decrypt_in_place(event: &mut TimelineEvent, room: Option<&Room>) {
1407    if let TimelineEventKind::UnableToDecrypt { utd_info, .. } = &event.kind
1408        && let Some(room) = room
1409        && utd_info.reason == UnableToDecryptReason::Unknown
1410    {
1411        match room
1412            // Cast safety: a `TimelineEventKind::UnableToDecrypt` always holds the
1413            // `m.room.encrypted` event, and the `Unknown` reason above narrows this
1414            // further to the branch that has positively checked the `type` field in
1415            // `TimelineEvent::from_bundled_latest_event`.
1416            .decrypt_event(event.raw().cast_ref_unchecked::<OriginalSyncRoomEncryptedEvent>(), None)
1417            .await
1418        {
1419            Ok(decrypted) => *event = decrypted,
1420            Err(e) => warn!(
1421                "Failed to decrypt a bundled thread event we haven't tried to decrypt yet {e:?}"
1422            ),
1423        }
1424    }
1425}
1426
1427#[cfg(not(target_family = "wasm"))]
1428#[cfg(test)]
1429mod tests {
1430    use std::{assert_matches, collections::BTreeSet, time::Duration};
1431
1432    use eyeball_im::VectorDiff;
1433    use futures_util::{FutureExt, StreamExt, future::join_all};
1434    use matrix_sdk_base::{
1435        crypto::{
1436            store::{ROOM_KEYS_RECEIVED_CAPACITY, types::RoomKeyInfo},
1437            types::{EventEncryptionAlgorithm, events::room::encrypted::EncryptedToDeviceEvent},
1438        },
1439        deserialized_responses::{TimelineEventKind, UnableToDecryptReason, VerificationState},
1440        event_cache::store::ControlledMemoryStore,
1441        locks::Mutex,
1442        sleep::sleep,
1443        store::StoreConfig,
1444    };
1445    use matrix_sdk_common::{
1446        cross_process_lock::CrossProcessLockConfig, executor::spawn, timeout::timeout,
1447    };
1448    use matrix_sdk_test::{
1449        JoinedRoomBuilder, SyncResponseBuilder, async_test, event_factory::EventFactory,
1450    };
1451    use ruma::{
1452        EventId, OwnedEventId, RoomId, RoomVersionId, UserId, device_id, event_id,
1453        events::{
1454            AnySyncTimelineEvent, MessageLikeEventContent,
1455            relation::Thread,
1456            room::message::{
1457                AddMentions, ReplyMetadata, ReplyWithinThread, RoomMessageEventContent,
1458            },
1459        },
1460        owned_room_id, room_id,
1461        serde::Raw,
1462        user_id,
1463    };
1464    use serde_json::json;
1465    use strass::assert_let;
1466    use tracing::{Instrument, info};
1467    use vodozemac::Curve25519PublicKey;
1468    use wiremock::{Request, Respond, ResponseTemplate};
1469
1470    use crate::{
1471        Client, assert_let_timeout,
1472        encryption::EncryptionSettings,
1473        event_cache::{
1474            DecryptionRetryRequest, RedecryptorReport, RoomEventCacheGenericUpdate,
1475            RoomEventCacheUpdate, TimelineVectorDiffs, caches::subscriber::Subscriber,
1476            redecryptor::RoomKeyCollator,
1477        },
1478        test_utils::mocks::MatrixMockServer,
1479    };
1480
1481    async fn set_up_clients(
1482        room_id: &RoomId,
1483        alice_enables_cross_signing: bool,
1484        use_delayed_store: bool,
1485    ) -> (Client, Client, MatrixMockServer, Option<ControlledMemoryStore>) {
1486        let alice_span = tracing::info_span!("alice");
1487        let bob_span = tracing::info_span!("bob");
1488
1489        let alice_user_id = user_id!("@alice:localhost");
1490        let alice_device_id = device_id!("ALICEDEVICE");
1491        let bob_user_id = user_id!("@bob:localhost");
1492        let bob_device_id = device_id!("BOBDEVICE");
1493
1494        let matrix_mock_server = MatrixMockServer::new().await;
1495        matrix_mock_server.mock_crypto_endpoints_preset().await;
1496
1497        let encryption_settings = EncryptionSettings {
1498            auto_enable_cross_signing: alice_enables_cross_signing,
1499            ..Default::default()
1500        };
1501
1502        // Create some clients for Alice and Bob.
1503
1504        let alice = matrix_mock_server
1505            .client_builder_for_crypto_end_to_end(alice_user_id, alice_device_id)
1506            .on_builder(|builder| {
1507                builder
1508                    .with_enable_share_history_on_invite(true)
1509                    .with_encryption_settings(encryption_settings)
1510            })
1511            .build()
1512            .instrument(alice_span.clone())
1513            .await;
1514
1515        let encryption_settings =
1516            EncryptionSettings { auto_enable_cross_signing: true, ..Default::default() };
1517
1518        let (store_config, store) = if use_delayed_store {
1519            let store = ControlledMemoryStore::new();
1520            store.block_writes();
1521
1522            (
1523                StoreConfig::new(CrossProcessLockConfig::multi_process(
1524                    "delayed_store_event_cache_test",
1525                ))
1526                .event_cache_store(store.clone()),
1527                Some(store),
1528            )
1529        } else {
1530            (
1531                StoreConfig::new(CrossProcessLockConfig::multi_process(
1532                    "normal_store_event_cache_test",
1533                )),
1534                None,
1535            )
1536        };
1537
1538        let bob = matrix_mock_server
1539            .client_builder_for_crypto_end_to_end(bob_user_id, bob_device_id)
1540            .on_builder(|builder| {
1541                builder
1542                    .with_enable_share_history_on_invite(true)
1543                    .with_encryption_settings(encryption_settings)
1544                    .store_config(store_config)
1545            })
1546            .build()
1547            .instrument(bob_span.clone())
1548            .await;
1549
1550        // Ensure that Alice and Bob are aware of their devices and identities.
1551        matrix_mock_server.exchange_e2ee_identities(&alice, &bob).await;
1552
1553        let event_factory = EventFactory::new().room(room_id).sender(alice_user_id);
1554
1555        // Let us now create a room for them.
1556        let room_builder = JoinedRoomBuilder::new(room_id)
1557            .add_state_event(event_factory.create(alice_user_id, RoomVersionId::V1))
1558            .add_state_event(event_factory.room_encryption());
1559
1560        matrix_mock_server
1561            .mock_sync()
1562            .ok_and_run(&alice, |builder| {
1563                builder.add_joined_room(room_builder.clone());
1564            })
1565            .instrument(alice_span)
1566            .await;
1567
1568        matrix_mock_server
1569            .mock_sync()
1570            .ok_and_run(&bob, |builder| {
1571                builder.add_joined_room(room_builder);
1572            })
1573            .instrument(bob_span)
1574            .await;
1575
1576        // Mock the members endpoint, so that Alice can share room keys with
1577        // Bob.
1578        let member_factory = EventFactory::new().room(room_id);
1579        matrix_mock_server
1580            .mock_get_members()
1581            .ok(vec![
1582                member_factory.member(alice_user_id).into_raw(),
1583                member_factory.member(bob_user_id).into_raw(),
1584            ])
1585            .mount()
1586            .await;
1587
1588        (alice, bob, matrix_mock_server, store)
1589    }
1590
1591    #[async_test]
1592    async fn test_room_key_collator_preserves_arrival_order() {
1593        let mut collator = RoomKeyCollator::default();
1594        let key1 = RoomKeyInfo {
1595            algorithm: EventEncryptionAlgorithm::MegolmV1AesSha2,
1596            room_id: owned_room_id!("!example:matrix.org"),
1597            sender_key: Curve25519PublicKey::from(b"i love coyotes! i love coyotes!!".to_owned()),
1598            session_id: "session1".to_owned(),
1599        };
1600
1601        let key2 = RoomKeyInfo {
1602            algorithm: EventEncryptionAlgorithm::MegolmV1AesSha2,
1603            room_id: owned_room_id!("!example:matrix.org"),
1604            sender_key: Curve25519PublicKey::from(b"i really love coyotes! coyotes!!".to_owned()),
1605            session_id: "session2".to_owned(),
1606        };
1607
1608        // Add the same key twice.
1609        collator.add_key(key1.clone());
1610        collator.add_key(key2);
1611        collator.add_key(key1);
1612
1613        // We should see both copies.
1614        assert_eq!(collator.room_keys.len(), 3);
1615        assert_eq!(collator.room_keys[0].session_id, "session1");
1616        assert_eq!(collator.room_keys[1].session_id, "session2");
1617        assert_eq!(collator.room_keys[2].session_id, "session1");
1618    }
1619
1620    #[async_test]
1621    async fn test_room_key_collator_evicts_oldest() {
1622        let key1 = RoomKeyInfo {
1623            algorithm: EventEncryptionAlgorithm::MegolmV1AesSha2,
1624            room_id: owned_room_id!("!example:matrix.org"),
1625            sender_key: Curve25519PublicKey::from(b"i love coyotes! i love coyotes!!".to_owned()),
1626            session_id: "session1".to_owned(),
1627        };
1628        let key2 = RoomKeyInfo {
1629            algorithm: EventEncryptionAlgorithm::MegolmV1AesSha2,
1630            room_id: owned_room_id!("!example:matrix.org"),
1631            sender_key: Curve25519PublicKey::from(b"i really love coyotes! coyotes!!".to_owned()),
1632            session_id: "session2".to_owned(),
1633        };
1634
1635        // Create a collator and append `key1`.
1636        let mut collator = RoomKeyCollator::default();
1637        collator.add_key(key1);
1638
1639        // Fill the collator with keys past its capacity, which should make it
1640        // evict `key1`.
1641        for _ in 0..(RoomKeyCollator::CAPACITY + 1) {
1642            collator.add_key(key2.clone());
1643        }
1644
1645        // `key1` should have been evicted, and the first key should be `key2`.
1646        assert_eq!(collator.room_keys[0].session_id, "session2");
1647    }
1648
1649    #[async_test]
1650    async fn test_redecryptor() {
1651        let room_id = room_id!("!test:localhost");
1652
1653        let (alice, bob, matrix_mock_server, _) = set_up_clients(room_id, true, false).await;
1654
1655        let (event, room_key) = send_encrypted(
1656            &matrix_mock_server,
1657            &alice,
1658            room_id,
1659            event_id!("$some_id"),
1660            RoomMessageEventContent::text_plain("It's a secret to everybody"),
1661        )
1662        .await;
1663
1664        // Let's now see what Bob's event cache does.
1665
1666        let event_cache = bob.event_cache().unwrap();
1667        let (room_cache, _) = event_cache
1668            .room(room_id)
1669            .await
1670            .expect("We should be able to get to the event cache for a specific room");
1671
1672        let (_, mut subscriber) = room_cache.subscribe().await.unwrap();
1673        let mut generic_stream = event_cache.subscribe_to_room_generic_updates();
1674
1675        // We regenerate the Olm machine to check if the room key stream is
1676        // recreated to correctly.
1677        bob.inner
1678            .base_client
1679            .regenerate_olm(None)
1680            .await
1681            .expect("We should be able to regenerate the Olm machine");
1682
1683        // Let us forward the event to Bob.
1684        sync_room(
1685            &matrix_mock_server,
1686            &bob,
1687            JoinedRoomBuilder::new(room_id).add_timeline_event(event),
1688        )
1689        .await;
1690
1691        // Alright, Bob has received an update from the cache.
1692
1693        assert_let_timeout!(
1694            Ok(RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. })) =
1695                subscriber.recv()
1696        );
1697
1698        // There should be a single new event, and it should be a UTD as we did
1699        // not receive the room key yet.
1700        assert_eq!(diffs.len(), 1);
1701        assert_let!(VectorDiff::Append { values } = &diffs[0]);
1702        assert_eq!(values.len(), 1);
1703        assert_matches!(&values[0].kind, TimelineEventKind::UnableToDecrypt { .. });
1704
1705        assert_let_timeout!(
1706            Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) = generic_stream.recv()
1707        );
1708        assert_eq!(expected_room_id, room_id);
1709        assert!(generic_stream.is_empty());
1710
1711        // Now we send the room key to Bob.
1712        sync_room_keys(&matrix_mock_server, &bob, &[room_key]).await;
1713
1714        // Bob should receive a new update from the cache.
1715        assert_let_timeout!(
1716            Duration::from_secs(1),
1717            Ok(RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. })) =
1718                subscriber.recv()
1719        );
1720
1721        // It should replace the UTD with a decrypted event.
1722        assert_eq!(diffs.len(), 1);
1723        assert_let!(VectorDiff::Set { index, value } = &diffs[0]);
1724        assert_eq!(*index, 0);
1725        assert_matches!(&value.kind, TimelineEventKind::Decrypted { .. });
1726
1727        assert_let_timeout!(
1728            Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) = generic_stream.recv()
1729        );
1730        assert_eq!(expected_room_id, room_id);
1731        assert!(generic_stream.is_empty());
1732    }
1733
1734    #[cfg(feature = "experimental-search")]
1735    #[async_test]
1736    async fn test_redecrypted_event_is_indexed() {
1737        let room_id = room_id!("!test:localhost");
1738        let event_id = event_id!("$some_id");
1739
1740        let (alice, bob, matrix_mock_server, _) = set_up_clients(room_id, true, false).await;
1741
1742        let (event, room_key) = send_encrypted(
1743            &matrix_mock_server,
1744            &alice,
1745            room_id,
1746            event_id,
1747            RoomMessageEventContent::text_plain("It's a secret to everybody"),
1748        )
1749        .await;
1750
1751        let event_cache = bob.event_cache().unwrap();
1752        let (room_cache, _) = event_cache.room(room_id).await.unwrap();
1753        let (_, mut subscriber) = room_cache.subscribe().await.unwrap();
1754
1755        // Bob receives the event as a UTD, which can't be indexed.
1756        sync_room(
1757            &matrix_mock_server,
1758            &bob,
1759            JoinedRoomBuilder::new(room_id).add_timeline_event(event),
1760        )
1761        .await;
1762        assert_let_timeout!(Ok(RoomEventCacheUpdate::UpdateTimelineEvents(_)) = subscriber.recv());
1763
1764        let room = bob.get_room(room_id).unwrap();
1765        assert!(room.search("secret", 5, None).await.unwrap().events.is_empty());
1766
1767        // Once the room key arrives, the event is redecrypted…
1768        sync_room_keys(&matrix_mock_server, &bob, &[room_key]).await;
1769        assert_let_timeout!(
1770            Duration::from_secs(1),
1771            Ok(RoomEventCacheUpdate::UpdateTimelineEvents(_)) = subscriber.recv()
1772        );
1773
1774        // … and indexed.
1775        let mut results = Vec::new();
1776        for _ in 0..50 {
1777            results = room.search("secret", 5, None).await.unwrap().events;
1778            if !results.is_empty() {
1779                break;
1780            }
1781            sleep(Duration::from_millis(20)).await;
1782        }
1783        assert_eq!(results.len(), 1, "the redecrypted event should be indexed");
1784        assert_eq!(results[0].1, event_id);
1785    }
1786
1787    #[async_test]
1788    async fn test_redecryptor_updating_encryption_info() {
1789        let bob_span = tracing::info_span!("bob");
1790
1791        let room_id = room_id!("!test:localhost");
1792
1793        let (alice, bob, matrix_mock_server, _) = set_up_clients(room_id, false, false).await;
1794
1795        let (event, room_key) = send_encrypted(
1796            &matrix_mock_server,
1797            &alice,
1798            room_id,
1799            event_id!("$some_id"),
1800            RoomMessageEventContent::text_plain("It's a secret to everybody"),
1801        )
1802        .await;
1803
1804        // Let's now see what Bob's event cache does.
1805
1806        let event_cache = bob.event_cache().unwrap();
1807        let (room_cache, _) = event_cache
1808            .room(room_id)
1809            .instrument(bob_span.clone())
1810            .await
1811            .expect("We should be able to get to the event cache for a specific room");
1812
1813        let (_, mut subscriber) = room_cache.subscribe().await.unwrap();
1814        let mut generic_stream = event_cache.subscribe_to_room_generic_updates();
1815
1816        // Let us forward the event to Bob.
1817        sync_room(
1818            &matrix_mock_server,
1819            &bob,
1820            JoinedRoomBuilder::new(room_id).add_timeline_event(event),
1821        )
1822        .instrument(bob_span.clone())
1823        .await;
1824
1825        // Alright, Bob has received an update from the cache.
1826
1827        assert_let_timeout!(
1828            Ok(RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. })) =
1829                subscriber.recv()
1830        );
1831
1832        // There should be a single new event, and it should be a UTD as we did
1833        // not receive the room key yet.
1834        assert_eq!(diffs.len(), 1);
1835        assert_let!(VectorDiff::Append { values } = &diffs[0]);
1836        assert_eq!(values.len(), 1);
1837        assert_matches!(&values[0].kind, TimelineEventKind::UnableToDecrypt { .. });
1838
1839        assert_let_timeout!(
1840            Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) = generic_stream.recv()
1841        );
1842        assert_eq!(expected_room_id, room_id);
1843        assert!(generic_stream.is_empty());
1844
1845        // Now we send the room key to Bob.
1846        sync_room_keys(&matrix_mock_server, &bob, &[room_key]).instrument(bob_span.clone()).await;
1847
1848        // Bob should receive a new update from the cache.
1849        assert_let_timeout!(
1850            Duration::from_secs(1),
1851            Ok(RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. })) =
1852                subscriber.recv()
1853        );
1854
1855        // It should replace the UTD with a decrypted event.
1856        assert_eq!(diffs.len(), 1);
1857        assert_let!(VectorDiff::Set { index: 0, value } = &diffs[0]);
1858        assert_matches!(&value.kind, TimelineEventKind::Decrypted { .. });
1859
1860        let encryption_info = value.encryption_info().unwrap();
1861        assert_matches!(&encryption_info.verification_state, VerificationState::Unverified(_));
1862
1863        assert_let_timeout!(
1864            Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) = generic_stream.recv()
1865        );
1866        assert_eq!(expected_room_id, room_id);
1867        assert!(generic_stream.is_empty());
1868
1869        let session_id = encryption_info.session_id().unwrap().to_owned();
1870        let alice_user_id = alice.user_id().unwrap();
1871
1872        // Alice now creates the identity.
1873        alice
1874            .encryption()
1875            .bootstrap_cross_signing(None)
1876            .await
1877            .expect("Alice should be able to create the cross-signing keys");
1878
1879        bob.update_tracked_users_for_testing([alice_user_id]).instrument(bob_span.clone()).await;
1880        matrix_mock_server
1881            .mock_sync()
1882            .ok_and_run(&bob, |builder| {
1883                builder.add_change_device(alice_user_id);
1884            })
1885            .instrument(bob_span.clone())
1886            .await;
1887
1888        bob.event_cache().unwrap().request_decryption(DecryptionRetryRequest {
1889            room_id: room_id.into(),
1890            utd_session_ids: BTreeSet::new(),
1891            refresh_info_session_ids: BTreeSet::from([session_id]),
1892        });
1893
1894        // Bob should again receive a new update from the cache, this time
1895        // updating the encryption info.
1896        assert_let_timeout!(
1897            Duration::from_secs(1),
1898            Ok(RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. })) =
1899                subscriber.recv()
1900        );
1901
1902        assert_eq!(diffs.len(), 1);
1903        assert_let!(VectorDiff::Set { index: 0, value } = &diffs[0]);
1904        assert_matches!(&value.kind, TimelineEventKind::Decrypted { .. });
1905        let encryption_info = value.encryption_info().unwrap();
1906
1907        assert_matches!(
1908            &encryption_info.verification_state,
1909            VerificationState::Unverified(_),
1910            "The event should now know about the identity but still be unverified"
1911        );
1912
1913        assert_let_timeout!(
1914            Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) = generic_stream.recv()
1915        );
1916        assert_eq!(expected_room_id, room_id);
1917        assert!(generic_stream.is_empty());
1918    }
1919
1920    #[async_test]
1921    async fn test_event_is_redecrypted_even_if_key_arrives_while_event_processing() {
1922        let room_id = room_id!("!test:localhost");
1923
1924        let (alice, bob, matrix_mock_server, delayed_store) =
1925            set_up_clients(room_id, true, true).await;
1926
1927        let delayed_store = delayed_store.unwrap();
1928
1929        let (event, room_key) = send_encrypted(
1930            &matrix_mock_server,
1931            &alice,
1932            room_id,
1933            event_id!("$some_id"),
1934            RoomMessageEventContent::text_plain("It's a secret to everybody"),
1935        )
1936        .await;
1937
1938        let event_cache = bob.event_cache().unwrap();
1939
1940        // Let's now see what Bob's event cache does.
1941        let (room_cache, _) = event_cache
1942            .room(room_id)
1943            .await
1944            .expect("We should be able to get to the event cache for a specific room");
1945
1946        let (_, mut subscriber) = room_cache.subscribe().await.unwrap();
1947        let mut generic_stream = event_cache.subscribe_to_room_generic_updates();
1948
1949        // Custom type to mock the `/sync` endpoints.
1950        struct Responder<'a> {
1951            sync_response_builder: Mutex<(usize, SyncResponseBuilder)>,
1952            room_id: &'a RoomId,
1953            event: Raw<AnySyncTimelineEvent>,
1954            room_key: Raw<EncryptedToDeviceEvent>,
1955        }
1956
1957        impl<'a> Responder<'a> {
1958            fn new(
1959                room_id: &'a RoomId,
1960                event: Raw<AnySyncTimelineEvent>,
1961                room_key: Raw<EncryptedToDeviceEvent>,
1962            ) -> Self {
1963                Self {
1964                    sync_response_builder: Mutex::new((0, SyncResponseBuilder::new())),
1965                    room_id,
1966                    event,
1967                    room_key,
1968                }
1969            }
1970        }
1971
1972        impl<'a> Respond for Responder<'a> {
1973            fn respond(&self, _request: &Request) -> ResponseTemplate {
1974                let (nth_sync, sync_response_builder) = &mut *self.sync_response_builder.lock();
1975
1976                match nth_sync {
1977                    // First request for `sync_room`.
1978                    0 => {
1979                        *nth_sync = 1;
1980                        ResponseTemplate::new(200).set_body_json(
1981                            sync_response_builder
1982                                .add_joined_room(
1983                                    JoinedRoomBuilder::new(self.room_id)
1984                                        .add_timeline_event(self.event.clone()),
1985                                )
1986                                .build_json_sync_response(),
1987                        )
1988                    }
1989
1990                    // Second request for `sync_room_keys`.
1991                    1 => {
1992                        *nth_sync = 2;
1993                        ResponseTemplate::new(200).set_body_json(
1994                            sync_response_builder
1995                                .add_to_device_event(self.room_key.deserialize_as().unwrap())
1996                                .build_json_sync_response(),
1997                        )
1998                    }
1999
2000                    _ => panic!("`/sync` is called once too much"),
2001                }
2002            }
2003        }
2004
2005        let mock = matrix_mock_server
2006            .mock_sync()
2007            .respond_with(Responder::new(room_id, event, room_key))
2008            .mount_as_scoped()
2009            .await;
2010
2011        let sync_room = spawn({
2012            let bob = bob.clone();
2013
2014            // Let us forward the event to Bob, immediately. It will stop
2015            // before persisting everything in the store.
2016            async move {
2017                let _ = bob.sync_once(Default::default()).await.unwrap();
2018            }
2019        });
2020
2021        let sync_room_keys = spawn({
2022            let bob = bob.clone();
2023
2024            // Now we send the room key to Bob, let's say after a delay of
2025            // 1sec, so that the Event Cache had time to start handling the
2026            // event and being blocked when persisting it.
2027            async move {
2028                // Wait on `sync_room` to hang.
2029                sleep(Duration::from_secs(1)).await;
2030
2031                let _ = bob.sync_once(Default::default()).await.unwrap();
2032
2033                // Allow the redecryptor some time to retry any UTDs.
2034                sleep(Duration::from_millis(100)).await;
2035            }
2036        });
2037
2038        let delay = spawn({
2039            // Unblock `sync_room` after 2 secs, so that `sync_room_keys` has
2040            // finished before `sync_room` finishes.
2041            async move {
2042                sleep(Duration::from_secs(2)).await;
2043                info!("Stopping the delay");
2044                delayed_store.unblock_writes();
2045                delayed_store.wait_for_write_to_finish().await;
2046            }
2047        });
2048
2049        assert!(
2050            join_all([sync_room, sync_room_keys, delay]).await.into_iter().all(|res| res.is_ok()),
2051            "all tasks should succeed"
2052        );
2053
2054        drop(mock);
2055
2056        // The first decryption attempt has failed because the first sync (the
2057        // one with the event) did not contain the room key. The decryptor has
2058        // later received the room key.
2059
2060        // Alright, Bob has received an update from the cache.
2061        assert_let_timeout!(
2062            Ok(RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. })) =
2063                subscriber.recv()
2064        );
2065
2066        // There should be a single new event, and it should be a UTD as we did
2067        // not receive the room key yet.
2068        assert_eq!(diffs.len(), 1);
2069        assert_let!(VectorDiff::Append { values } = &diffs[0]);
2070        assert_eq!(values.len(), 1);
2071        assert_matches!(&values[0].kind, TimelineEventKind::UnableToDecrypt { .. });
2072
2073        // And the companion generic update.
2074        assert_let_timeout!(
2075            Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) = generic_stream.recv()
2076        );
2077        assert_eq!(expected_room_id, room_id);
2078
2079        // Bob should receive a new update from the cache.
2080        assert_let_timeout!(
2081            Duration::from_secs(1),
2082            Ok(RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. })) =
2083                subscriber.recv()
2084        );
2085
2086        // It should replace the UTD with a decrypted event.
2087        assert_eq!(diffs.len(), 1);
2088        assert_let!(VectorDiff::Set { index, value } = &diffs[0]);
2089        assert_eq!(*index, 0);
2090        assert_matches!(&value.kind, TimelineEventKind::Decrypted { .. });
2091
2092        // And the companion generic update.
2093        assert_let_timeout!(
2094            Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) = generic_stream.recv()
2095        );
2096        assert_eq!(expected_room_id, room_id);
2097        assert!(generic_stream.is_empty());
2098    }
2099
2100    #[async_test]
2101    async fn test_event_is_redecrypted_even_if_redecryptor_busy() {
2102        let room_id = room_id!("!test:localhost");
2103
2104        let (alice, bob, matrix_mock_server, delayed_store) =
2105            set_up_clients(room_id, true, true).await;
2106
2107        let delayed_store = delayed_store.unwrap();
2108
2109        // Send enough messages to exceed the capacity of the internal channel
2110        // used by OlmMachine's room key stream, each with a unique room key so
2111        // Bob's channel fills up. See `CryptoStoreWrapper::new`.
2112        const EVENT_COUNT: usize = ROOM_KEYS_RECEIVED_CAPACITY + 15;
2113        let (events, room_keys) =
2114            send_encrypted_with_unique_keys(&matrix_mock_server, &alice, room_id, EVENT_COUNT)
2115                .await;
2116
2117        let event_cache = bob.event_cache().unwrap();
2118
2119        // Fetch a reference to Bob's event cache so we can listen to cache
2120        // updates.
2121        let (room_cache, _) = event_cache
2122            .room(room_id)
2123            .await
2124            .expect("We should be able to get to the event cache for a specific room");
2125
2126        // Set up the necessary subscriptions.
2127        let (_, mut subscriber) = room_cache.subscribe().await.unwrap();
2128        let mut generic_stream = event_cache.subscribe_to_room_generic_updates();
2129        let mut reports = event_cache.subscribe_to_decryption_reports();
2130
2131        // Mock the first sync request made by `sync_room`
2132        let _sync_guard = matrix_mock_server
2133            .mock_sync()
2134            .ok(|builder| {
2135                builder.add_joined_room(JoinedRoomBuilder::new(room_id).add_timeline_bulk(events));
2136            })
2137            .mock_once()
2138            .mount_as_scoped()
2139            .await;
2140
2141        let sync_room = spawn({
2142            let bob = bob.clone();
2143
2144            // Let us forward the events to Bob, immediately. This will block
2145            // before persisting everything in the store (since we're using a
2146            // delayed store).
2147            async move {
2148                let _ = bob.sync_once(Default::default()).await.unwrap();
2149            }
2150        });
2151
2152        // The `sync_room` task should attempt to write into the store, which in
2153        // turn should notify us this is the case.
2154        timeout(delayed_store.wait_for_write_to_start(), Duration::from_secs(5))
2155            .await
2156            .expect("`sync_room` should start writing to the event cache store");
2157
2158        // Deliver each room key in its own sync, so each one is a separate
2159        // broadcast on the room key stream. With R2D2 blocked on the event
2160        // cache, this overflows the stream's capacity.
2161        for key in room_keys {
2162            let _mock = matrix_mock_server
2163                .mock_sync()
2164                .ok(|builder| {
2165                    // Report a full set of one-time keys, otherwise Bob
2166                    // generates new ones on every sync, and every crypto
2167                    // store commit slows down as his account grows.
2168                    builder
2169                        .set_one_time_keys_count(50)
2170                        .add_to_device_event(key.deserialize_as().unwrap());
2171                })
2172                .mock_once()
2173                .mount_as_scoped()
2174                .await;
2175
2176            bob.sync_once(Default::default()).await.unwrap();
2177        }
2178
2179        // Unblock the `sync_room` task.
2180        info!("Stopping the delay");
2181        delayed_store.unblock_writes();
2182        delayed_store.wait_for_write_to_finish().await;
2183
2184        sync_room.await.expect("sync_room should succeed");
2185
2186        drop(_sync_guard);
2187
2188        // The first decryption attempts should fail because the first sync
2189        // (the one with the events) did not contain any room keys. The
2190        // redecryptor receives the room keys later.
2191
2192        // All events should be appended as UTDs, as we did not receive the room
2193        // keys yet.
2194        assert_appended_as_utds(&mut subscriber, EVENT_COUNT).await;
2195
2196        // And the companion generic update.
2197        assert_let_timeout!(
2198            Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) = generic_stream.recv()
2199        );
2200        assert_eq!(expected_room_id, room_id);
2201
2202        // Collect updates from the event cache until every event was decrypted.
2203        assert_all_decrypted(&mut subscriber, EVENT_COUNT, Duration::from_secs(1)).await;
2204
2205        // R2D2 must never have missed a room key. Without the collator, the
2206        // room key stream lags and R2D2 falls back to a `Lagging` report.
2207        while let Some(Some(report)) = reports.next().now_or_never() {
2208            assert_matches!(
2209                report,
2210                Ok(RedecryptorReport::ResolvedUtds { .. }),
2211                "R2D2 should not have lagged"
2212            );
2213        }
2214    }
2215
2216    #[async_test]
2217    async fn test_lagging_is_reported_when_collator_capacity_is_exceeded() {
2218        let room_id = room_id!("!test:localhost");
2219
2220        let (alice, bob, matrix_mock_server, _) = set_up_clients(room_id, true, false).await;
2221
2222        // Provide the collator with one key more than it can hold, with a
2223        // unique room key per event.
2224        const EVENT_COUNT: usize = RoomKeyCollator::CAPACITY + 1;
2225        let (events, room_keys) =
2226            send_encrypted_with_unique_keys(&matrix_mock_server, &alice, room_id, EVENT_COUNT)
2227                .await;
2228
2229        let event_cache = bob.event_cache().unwrap();
2230
2231        let (room_cache, _) = event_cache
2232            .room(room_id)
2233            .await
2234            .expect("We should be able to get to the event cache for a specific room");
2235
2236        let (_, mut subscriber) = room_cache.subscribe().await.unwrap();
2237        let mut reports = event_cache.subscribe_to_decryption_reports();
2238
2239        // Sync the events to Bob before any room key arrives ...
2240        sync_room(
2241            &matrix_mock_server,
2242            &bob,
2243            JoinedRoomBuilder::new(room_id).add_timeline_bulk(events),
2244        )
2245        .await;
2246
2247        // ... which should all land in the event cache as UTDs.
2248        assert_appended_as_utds(&mut subscriber, EVENT_COUNT).await;
2249
2250        // Now deliver all the room keys in a single sync. The OlmMachine
2251        // persists them in one go and broadcasts them as a single batch, which
2252        // the collation task flattens and adds to the collator while holding
2253        // its lock.
2254        sync_room_keys(&matrix_mock_server, &bob, &room_keys).await;
2255
2256        // The main task therefore cannot drain the collator part way through,
2257        // and the collator must evict the oldest key and report the lag, which
2258        // should surface as a `RedecryptorReport::Lagging`.
2259        timeout(
2260            async {
2261                loop {
2262                    match reports.next().await {
2263                        Some(Ok(RedecryptorReport::Lagging)) => break,
2264                        Some(_) => (),
2265                        None => panic!("the report stream should not close"),
2266                    }
2267                }
2268            },
2269            Duration::from_secs(10),
2270        )
2271        .await
2272        .expect("evicting room keys from the collator should produce a `Lagging` report");
2273
2274        // Despite the eviction, every event should eventually decrypt. All the
2275        // keys are in the crypto store, and the lag report comes with a
2276        // retry of every in-memory UTD.
2277        assert_all_decrypted(&mut subscriber, EVENT_COUNT, Duration::from_secs(10)).await;
2278    }
2279
2280    /// Helper method to send an encrypted message to a room, and capture both
2281    /// the sent event and the to-device message sharing its room key.
2282    ///
2283    /// The message must share a new room key: it has to be the first message in
2284    /// the room, or the first one after the room key was discarded.
2285    async fn send_encrypted(
2286        matrix_mock_server: &MatrixMockServer,
2287        client: &Client,
2288        room_id: &RoomId,
2289        event_id: &EventId,
2290        content: impl MessageLikeEventContent,
2291    ) -> (Raw<AnySyncTimelineEvent>, Raw<EncryptedToDeviceEvent>) {
2292        let user_id = client.user_id().unwrap();
2293        let room = client.get_room(room_id).unwrap();
2294
2295        let (event_receiver, mock) =
2296            matrix_mock_server.mock_room_send().ok_with_capture(event_id, user_id);
2297        // Keep the guards bound until the end of the method, or the mocks are
2298        // dropped immediately.
2299        let _send_guard = mock.mock_once().mount_as_scoped().await;
2300        let (_to_device_guard, room_key) =
2301            matrix_mock_server.mock_capture_put_to_device(user_id).await;
2302
2303        room.send(content).await.unwrap();
2304
2305        let event: Raw<AnySyncTimelineEvent> = event_receiver.await.unwrap();
2306        let room_key = timeout(room_key, Duration::from_secs(1))
2307            .await
2308            .expect("the send should have shared a new room key - did you forget to rotate?");
2309
2310        (event, room_key)
2311    }
2312
2313    /// Helper method to send `count` encrypted messages to a room, discarding
2314    /// the room key before each send so every event is encrypted with a
2315    /// unique session.
2316    async fn send_encrypted_with_unique_keys(
2317        matrix_mock_server: &MatrixMockServer,
2318        client: &Client,
2319        room_id: &RoomId,
2320        count: usize,
2321    ) -> (Vec<Raw<AnySyncTimelineEvent>>, Vec<Raw<EncryptedToDeviceEvent>>) {
2322        let mut events = Vec::with_capacity(count);
2323        let mut room_keys = Vec::with_capacity(count);
2324
2325        for i in 0..count {
2326            client.get_room(room_id).unwrap().discard_room_key().await.unwrap();
2327            let (event, room_key) = send_encrypted(
2328                matrix_mock_server,
2329                client,
2330                room_id,
2331                &OwnedEventId::try_from(format!("${i}")).unwrap(),
2332                RoomMessageEventContent::text_plain("It's a secret to everybody"),
2333            )
2334            .await;
2335            events.push(event);
2336            room_keys.push(room_key);
2337        }
2338
2339        (events, room_keys)
2340    }
2341
2342    /// Assert that the next timeline update appends exactly `expected` events,
2343    /// all of them UTDs. The events may span several appends, one per linked
2344    /// chunk.
2345    async fn assert_appended_as_utds(
2346        subscriber: &mut Subscriber<RoomEventCacheUpdate>,
2347        expected: usize,
2348    ) {
2349        assert_let_timeout!(
2350            Ok(RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. })) =
2351                subscriber.recv()
2352        );
2353
2354        let mut appended = 0;
2355        for diff in diffs {
2356            assert_let!(VectorDiff::Append { values } = diff);
2357            for value in &values {
2358                assert_matches!(&value.kind, TimelineEventKind::UnableToDecrypt { .. });
2359            }
2360            appended += values.len();
2361        }
2362        assert_eq!(appended, expected);
2363    }
2364
2365    /// Collect timeline updates until `expected` distinct events have been
2366    /// decrypted. R2D2 may decrypt them one key at a time, or in a single
2367    /// batch, depending on which of its streams it handles first.
2368    async fn assert_all_decrypted(
2369        subscriber: &mut Subscriber<RoomEventCacheUpdate>,
2370        expected: usize,
2371        update_timeout: Duration,
2372    ) {
2373        let mut decrypted = BTreeSet::new();
2374        while decrypted.len() < expected {
2375            assert_let_timeout!(
2376                update_timeout,
2377                Ok(RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. })) =
2378                    subscriber.recv()
2379            );
2380            for diff in diffs {
2381                assert_let!(VectorDiff::Set { index, value } = diff);
2382                assert_matches!(value.kind, TimelineEventKind::Decrypted { .. });
2383                decrypted.insert(index);
2384            }
2385        }
2386    }
2387
2388    /// Bundle `child` as the latest thread event of `root`.
2389    fn with_bundled_thread(
2390        root: &Raw<AnySyncTimelineEvent>,
2391        child: &Raw<AnySyncTimelineEvent>,
2392    ) -> Raw<AnySyncTimelineEvent> {
2393        let mut root: serde_json::Value = root.deserialize_as().unwrap();
2394        root["unsigned"] = json!({
2395            "m.relations": {
2396                "m.thread": {
2397                    "latest_event": child,
2398                    "count": 1,
2399                    "current_user_participated": false,
2400                },
2401            },
2402        });
2403        Raw::new(&root).unwrap().cast_unchecked()
2404    }
2405
2406    /// Helper method to sync room keys to a client, in a single sync response.
2407    async fn sync_room_keys(
2408        matrix_mock_server: &MatrixMockServer,
2409        client: &Client,
2410        room_keys: &[Raw<EncryptedToDeviceEvent>],
2411    ) {
2412        matrix_mock_server
2413            .mock_sync()
2414            .ok_and_run(client, |builder| {
2415                for room_key in room_keys {
2416                    builder.add_to_device_event(room_key.deserialize_as().unwrap());
2417                }
2418            })
2419            .await;
2420        // Allow the redecryptor some time to retry any UTDs.
2421        sleep(Duration::from_millis(100)).await;
2422    }
2423
2424    /// Helper method to sync a joined room update to a client.
2425    async fn sync_room(
2426        matrix_mock_server: &MatrixMockServer,
2427        client: &Client,
2428        room: JoinedRoomBuilder,
2429    ) {
2430        matrix_mock_server
2431            .mock_sync()
2432            .ok_and_run(client, |builder| {
2433                builder.add_joined_room(room);
2434            })
2435            .await;
2436        // Allow the redecryptor some time to retry any UTDs.
2437        sleep(Duration::from_millis(200)).await;
2438    }
2439
2440    /// Get the cached timeline event kind for a given event ID in a room, if it
2441    /// exists. Returns `None` if the event is not in the cache.
2442    async fn get_cached_timeline_event_kind(
2443        client: &Client,
2444        room_id: &RoomId,
2445        event_id: &EventId,
2446    ) -> Option<TimelineEventKind> {
2447        client
2448            .get_room(room_id)
2449            .unwrap()
2450            .load_or_fetch_event(event_id, None)
2451            .await
2452            .map(|event| event.kind)
2453            // An error here means the event is not in the cache, so we return `None`.
2454            .ok()
2455    }
2456
2457    /// Helper method to create a thread reply event contents.
2458    fn make_thread_reply_event_content(
2459        root_id: &EventId,
2460        sender: &UserId,
2461    ) -> RoomMessageEventContent {
2462        RoomMessageEventContent::text_plain("In the thread").make_for_thread(
2463            ReplyMetadata::new(
2464                root_id,
2465                sender,
2466                Some(&Thread::plain(root_id.to_owned(), root_id.to_owned())),
2467            ),
2468            ReplyWithinThread::No,
2469            AddMentions::No,
2470        )
2471    }
2472
2473    /// Case 1 (normal): the key arrives first, then the root and the reply as
2474    /// separate events.
2475    #[async_test]
2476    async fn test_thread_reply_in_timeline_after_key() {
2477        let room_id = room_id!("!test:localhost");
2478        let root_id = event_id!("$root");
2479        let reply_id = event_id!("$reply");
2480
2481        // Alice and Bob are in an encrypted room ...
2482        let (alice, bob, server, _) = set_up_clients(room_id, true, false).await;
2483        let alice_id = alice.user_id().unwrap();
2484
2485        // ... in which Alice sends a message.
2486        let (root, root_key) = send_encrypted(
2487            &server,
2488            &alice,
2489            room_id,
2490            root_id,
2491            RoomMessageEventContent::text_plain("Root"),
2492        )
2493        .await;
2494
2495        // Alice discards the room key ...
2496        alice.get_room(room_id).unwrap().discard_room_key().await.unwrap();
2497
2498        // ... then sends a reply in a new thread using a newly generated room
2499        // key.
2500        let (reply, reply_key) = send_encrypted(
2501            &server,
2502            &alice,
2503            room_id,
2504            reply_id,
2505            make_thread_reply_event_content(root_id, alice_id),
2506        )
2507        .await;
2508
2509        // Bob receives both room keys first, then the root and reply events.
2510        sync_room_keys(&server, &bob, &[root_key, reply_key]).await;
2511        sync_room(&server, &bob, JoinedRoomBuilder::new(room_id).add_timeline_bulk([root, reply]))
2512            .await;
2513
2514        // Bob should now have both events in his cache, and they should be
2515        // decrypted.
2516        assert_matches!(
2517            get_cached_timeline_event_kind(&bob, room_id, root_id).await,
2518            Some(TimelineEventKind::Decrypted { .. })
2519        );
2520        assert_matches!(
2521            get_cached_timeline_event_kind(&bob, room_id, reply_id).await,
2522            Some(TimelineEventKind::Decrypted { .. })
2523        );
2524    }
2525
2526    /// Case 2: The key arrives first, then the root and bundled reply arrive in
2527    /// a single sync.
2528    #[async_test]
2529    async fn test_bundled_thread_reply_after_key_decryptable_root() {
2530        let room_id = room_id!("!test:localhost");
2531        let root_id = event_id!("$root");
2532        let reply_id = event_id!("$reply");
2533
2534        // Alice and Bob are in an encrypted room ...
2535        let (alice, bob, server, _) = set_up_clients(room_id, true, false).await;
2536        let alice_id = alice.user_id().unwrap();
2537
2538        // ... in which Alice sends a message.
2539        let (root, root_key) = send_encrypted(
2540            &server,
2541            &alice,
2542            room_id,
2543            root_id,
2544            RoomMessageEventContent::text_plain("Root"),
2545        )
2546        .await;
2547
2548        // Alice discards the room key ...
2549        alice.get_room(room_id).unwrap().discard_room_key().await.unwrap();
2550
2551        // ... then sends a reply in a new thread using a newly generated room
2552        // key.
2553        let (reply, reply_key) = send_encrypted(
2554            &server,
2555            &alice,
2556            room_id,
2557            reply_id,
2558            make_thread_reply_event_content(root_id, alice_id),
2559        )
2560        .await;
2561
2562        // Bob receives both room keys first, then the reply bundled as the
2563        // latest thread event of the root.
2564        sync_room_keys(&server, &bob, &[root_key, reply_key]).await;
2565        sync_room(
2566            &server,
2567            &bob,
2568            // Servers only bundle aggregations into limited timelines, per https://spec.matrix.org/latest/client-server-api/#aggregations-of-child-events
2569            JoinedRoomBuilder::new(room_id)
2570                .add_timeline_event(with_bundled_thread(&root, &reply))
2571                .set_timeline_limited()
2572                .set_timeline_prev_batch("prev_batch"),
2573        )
2574        .await;
2575
2576        // Bob should have both events in his cache, and they should be
2577        // decrypted.
2578        assert_matches!(
2579            get_cached_timeline_event_kind(&bob, room_id, root_id).await,
2580            Some(TimelineEventKind::Decrypted { .. })
2581        );
2582        assert_matches!(
2583            get_cached_timeline_event_kind(&bob, room_id, reply_id).await,
2584            Some(TimelineEventKind::Decrypted { .. })
2585        );
2586    }
2587
2588    /// Case 3: The root key arrives first, then the root and bundled reply
2589    /// arrive in a single sync, then the reply key arrives.
2590    #[async_test]
2591    async fn test_bundled_thread_reply_key_arrives_later() {
2592        let room_id = room_id!("!test:localhost");
2593        let root_id = event_id!("$root");
2594        let reply_id = event_id!("$reply");
2595
2596        // Alice and Bob are in an encrypted room ...
2597        let (alice, bob, server, _) = set_up_clients(room_id, true, false).await;
2598        let alice_id = alice.user_id().unwrap();
2599
2600        // ... in which Alice sends a message.
2601        let (root, root_key) = send_encrypted(
2602            &server,
2603            &alice,
2604            room_id,
2605            root_id,
2606            RoomMessageEventContent::text_plain("Root"),
2607        )
2608        .await;
2609
2610        // Alice discards the room key ...
2611        alice.get_room(room_id).unwrap().discard_room_key().await.unwrap();
2612
2613        // ... then sends a reply in a new thread using a newly generated room
2614        // key.
2615        let (reply, reply_key) = send_encrypted(
2616            &server,
2617            &alice,
2618            room_id,
2619            reply_id,
2620            make_thread_reply_event_content(root_id, alice_id),
2621        )
2622        .await;
2623
2624        // Bob receives the root key first, then the root and reply events
2625        // bundled together, but not the reply key.
2626        sync_room_keys(&server, &bob, &[root_key]).await;
2627        sync_room(
2628            &server,
2629            &bob,
2630            // Servers only bundle aggregations into limited timelines, per https://spec.matrix.org/latest/client-server-api/#aggregations-of-child-events
2631            JoinedRoomBuilder::new(room_id)
2632                .add_timeline_event(with_bundled_thread(&root, &reply))
2633                .set_timeline_limited()
2634                .set_timeline_prev_batch("prev_batch"),
2635        )
2636        .await;
2637
2638        // Bob should have both events in his cache, but should only be able to
2639        // decrypt the root.
2640        assert_matches!(
2641            get_cached_timeline_event_kind(&bob, room_id, root_id).await,
2642            Some(TimelineEventKind::Decrypted { .. })
2643        );
2644        // Bob should also know why the decryption failed, rather than a generic
2645        // `UnableToDecryptReason::Unknown`.
2646        assert_let!(
2647            Some(TimelineEventKind::UnableToDecrypt { utd_info, .. }) =
2648                get_cached_timeline_event_kind(&bob, room_id, reply_id).await
2649        );
2650        assert_matches!(
2651            utd_info.reason,
2652            UnableToDecryptReason::MissingMegolmSession { withheld_code: None }
2653        );
2654
2655        // Now Bob receives the reply key ...
2656        sync_room_keys(&server, &bob, &[reply_key]).await;
2657
2658        // ... and should therefore be able to decrypt the reply as well.
2659        assert_matches!(
2660            get_cached_timeline_event_kind(&bob, room_id, reply_id).await,
2661            Some(TimelineEventKind::Decrypted { .. })
2662        );
2663    }
2664
2665    /// Case 4: The reply key arrives first, then the root and bundled reply
2666    /// arrive in a single sync, then the root key arrives.
2667    #[async_test]
2668    async fn test_bundled_thread_reply_root_key_arrives_later() {
2669        let room_id = room_id!("!test:localhost");
2670        let root_id = event_id!("$root");
2671        let reply_id = event_id!("$reply");
2672
2673        // Alice and Bob are in an encrypted room ...
2674        let (alice, bob, server, _) = set_up_clients(room_id, true, false).await;
2675        let alice_id = alice.user_id().unwrap();
2676
2677        // ... in which Alice sends a message.
2678        let (root, root_key) = send_encrypted(
2679            &server,
2680            &alice,
2681            room_id,
2682            root_id,
2683            RoomMessageEventContent::text_plain("Root"),
2684        )
2685        .await;
2686
2687        // Alice discards the room key ...
2688        alice.get_room(room_id).unwrap().discard_room_key().await.unwrap();
2689
2690        // ... then sends a reply in a new thread using a newly generated room
2691        // key.
2692        let (reply, reply_key) = send_encrypted(
2693            &server,
2694            &alice,
2695            room_id,
2696            reply_id,
2697            make_thread_reply_event_content(root_id, alice_id),
2698        )
2699        .await;
2700
2701        // Bob receives the reply key first, then the root and reply events
2702        // bundled together, but not the root key.
2703        sync_room_keys(&server, &bob, &[reply_key]).await;
2704        sync_room(
2705            &server,
2706            &bob,
2707            // Servers only bundle aggregations into limited timelines, per https://spec.matrix.org/latest/client-server-api/#aggregations-of-child-events
2708            JoinedRoomBuilder::new(room_id)
2709                .add_timeline_event(with_bundled_thread(&root, &reply))
2710                .set_timeline_limited()
2711                .set_timeline_prev_batch("prev_batch"),
2712        )
2713        .await;
2714
2715        // Bob should have both events in his cache. The root stays a UTD, since
2716        // its room key is still missing, but the reply must be
2717        // decrypted: it was bundled inside a UTD, so nothing decrypted
2718        // it on the way in, but Bob does have its room key, and the
2719        // redecryptor is asked to retry bundled UTDs as soon as they're
2720        // saved.
2721        assert_matches!(
2722            get_cached_timeline_event_kind(&bob, room_id, root_id).await,
2723            Some(TimelineEventKind::UnableToDecrypt { .. })
2724        );
2725        assert_matches!(
2726            get_cached_timeline_event_kind(&bob, room_id, reply_id).await,
2727            Some(TimelineEventKind::Decrypted { .. })
2728        );
2729
2730        // Now Bob receives the root key ...
2731        sync_room_keys(&server, &bob, &[root_key]).await;
2732
2733        // ... and should therefore be able to decrypt both the root and the
2734        // reply.
2735        assert_matches!(
2736            get_cached_timeline_event_kind(&bob, room_id, root_id).await,
2737            Some(TimelineEventKind::Decrypted { .. })
2738        );
2739        assert_matches!(
2740            get_cached_timeline_event_kind(&bob, room_id, reply_id).await,
2741            Some(TimelineEventKind::Decrypted { .. })
2742        );
2743    }
2744}