Skip to main content

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;
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.
29///
30/// The returned [`TimelineEvent`] has no push actions set up. It's the
31/// responsibility of the caller to set them.
32pub async fn sync_timeline_event(
33    e2ee: E2EE<'_>,
34    event: &TimelineEvent,
35    room_id: &RoomId,
36) -> Result<Option<TimelineEvent>> {
37    let Some(olm) = e2ee.olm_machine else { return Ok(None) };
38
39    Ok(Some(
40        match olm
41            .try_decrypt_room_event(
42                event.raw().cast_ref_unchecked(),
43                room_id,
44                e2ee.decryption_settings,
45            )
46            .await?
47        {
48            RoomEventDecryptionResult::Decrypted(decrypted) => {
49                // Note: the push actions are set by the caller.
50                let timeline_event = event.to_decrypted(decrypted, None);
51
52                if let Ok(sync_timeline_event) = timeline_event.raw().deserialize() {
53                    verification::process_if_relevant(&sync_timeline_event, e2ee, room_id).await?;
54                }
55
56                timeline_event
57            }
58            RoomEventDecryptionResult::UnableToDecrypt(utd_info) => event.to_utd(utd_info),
59        },
60    ))
61}