matrix_sdk_base/response_processors/e2ee/decrypt.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
15use matrix_sdk_common::deserialized_responses::TimelineEvent;
16use matrix_sdk_crypto::RoomEventDecryptionResult;
17use ruma::{RoomId, events::AnySyncTimelineEvent, serde::Raw};
18
19use super::{super::verification, E2EE};
20use crate::Result;
21
22/// Attempt to decrypt the given raw event into a [`TimelineEvent`].
23///
24/// In the case of a decryption error, returns a [`TimelineEvent`]
25/// representing the decryption error; in the case of problems with our
26/// application, returns `Err`.
27///
28/// Returns `Ok(None)` if encryption is not configured.
29pub async fn sync_timeline_event(
30 e2ee: E2EE<'_>,
31 event: &Raw<AnySyncTimelineEvent>,
32 room_id: &RoomId,
33) -> Result<Option<TimelineEvent>> {
34 let Some(olm) = e2ee.olm_machine else { return Ok(None) };
35
36 Ok(Some(
37 match olm
38 .try_decrypt_room_event(event.cast_ref_unchecked(), room_id, e2ee.decryption_settings)
39 .await?
40 {
41 RoomEventDecryptionResult::Decrypted(decrypted) => {
42 // Note: the push actions are set by the caller.
43 let timeline_event = TimelineEvent::from_decrypted(decrypted, None);
44
45 if let Ok(sync_timeline_event) = timeline_event.raw().deserialize() {
46 verification::process_if_relevant(&sync_timeline_event, e2ee, room_id).await?;
47 }
48
49 timeline_event
50 }
51 RoomEventDecryptionResult::UnableToDecrypt(utd_info) => {
52 TimelineEvent::from_utd(event.clone(), utd_info)
53 }
54 },
55 ))
56}