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

Timeline: Extend UtdCause with new reason codes #4126

Merged
merged 7 commits into from
Oct 23, 2024
2 changes: 2 additions & 0 deletions crates/matrix-sdk-crypto/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,8 @@ pub enum MegolmError {
/// An encrypted message wasn't decrypted, because the sender's
/// cross-signing identity did not satisfy the requested
/// [`crate::TrustRequirement`].
///
/// The nested value is the sender's current verification level.
#[error("decryption failed because trust requirement not satisfied: {0}")]
SenderIdentityNotTrusted(VerificationLevel),
}
Expand Down
232 changes: 189 additions & 43 deletions crates/matrix-sdk-crypto/src/types/events/utd_cause.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use matrix_sdk_common::deserialized_responses::{
UnableToDecryptInfo, UnableToDecryptReason, VerificationLevel,
};
use ruma::{events::AnySyncTimelineEvent, serde::Raw};
use serde::Deserialize;

Expand All @@ -24,16 +27,26 @@ pub enum UtdCause {
#[default]
Unknown = 0,

/// This event was sent when we were not a member of the room (or invited),
/// so it is impossible to decrypt (without MSC3061).
Membership = 1,
//
// TODO: Other causes for UTDs. For example, this message is device-historical, information
// extracted from the WithheldCode in the MissingRoomKey object, or various types of Olm
// session problems.
//
// Note: This needs to be a simple enum so we can export it via FFI, so if more information
// needs to be provided, it should be through a separate type.
/// We are missing the keys for this event, and the event was sent when we
/// were not a member of the room (or invited).
SentBeforeWeJoined = 1,

/// The message was sent by a user identity we have not verified, but the
/// user was previously verified.
VerificationViolation = 2,

/// The [`crate::TrustRequirement`] requires that the sending device be
/// signed by its owner, and it was not.
UnsignedDevice = 3,

/// The [`crate::TrustRequirement`] requires that the sending device be
/// signed by its owner, and we were unable to securely find the device.
///
/// This could be because the device has since been deleted, because we
/// haven't yet downloaded it from the server, or because the session
/// data was obtained from an insecure source (imported from a file,
/// obtained from a legacy (asymmetric) backup, unsafe key forward, etc.)
UnknownDevice = 4,
}

