Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for UTD error codes in [Sync]TimelineEvent #4070

Merged
merged 4 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 39 additions & 18 deletions crates/matrix-sdk-base/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ use futures_util::Stream;
#[cfg(feature = "e2e-encryption")]
use matrix_sdk_crypto::{
store::DynCryptoStore, CollectStrategy, DecryptionSettings, EncryptionSettings,
EncryptionSyncChanges, OlmError, OlmMachine, ToDeviceRequest, TrustRequirement,
EncryptionSyncChanges, OlmError, OlmMachine, RoomEventDecryptionResult, ToDeviceRequest,
TrustRequirement,
};
#[cfg(feature = "e2e-encryption")]
use ruma::events::{
Expand Down Expand Up @@ -343,6 +344,13 @@ impl BaseClient {
Ok(())
}

/// Attempt to decrypt the given raw event into a `SyncTimelineEvent`.
///
/// In the case of a decryption error, returns a `SyncTimelineEvent`
/// representing the decryption error; in the case of problems with our
/// application, returns `Err`.
///
/// Returns `Ok(None)` if encryption is not configured.
#[cfg(feature = "e2e-encryption")]
async fn decrypt_sync_room_event(
&self,
Expand All @@ -355,24 +363,37 @@ impl BaseClient {
let decryption_settings = DecryptionSettings {
sender_device_trust_requirement: self.decryption_trust_requirement,
};
let event: SyncTimelineEvent =
olm.decrypt_room_event(event.cast_ref(), room_id, &decryption_settings).await?.into();

if let Ok(AnySyncTimelineEvent::MessageLike(e)) = event.raw().deserialize() {
match &e {
AnySyncMessageLikeEvent::RoomMessage(SyncMessageLikeEvent::Original(
original_event,
)) => {
if let MessageType::VerificationRequest(_) = &original_event.content.msgtype {
self.handle_verification_event(&e, room_id).await?;

let event = match olm
.try_decrypt_room_event(event.cast_ref(), room_id, &decryption_settings)
.await?
{
RoomEventDecryptionResult::Decrypted(decrypted) => {
let event: SyncTimelineEvent = decrypted.into();

if let Ok(AnySyncTimelineEvent::MessageLike(e)) = event.raw().deserialize() {
match &e {
AnySyncMessageLikeEvent::RoomMessage(SyncMessageLikeEvent::Original(
original_event,
)) => {
if let MessageType::VerificationRequest(_) =
&original_event.content.msgtype
{
self.handle_verification_event(&e, room_id).await?;
}
}
_ if e.event_type().to_string().starts_with("m.key.verification") => {
self.handle_verification_event(&e, room_id).await?;
}
_ => (),
}
}
_ if e.event_type().to_string().starts_with("m.key.verification") => {
self.handle_verification_event(&e, room_id).await?;
}
_ => (),
event
}
}
RoomEventDecryptionResult::UnableToDecrypt(utd_info) => {
SyncTimelineEvent::new_utd_event(event.clone(), utd_info)
}
};

Ok(Some(event))
}
Expand Down Expand Up @@ -460,10 +481,10 @@ impl BaseClient {
AnySyncMessageLikeEvent::RoomEncrypted(
SyncMessageLikeEvent::Original(_),
) => {
if let Ok(Some(e)) = Box::pin(
if let Some(e) = Box::pin(
self.decrypt_sync_room_event(event.raw(), room.room_id()),
)
.await
.await?
{
event = e;
}
Expand Down
11 changes: 9 additions & 2 deletions crates/matrix-sdk-base/src/sliding_sync/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -876,7 +876,10 @@ mod tests {
};

use assert_matches::assert_matches;
use matrix_sdk_common::{deserialized_responses::SyncTimelineEvent, ring_buffer::RingBuffer};
use matrix_sdk_common::{
deserialized_responses::{SyncTimelineEvent, UnableToDecryptInfo, UnableToDecryptReason},
ring_buffer::RingBuffer,
};
use matrix_sdk_test::async_test;
use ruma::{
api::client::sync::sync_events::UnreadNotificationsCount,
Expand Down Expand Up @@ -2494,7 +2497,7 @@ mod tests {
}

fn make_encrypted_event(id: &str) -> SyncTimelineEvent {
SyncTimelineEvent::new(
SyncTimelineEvent::new_utd_event(
Raw::from_json_string(
json!({
"type": "m.room.encrypted",
Expand All @@ -2512,6 +2515,10 @@ mod tests {
.to_string(),
)
.unwrap(),
UnableToDecryptInfo {
session_id: Some("".to_owned()),
reason: UnableToDecryptReason::MissingMegolmSession,
},
)
}

Expand Down
39 changes: 39 additions & 0 deletions crates/matrix-sdk-common/src/deserialized_responses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,12 @@ impl SyncTimelineEvent {
Self { kind: TimelineEventKind::PlainText { event }, push_actions }
}

/// Create a new `SyncTimelineEvent` to represent the given decryption
/// failure.
pub fn new_utd_event(event: Raw<AnySyncTimelineEvent>, utd_info: UnableToDecryptInfo) -> Self {
Self { kind: TimelineEventKind::UnableToDecrypt { event, utd_info }, push_actions: vec![] }
}

/// Get the event id of this `SyncTimelineEvent` if the event has any valid
/// id.
pub fn event_id(&self) -> Option<OwnedEventId> {
Expand Down Expand Up @@ -450,6 +456,11 @@ impl TimelineEvent {
}
}

/// Create a new `TimelineEvent` to represent the given decryption failure.
pub fn new_utd_event(event: Raw<AnySyncTimelineEvent>, utd_info: UnableToDecryptInfo) -> Self {
Self { kind: TimelineEventKind::UnableToDecrypt { event, utd_info }, push_actions: None }
}

/// Returns a reference to the (potentially decrypted) Matrix event inside
/// this `TimelineEvent`.
pub fn raw(&self) -> &Raw<AnySyncTimelineEvent> {
Expand Down Expand Up @@ -482,6 +493,17 @@ pub enum TimelineEventKind {
/// A successfully-decrypted encrypted event.
Decrypted(DecryptedRoomEvent),

/// An encrypted event which could not be decrypted.
UnableToDecrypt {
/// The `m.room.encrypted` event. Depending on the source of the event,
/// it could actually be an [`AnyTimelineEvent`] (i.e., it may
/// have a `room_id` property).
event: Raw<AnySyncTimelineEvent>,

/// Information on the reason we failed to decrypt
utd_info: UnableToDecryptInfo,
},

/// An unencrypted event.
PlainText {
/// The actual event. Depending on the source of the event, it could
Expand All @@ -502,6 +524,7 @@ impl TimelineEventKind {
// expected to contain a `room_id`). It just means that the `room_id` will be ignored
// in a future deserialization.
TimelineEventKind::Decrypted(d) => d.event.cast_ref(),
TimelineEventKind::UnableToDecrypt { event, .. } => event.cast_ref(),
TimelineEventKind::PlainText { event } => event,
}
}
Expand All @@ -511,6 +534,7 @@ impl TimelineEventKind {
pub fn encryption_info(&self) -> Option<&EncryptionInfo> {
match self {
TimelineEventKind::Decrypted(d) => Some(&d.encryption_info),
TimelineEventKind::UnableToDecrypt { .. } => None,
TimelineEventKind::PlainText { .. } => None,
}
}
Expand All @@ -525,6 +549,7 @@ impl TimelineEventKind {
// expected to contain a `room_id`). It just means that the `room_id` will be ignored
// in a future deserialization.
TimelineEventKind::Decrypted(d) => d.event.cast(),
TimelineEventKind::UnableToDecrypt { event, .. } => event.cast(),
TimelineEventKind::PlainText { event } => event,
}
}
Expand All @@ -539,6 +564,12 @@ impl fmt::Debug for TimelineEventKind {
.field("event", &DebugRawEvent(event))
.finish(),

Self::UnableToDecrypt { event, utd_info } => f
.debug_struct("TimelineEventDecryptionResult::UnableToDecrypt")
.field("event", &DebugRawEvent(event))
.field("utd_info", &utd_info)
.finish(),

Self::Decrypted(decrypted) => {
f.debug_tuple("TimelineEventDecryptionResult::Decrypted").field(decrypted).finish()
}
Expand Down Expand Up @@ -677,6 +708,14 @@ pub enum UnableToDecryptReason {
SenderIdentityNotTrusted(VerificationLevel),
}

impl UnableToDecryptReason {
/// Returns true if this UTD is due to a missing room key (and hence might
/// resolve itself if we wait a bit.)
pub fn is_missing_room_key(&self) -> bool {
matches!(self, Self::MissingMegolmSession | Self::UnknownMegolmMessageIndex)
}
}

/// Deserialization helper for [`SyncTimelineEvent`], for the modern format.
///
/// This has the exact same fields as [`SyncTimelineEvent`] itself, but has a
Expand Down
54 changes: 31 additions & 23 deletions crates/matrix-sdk-ui/src/notification_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,7 @@ use std::{
use futures_util::{pin_mut, StreamExt as _};
use matrix_sdk::{room::Room, Client, ClientBuildError, SlidingSyncList, SlidingSyncMode};
use matrix_sdk_base::{
crypto::{vodozemac, MegolmError},
deserialized_responses::TimelineEvent,
sliding_sync::http,
RoomState, StoreError,
deserialized_responses::TimelineEvent, sliding_sync::http, RoomState, StoreError,
};
use ruma::{
assign,
Expand Down Expand Up @@ -216,24 +213,24 @@ impl NotificationClient {

tokio::time::sleep(Duration::from_millis(wait)).await;

match room.decrypt_event(raw_event.cast_ref()).await {
Ok(new_event) => {
let new_event = room.decrypt_event(raw_event.cast_ref()).await?;

match new_event.kind {
matrix_sdk::deserialized_responses::TimelineEventKind::UnableToDecrypt {
utd_info, ..} => {
if utd_info.reason.is_missing_room_key() {
// Decryption error that could be caused by a missing room
// key; retry in a few.
wait *= 2;
} else {
debug!("Event could not be decrypted, but waiting longer is unlikely to help: {:?}", utd_info.reason);
return Ok(None);
}
}
_ => {
trace!("Waiting succeeded and event could be decrypted!");
return Ok(Some(new_event));
}
Err(matrix_sdk::Error::MegolmError(
MegolmError::MissingRoomKey(_)
| MegolmError::Decryption(
vodozemac::megolm::DecryptionError::UnknownMessageIndex(_, _),
),
)) => {
// Decryption error that could be caused by a missing room key;
// retry in a few.
wait *= 2;
}
Err(err) => {
return Err(err.into());
}
}
}

Expand All @@ -259,10 +256,21 @@ impl NotificationClient {
match encryption_sync {
Ok(sync) => match sync.run_fixed_iterations(2, sync_permit_guard).await {
Ok(()) => match room.decrypt_event(raw_event.cast_ref()).await {
Ok(new_event) => {
trace!("Encryption sync managed to decrypt the event.");
Ok(Some(new_event))
}
Ok(new_event) => match new_event.kind {
matrix_sdk::deserialized_responses::TimelineEventKind::UnableToDecrypt {
utd_info, ..
} => {
trace!(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe here too?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again, the actual error will be logged at warning, and in this case it's just replicating the previous behaviour (note the trace!("Encryption sync failed to decrypt the event: {err}"); just below).

I can change this if you feel strongly but it's not obvious to me that we should.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No no, that's quite okay, I didn't check the lower levels to see if we print it anywhere else.

"Encryption sync failed to decrypt the event: {:?}",
utd_info.reason
);
Ok(None)
}
_ => {
trace!("Encryption sync managed to decrypt the event.");
Ok(Some(new_event))
}
},
Err(err) => {
trace!("Encryption sync failed to decrypt the event: {err}");
Ok(None)
Expand Down
Loading
Loading