Skip to content

Commit 25f893b

Browse files
committed
Merge branch 'main' into bnjbvr/permalink-mvp
2 parents 397a26e + 4156170 commit 25f893b

File tree

16 files changed

+385
-58
lines changed

16 files changed

+385
-58
lines changed

bindings/matrix-sdk-ffi/src/authentication_service.rs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use std::{
44
};
55

66
use matrix_sdk::{
7+
encryption::BackupDownloadStrategy,
78
oidc::{
89
registrations::{ClientId, OidcRegistrations, OidcRegistrationsError},
910
types::{
@@ -621,12 +622,9 @@ impl AuthenticationService {
621622
.passphrase(self.passphrase.clone())
622623
.homeserver_url(homeserver_url)
623624
.sliding_sync_proxy(sliding_sync_proxy)
624-
.with_encryption_settings(matrix_sdk::encryption::EncryptionSettings {
625-
auto_enable_cross_signing: true,
626-
backup_download_strategy:
627-
matrix_sdk::encryption::BackupDownloadStrategy::AfterDecryptionFailure,
628-
auto_enable_backups: true,
629-
})
625+
.auto_enable_cross_signing(true)
626+
.backup_download_strategy(BackupDownloadStrategy::AfterDecryptionFailure)
627+
.auto_enable_backups(true)
630628
.username(user_id.to_string());
631629

632630
if let Some(proxy) = &self.proxy {

bindings/matrix-sdk-ffi/src/client_builder.rs

Lines changed: 37 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ pub struct ClientBuilder {
7676
cross_process_refresh_lock_id: Option<String>,
7777
session_delegate: Option<Arc<dyn ClientSessionDelegate>>,
7878
additional_root_certificates: Vec<Vec<u8>>,
79+
encryption_settings: EncryptionSettings,
7980
}
8081

8182
#[uniffi::export(async_runtime = "tokio")]
@@ -93,14 +94,16 @@ impl ClientBuilder {
9394
proxy: None,
9495
disable_ssl_verification: false,
9596
disable_automatic_token_refresh: false,
96-
inner: MatrixClient::builder().with_encryption_settings(EncryptionSettings {
97-
auto_enable_cross_signing: false,
98-
backup_download_strategy: BackupDownloadStrategy::AfterDecryptionFailure,
99-
auto_enable_backups: false,
100-
}),
97+
inner: MatrixClient::builder(),
10198
cross_process_refresh_lock_id: None,
10299
session_delegate: None,
103100
additional_root_certificates: Default::default(),
101+
encryption_settings: EncryptionSettings {
102+
auto_enable_cross_signing: false,
103+
backup_download_strategy:
104+
matrix_sdk::encryption::BackupDownloadStrategy::AfterDecryptionFailure,
105+
auto_enable_backups: false,
106+
},
104107
})
105108
}
106109

@@ -203,21 +206,41 @@ impl ClientBuilder {
203206
Arc::new(builder)
204207
}
205208

206-
pub async fn build(self: Arc<Self>) -> Result<Arc<Client>, ClientBuildError> {
207-
Ok(Arc::new(self.build_inner().await?))
209+
pub fn auto_enable_cross_signing(
210+
self: Arc<Self>,
211+
auto_enable_cross_signing: bool,
212+
) -> Arc<Self> {
213+
let mut builder = unwrap_or_clone_arc(self);
214+
builder.encryption_settings.auto_enable_cross_signing = auto_enable_cross_signing;
215+
Arc::new(builder)
208216
}
209-
}
210217

211-
impl ClientBuilder {
212-
pub(crate) fn with_encryption_settings(
218+
/// Select a strategy to download room keys from the backup. By default
219+
/// we download after a decryption failure.
220+
///
221+
/// Take a look at the [`BackupDownloadStrategy`] enum for more options.
222+
pub fn backup_download_strategy(
213223
self: Arc<Self>,
214-
settings: EncryptionSettings,
224+
backup_download_strategy: BackupDownloadStrategy,
215225
) -> Arc<Self> {
216226
let mut builder = unwrap_or_clone_arc(self);
217-
builder.inner = builder.inner.with_encryption_settings(settings);
227+
builder.encryption_settings.backup_download_strategy = backup_download_strategy;
218228
Arc::new(builder)
219229
}
220230

231+
/// Automatically create a backup version if no backup exists.
232+
pub fn auto_enable_backups(self: Arc<Self>, auto_enable_backups: bool) -> Arc<Self> {
233+
let mut builder = unwrap_or_clone_arc(self);
234+
builder.encryption_settings.auto_enable_backups = auto_enable_backups;
235+
Arc::new(builder)
236+
}
237+
238+
pub async fn build(self: Arc<Self>) -> Result<Arc<Client>, ClientBuildError> {
239+
Ok(Arc::new(self.build_inner().await?))
240+
}
241+
}
242+
243+
impl ClientBuilder {
221244
pub(crate) fn enable_cross_process_refresh_lock_inner(
222245
self: Arc<Self>,
223246
process_id: String,
@@ -316,6 +339,8 @@ impl ClientBuilder {
316339
);
317340
}
318341

342+
inner_builder = inner_builder.with_encryption_settings(builder.encryption_settings);
343+
319344
let sdk_client = inner_builder.build().await?;
320345

321346
// At this point, `sdk_client` might contain a `sliding_sync_proxy` that has

bindings/matrix-sdk-ffi/src/sync_service.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
use std::{fmt::Debug, sync::Arc, time::Duration};
1616

1717
use futures_util::pin_mut;
18-
use matrix_sdk::Client;
18+
use matrix_sdk::{crypto::types::events::UtdCause, Client};
1919
use matrix_sdk_ui::{
2020
sync_service::{
2121
State as MatrixSyncServiceState, SyncService as MatrixSyncService,
@@ -187,13 +187,18 @@ pub struct UnableToDecryptInfo {
187187
///
188188
/// If set, this is in milliseconds.
189189
pub time_to_decrypt_ms: Option<u64>,
190+
191+
/// What we know about what caused this UTD. E.g. was this event sent when
192+
/// we were not a member of this room?
193+
pub cause: UtdCause,
190194
}
191195

192196
impl From<SdkUnableToDecryptInfo> for UnableToDecryptInfo {
193197
fn from(value: SdkUnableToDecryptInfo) -> Self {
194198
Self {
195199
event_id: value.event_id.to_string(),
196200
time_to_decrypt_ms: value.time_to_decrypt.map(|ttd| ttd.as_millis() as u64),
201+
cause: value.cause,
197202
}
198203
}
199204
}

bindings/matrix-sdk-ffi/src/timeline/content.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
use std::{collections::HashMap, sync::Arc};
1616

17-
use matrix_sdk::room::power_levels::power_level_user_changes;
17+
use matrix_sdk::{crypto::types::events::UtdCause, room::power_levels::power_level_user_changes};
1818
use matrix_sdk_ui::timeline::{PollResult, TimelineDetails};
1919
use tracing::warn;
2020

@@ -214,6 +214,10 @@ pub enum EncryptedMessage {
214214
MegolmV1AesSha2 {
215215
/// The ID of the session used to encrypt the message.
216216
session_id: String,
217+
218+
/// What we know about what caused this UTD. E.g. was this event sent
219+
/// when we were not a member of this room?
220+
cause: UtdCause,
217221
},
218222
Unknown,
219223
}
@@ -227,9 +231,9 @@ impl EncryptedMessage {
227231
let sender_key = sender_key.clone();
228232
Self::OlmV1Curve25519AesSha2 { sender_key }
229233
}
230-
Message::MegolmV1AesSha2 { session_id, .. } => {
234+
Message::MegolmV1AesSha2 { session_id, cause, .. } => {
231235
let session_id = session_id.clone();
232-
Self::MegolmV1AesSha2 { session_id }
236+
Self::MegolmV1AesSha2 { session_id, cause: *cause }
233237
}
234238
Message::Unknown => Self::Unknown,
235239
}

bindings/matrix-sdk-ffi/src/timeline/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ impl Timeline {
186186
/// Paginate forwards, when in focused mode.
187187
///
188188
/// Returns whether we hit the end of the timeline or not.
189-
pub async fn paginate_forwards(&self, num_events: u16) -> Result<bool, ClientError> {
189+
pub async fn focused_paginate_forwards(&self, num_events: u16) -> Result<bool, ClientError> {
190190
Ok(self.inner.focused_paginate_forwards(num_events).await?)
191191
}
192192

crates/matrix-sdk-base/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ qrcode = ["matrix-sdk-crypto?/qrcode"]
2323
automatic-room-key-forwarding = ["matrix-sdk-crypto?/automatic-room-key-forwarding"]
2424
message-ids = ["matrix-sdk-crypto?/message-ids"]
2525
experimental-sliding-sync = ["ruma/unstable-msc3575"]
26-
uniffi = ["dep:uniffi"]
26+
uniffi = ["dep:uniffi", "matrix-sdk-crypto?/uniffi"]
2727

2828
# helpers for testing features build upon this
2929
testing = [

crates/matrix-sdk-crypto/src/types/events/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,11 @@ pub mod room_key_request;
2727
pub mod room_key_withheld;
2828
pub mod secret_send;
2929
mod to_device;
30+
mod utd_cause;
3031

3132
use ruma::serde::Raw;
3233
pub use to_device::{ToDeviceCustomEvent, ToDeviceEvent, ToDeviceEvents};
34+
pub use utd_cause::UtdCause;
3335

3436
/// A trait for event contents to define their event type.
3537
pub trait EventType {
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
// Copyright 2024 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+
use ruma::{events::AnySyncTimelineEvent, serde::Raw};
16+
use serde::Deserialize;
17+
18+
/// Our best guess at the reason why an event can't be decrypted.
19+
#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
20+
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
21+
pub enum UtdCause {
22+
/// We don't have an explanation for why this UTD happened - it is probably
23+
/// a bug, or a network split between the two homeservers.
24+
#[default]
25+
Unknown = 0,
26+
27+
/// This event was sent when we were not a member of the room (or invited),
28+
/// so it is impossible to decrypt (without MSC3061).
29+
Membership = 1,
30+
//
31+
// TODO: Other causes for UTDs. For example, this message is device-historical, information
32+
// extracted from the WithheldCode in the MissingRoomKey object, or various types of Olm
33+
// session problems.
34+
//
35+
// Note: This needs to be a simple enum so we can export it via FFI, so if more information
36+
// needs to be provided, it should be through a separate type.
37+
}
38+
39+
/// MSC4115 membership info in the unsigned area.
40+
#[derive(Deserialize)]
41+
struct UnsignedWithMembership {
42+
#[serde(alias = "io.element.msc4115.membership")]
43+
membership: Membership,
44+
}
45+
46+
/// MSC4115 contents of the membership property
47+
#[derive(Deserialize)]
48+
#[serde(rename_all = "lowercase")]
49+
enum Membership {
50+
Leave,
51+
Invite,
52+
Join,
53+
}
54+
55+
impl UtdCause {
56+
/// Decide the cause of this UTD, based on the evidence we have.
57+
pub fn determine(raw_event: Option<&Raw<AnySyncTimelineEvent>>) -> Self {
58+
// TODO: in future, use more information to give a richer answer. E.g.
59+
// is this event device-historical? Was the Olm communication disrupted?
60+
// Did the sender refuse to send the key because we're not verified?
61+
62+
// Look in the unsigned area for a `membership` field.
63+
if let Some(raw_event) = raw_event {
64+
if let Ok(Some(unsigned)) = raw_event.get_field::<UnsignedWithMembership>("unsigned") {
65+
if let Membership::Leave = unsigned.membership {
66+
// We were not a member - this is the cause of the UTD
67+
return UtdCause::Membership;
68+
}
69+
}
70+
}
71+
72+
// We can't find an explanation for this UTD
73+
UtdCause::Unknown
74+
}
75+
}
76+
77+
#[cfg(test)]
78+
mod tests {
79+
use ruma::{events::AnySyncTimelineEvent, serde::Raw};
80+
use serde_json::{json, value::to_raw_value};
81+
82+
use crate::types::events::UtdCause;
83+
84+
#[test]
85+
fn a_missing_raw_event_means_we_guess_unknown() {
86+
// When we don't provide any JSON to check for membership, then we guess the UTD
87+
// is unknown.
88+
assert_eq!(UtdCause::determine(None), UtdCause::Unknown);
89+
}
90+
91+
#[test]
92+
fn if_there_is_no_membership_info_we_guess_unknown() {
93+
// If our JSON contains no membership info, then we guess the UTD is unknown.
94+
assert_eq!(UtdCause::determine(Some(&raw_event(json!({})))), UtdCause::Unknown);
95+
}
96+
97+
#[test]
98+
fn if_membership_info_cant_be_parsed_we_guess_unknown() {
99+
// If our JSON contains a membership property but not the JSON we expected, then
100+
// we guess the UTD is unknown.
101+
assert_eq!(
102+
UtdCause::determine(Some(&raw_event(json!({ "unsigned": { "membership": 3 } })))),
103+
UtdCause::Unknown
104+
);
105+
}
106+
107+
#[test]
108+
fn if_membership_is_invite_we_guess_unknown() {
109+
// If membership=invite then we expected to be sent the keys so the cause of the
110+
// UTD is unknown.
111+
assert_eq!(
112+
UtdCause::determine(Some(&raw_event(
113+
json!({ "unsigned": { "membership": "invite" } }),
114+
))),
115+
UtdCause::Unknown
116+
);
117+
}
118+
119+
#[test]
120+
fn if_membership_is_join_we_guess_unknown() {
121+
// If membership=join then we expected to be sent the keys so the cause of the
122+
// UTD is unknown.
123+
assert_eq!(
124+
UtdCause::determine(Some(&raw_event(json!({ "unsigned": { "membership": "join" } })))),
125+
UtdCause::Unknown
126+
);
127+
}
128+
129+
#[test]
130+
fn if_membership_is_leave_we_guess_membership() {
131+
// If membership=leave then we have an explanation for why we can't decrypt,
132+
// until we have MSC3061.
133+
assert_eq!(
134+
UtdCause::determine(Some(&raw_event(json!({ "unsigned": { "membership": "leave" } })))),
135+
UtdCause::Membership
136+
);
137+
}
138+
139+
#[test]
140+
fn if_unstable_prefix_membership_is_leave_we_guess_membership() {
141+
// Before MSC4115 is merged, we support the unstable prefix too.
142+
assert_eq!(
143+
UtdCause::determine(Some(&raw_event(
144+
json!({ "unsigned": { "io.element.msc4115.membership": "leave" } })
145+
))),
146+
UtdCause::Membership
147+
);
148+
}
149+
150+
fn raw_event(value: serde_json::Value) -> Raw<AnySyncTimelineEvent> {
151+
Raw::from_json(to_raw_value(&value).unwrap())
152+
}
153+
}

crates/matrix-sdk-ui/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ experimental-room-list-with-unified-invites = []
1818
native-tls = ["matrix-sdk/native-tls"]
1919
rustls-tls = ["matrix-sdk/rustls-tls"]
2020

21-
uniffi = ["dep:uniffi"]
21+
uniffi = ["dep:uniffi", "matrix-sdk/uniffi", "matrix-sdk-base/uniffi"]
2222

2323
[dependencies]
2424
as_variant = { workspace = true }

0 commit comments

Comments
 (0)