/// MSC4115 membership info in the unsigned area.
Expand All @@ -54,96 +67,229 @@ enum Membership {

impl UtdCause {
/// Decide the cause of this UTD, based on the evidence we have.
pub fn determine(raw_event: Option<&Raw<AnySyncTimelineEvent>>) -> Self {
pub fn determine(
raw_event: Option<&Raw<AnySyncTimelineEvent>>,
unable_to_decrypt_info: &UnableToDecryptInfo,
) -> Self {
// TODO: in future, use more information to give a richer answer. E.g.
// is this event device-historical? Was the Olm communication disrupted?
// Did the sender refuse to send the key because we're not verified?

// Look in the unsigned area for a `membership` field.
if let Some(raw_event) = raw_event {
if let Ok(Some(unsigned)) = raw_event.get_field::<UnsignedWithMembership>("unsigned") {
if let Membership::Leave = unsigned.membership {
// We were not a member - this is the cause of the UTD
return UtdCause::Membership;
match unable_to_decrypt_info.reason {
UnableToDecryptReason::MissingMegolmSession
| UnableToDecryptReason::UnknownMegolmMessageIndex => {
// Look in the unsigned area for a `membership` field.
if let Some(raw_event) = raw_event {
if let Ok(Some(unsigned)) =
raw_event.get_field::<UnsignedWithMembership>("unsigned")
{
if let Membership::Leave = unsigned.membership {
// We were not a member - this is the cause of the UTD
return UtdCause::SentBeforeWeJoined;
}
}
}
UtdCause::Unknown
}

UnableToDecryptReason::SenderIdentityNotTrusted(
VerificationLevel::VerificationViolation,
) => UtdCause::VerificationViolation,

UnableToDecryptReason::SenderIdentityNotTrusted(VerificationLevel::UnsignedDevice) => {
UtdCause::UnsignedDevice
}

UnableToDecryptReason::SenderIdentityNotTrusted(VerificationLevel::None(_)) => {
UtdCause::UnknownDevice
}
}

// We can't find an explanation for this UTD
UtdCause::Unknown
_ => UtdCause::Unknown,
}
}
}

#[cfg(test)]
mod tests {
use matrix_sdk_common::deserialized_responses::{
DeviceLinkProblem, UnableToDecryptInfo, UnableToDecryptReason, VerificationLevel,
};
use ruma::{events::AnySyncTimelineEvent, serde::Raw};
use serde_json::{json, value::to_raw_value};

use crate::types::events::UtdCause;

#[test]
fn a_missing_raw_event_means_we_guess_unknown() {
fn test_a_missing_raw_event_means_we_guess_unknown() {
// When we don't provide any JSON to check for membership, then we guess the UTD
// is unknown.
assert_eq!(UtdCause::determine(None), UtdCause::Unknown);
assert_eq!(
UtdCause::determine(
None,
&UnableToDecryptInfo {
session_id: None,
reason: UnableToDecryptReason::MissingMegolmSession,
}
),
UtdCause::Unknown
);
}

#[test]
fn if_there_is_no_membership_info_we_guess_unknown() {
fn test_if_there_is_no_membership_info_we_guess_unknown() {
// If our JSON contains no membership info, then we guess the UTD is unknown.
assert_eq!(UtdCause::determine(Some(&raw_event(json!({})))), UtdCause::Unknown);
assert_eq!(
UtdCause::determine(
Some(&raw_event(json!({}))),
&UnableToDecryptInfo {
session_id: None,
reason: UnableToDecryptReason::MissingMegolmSession
}
),
UtdCause::Unknown
);
}

#[test]
fn if_membership_info_cant_be_parsed_we_guess_unknown() {
fn test_if_membership_info_cant_be_parsed_we_guess_unknown() {
// If our JSON contains a membership property but not the JSON we expected, then
// we guess the UTD is unknown.
assert_eq!(
UtdCause::determine(Some(&raw_event(json!({ "unsigned": { "membership": 3 } })))),
UtdCause::determine(
Some(&raw_event(json!({ "unsigned": { "membership": 3 } }))),
&UnableToDecryptInfo {
session_id: None,
reason: UnableToDecryptReason::MissingMegolmSession
}
),
UtdCause::Unknown
);
}

#[test]
fn if_membership_is_invite_we_guess_unknown() {
fn test_if_membership_is_invite_we_guess_unknown() {
// If membership=invite then we expected to be sent the keys so the cause of the
// UTD is unknown.
assert_eq!(
UtdCause::determine(Some(&raw_event(
json!({ "unsigned": { "membership": "invite" } }),
))),
UtdCause::determine(
Some(&raw_event(json!({ "unsigned": { "membership": "invite" } }),)),
&UnableToDecryptInfo {
session_id: None,
reason: UnableToDecryptReason::MissingMegolmSession
}
),
UtdCause::Unknown
);
}

#[test]
fn if_membership_is_join_we_guess_unknown() {
fn test_if_membership_is_join_we_guess_unknown() {
// If membership=join then we expected to be sent the keys so the cause of the
// UTD is unknown.
assert_eq!(
UtdCause::determine(Some(&raw_event(json!({ "unsigned": { "membership": "join" } })))),
UtdCause::determine(
Some(&raw_event(json!({ "unsigned": { "membership": "join" } }))),
&UnableToDecryptInfo {
session_id: None,
reason: UnableToDecryptReason::MissingMegolmSession
}
),
UtdCause::Unknown
);
}

#[test]
fn if_membership_is_leave_we_guess_membership() {
fn test_if_membership_is_leave_we_guess_membership() {
// If membership=leave then we have an explanation for why we can't decrypt,
// until we have MSC3061.
assert_eq!(
UtdCause::determine(Some(&raw_event(json!({ "unsigned": { "membership": "leave" } })))),
UtdCause::Membership
UtdCause::determine(
Some(&raw_event(json!({ "unsigned": { "membership": "leave" } }))),
&UnableToDecryptInfo {
session_id: None,
reason: UnableToDecryptReason::MissingMegolmSession
}
),
UtdCause::SentBeforeWeJoined
);
}

#[test]
fn test_if_reason_is_not_missing_key_we_guess_unknown_even_if_membership_is_leave() {
// If the UnableToDecryptReason is other than MissingMegolmSession or
// UnknownMegolmMessageIndex, we do not know the reason for the failure
// even if membership=leave.
assert_eq!(
UtdCause::determine(
Some(&raw_event(json!({ "unsigned": { "membership": "leave" } }))),
&UnableToDecryptInfo {
session_id: None,
reason: UnableToDecryptReason::MalformedEncryptedEvent
}
),
UtdCause::Unknown
);
}

#[test]
fn if_unstable_prefix_membership_is_leave_we_guess_membership() {
fn test_if_unstable_prefix_membership_is_leave_we_guess_membership() {
// Before MSC4115 is merged, we support the unstable prefix too.
assert_eq!(
UtdCause::determine(Some(&raw_event(
json!({ "unsigned": { "io.element.msc4115.membership": "leave" } })
))),
UtdCause::Membership
UtdCause::determine(
Some(&raw_event(
json!({ "unsigned": { "io.element.msc4115.membership": "leave" } })
)),
&UnableToDecryptInfo {
session_id: None,
reason: UnableToDecryptReason::MissingMegolmSession
}
),
UtdCause::SentBeforeWeJoined
);
}

#[test]
fn test_verification_violation_is_passed_through() {
assert_eq!(
UtdCause::determine(
Some(&raw_event(json!({}))),
&UnableToDecryptInfo {
session_id: None,
reason: UnableToDecryptReason::SenderIdentityNotTrusted(
VerificationLevel::VerificationViolation,
)
}
),
UtdCause::VerificationViolation
);
}

#[test]
fn test_unsigned_device_is_passed_through() {
assert_eq!(
UtdCause::determine(
Some(&raw_event(json!({}))),
&UnableToDecryptInfo {
session_id: None,
reason: UnableToDecryptReason::SenderIdentityNotTrusted(
VerificationLevel::UnsignedDevice,
)
}
),
UtdCause::UnsignedDevice
);
}

#[test]
fn test_unknown_device_is_passed_through() {
assert_eq!(
UtdCause::determine(
Some(&raw_event(json!({}))),
&UnableToDecryptInfo {
session_id: None,
reason: UnableToDecryptReason::SenderIdentityNotTrusted(
VerificationLevel::None(DeviceLinkProblem::MissingDevice)
)
}
),
UtdCause::UnknownDevice
);
}

Expand Down
27 changes: 12 additions & 15 deletions crates/matrix-sdk-ui/src/timeline/controller/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -989,8 +989,6 @@ impl<P: RoomDataProvider> TimelineController<P> {
decryptor: impl Decryptor,
session_ids: Option<BTreeSet<String>>,
) {
use matrix_sdk::crypto::types::events::UtdCause;

use super::EncryptedMessage;

let mut state = self.state.clone().write_owned().await;
Expand Down Expand Up @@ -1038,16 +1036,17 @@ impl<P: RoomDataProvider> TimelineController<P> {
async move {
let event_item = item.as_event()?;

let session_id = match event_item.content().as_unable_to_decrypt()? {
EncryptedMessage::MegolmV1AesSha2 { session_id, .. }
if should_retry(session_id) =>
{
session_id
}
EncryptedMessage::MegolmV1AesSha2 { .. }
| EncryptedMessage::OlmV1Curve25519AesSha2 { .. }
| EncryptedMessage::Unknown => return None,
};
let (session_id, utd_cause) =
match event_item.content().as_unable_to_decrypt()? {
EncryptedMessage::MegolmV1AesSha2 { session_id, cause, .. }
if should_retry(session_id) =>
{
(session_id, cause)
}
EncryptedMessage::MegolmV1AesSha2 { .. }
| EncryptedMessage::OlmV1Curve25519AesSha2 { .. }
| EncryptedMessage::Unknown => return None,
};

tracing::Span::current().record("session_id", session_id);

Expand All @@ -1069,11 +1068,9 @@ impl<P: RoomDataProvider> TimelineController<P> {
"Successfully decrypted event that previously failed to decrypt"
);

let cause = UtdCause::determine(Some(original_json));

// Notify observers that we managed to eventually decrypt an event.
if let Some(hook) = unable_to_decrypt_hook {
hook.on_late_decrypt(&remote_event.event_id, cause).await;
hook.on_late_decrypt(&remote_event.event_id, *utd_cause).await;
}

Some(event)
Expand Down
Loading
Loading