Skip to content

Commit 97ca9ee

Browse files
committed
refactor(crypto): Pass DecryptionSettings in to OlmMachine::decrypt_to_device_event
This will be used in the next commit, but it was very noisy, so I separated it out into this commit to make the next one easier to read.
1 parent c2f50fd commit 97ca9ee

File tree

17 files changed

+395
-128
lines changed

17 files changed

+395
-128
lines changed

bindings/matrix-sdk-crypto-ffi/src/dehydrated_devices.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use matrix_sdk_crypto::{
77
RehydratedDevice as InnerRehydratedDevice,
88
},
99
store::types::DehydratedDeviceKey as InnerDehydratedDeviceKey,
10+
DecryptionSettings,
1011
};
1112
use ruma::{api::client::dehydrated_device, events::AnyToDeviceEvent, serde::Raw, OwnedDeviceId};
1213
use serde_json::json;
@@ -154,9 +155,13 @@ impl Drop for RehydratedDevice {
154155

155156
#[matrix_sdk_ffi_macros::export]
156157
impl RehydratedDevice {
157-
pub fn receive_events(&self, events: String) -> Result<(), crate::CryptoStoreError> {
158+
pub fn receive_events(
159+
&self,
160+
events: String,
161+
decryption_settings: &DecryptionSettings,
162+
) -> Result<(), crate::CryptoStoreError> {
158163
let events: Vec<Raw<AnyToDeviceEvent>> = serde_json::from_str(&events)?;
159-
self.runtime.block_on(self.inner.receive_events(events))?;
164+
self.runtime.block_on(self.inner.receive_events(events, decryption_settings))?;
160165

161166
Ok(())
162167
}

bindings/matrix-sdk-crypto-ffi/src/machine.rs

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -526,6 +526,7 @@ impl OlmMachine {
526526
key_counts: HashMap<String, i32>,
527527
unused_fallback_keys: Option<Vec<String>>,
528528
next_batch_token: String,
529+
decryption_settings: &DecryptionSettings,
529530
) -> Result<SyncChangesResult, CryptoStoreError> {
530531
let to_device: ToDevice = serde_json::from_str(&events)?;
531532
let device_changes: RumaDeviceLists = device_changes.into();
@@ -544,15 +545,17 @@ impl OlmMachine {
544545
let unused_fallback_keys: Option<Vec<OneTimeKeyAlgorithm>> =
545546
unused_fallback_keys.map(|u| u.into_iter().map(OneTimeKeyAlgorithm::from).collect());
546547

547-
let (to_device_events, room_key_infos) = self.runtime.block_on(
548-
self.inner.receive_sync_changes(matrix_sdk_crypto::EncryptionSyncChanges {
549-
to_device_events: to_device.events,
550-
changed_devices: &device_changes,
551-
one_time_keys_counts: &key_counts,
552-
unused_fallback_keys: unused_fallback_keys.as_deref(),
553-
next_batch_token: Some(next_batch_token),
554-
}),
555-
)?;
548+
let (to_device_events, room_key_infos) =
549+
self.runtime.block_on(self.inner.receive_sync_changes(
550+
matrix_sdk_crypto::EncryptionSyncChanges {
551+
to_device_events: to_device.events,
552+
changed_devices: &device_changes,
553+
one_time_keys_counts: &key_counts,
554+
unused_fallback_keys: unused_fallback_keys.as_deref(),
555+
next_batch_token: Some(next_batch_token),
556+
},
557+
decryption_settings,
558+
))?;
556559

557560
let to_device_events = to_device_events
558561
.into_iter()

crates/matrix-sdk-base/src/client.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -500,7 +500,12 @@ impl BaseClient {
500500
let processors::e2ee::to_device::Output {
501501
processed_to_device_events: to_device,
502502
room_key_updates,
503-
} = processors::e2ee::to_device::from_sync_v2(&response, olm_machine.as_ref()).await?;
503+
} = processors::e2ee::to_device::from_sync_v2(
504+
&response,
505+
olm_machine.as_ref(),
506+
&self.decryption_settings,
507+
)
508+
.await?;
504509

505510
processors::latest_event::decrypt_from_rooms(
506511
&mut context,

crates/matrix-sdk-base/src/response_processors/e2ee/to_device.rs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@
1515
use std::collections::BTreeMap;
1616

1717
use matrix_sdk_common::deserialized_responses::ProcessedToDeviceEvent;
18-
use matrix_sdk_crypto::{store::types::RoomKeyInfo, EncryptionSyncChanges, OlmMachine};
18+
use matrix_sdk_crypto::{
19+
store::types::RoomKeyInfo, DecryptionSettings, EncryptionSyncChanges, OlmMachine,
20+
};
1921
use ruma::{
2022
api::client::sync::sync_events::{v3, v5, DeviceLists},
2123
events::AnyToDeviceEvent,
@@ -34,6 +36,7 @@ pub async fn from_msc4186(
3436
to_device: Option<&v5::response::ToDevice>,
3537
e2ee: &v5::response::E2EE,
3638
olm_machine: Option<&OlmMachine>,
39+
decryption_settings: &DecryptionSettings,
3740
) -> Result<Output> {
3841
process(
3942
olm_machine,
@@ -42,6 +45,7 @@ pub async fn from_msc4186(
4245
&e2ee.device_one_time_keys_count,
4346
e2ee.device_unused_fallback_key_types.as_deref(),
4447
to_device.as_ref().map(|to_device| to_device.next_batch.clone()),
48+
decryption_settings,
4549
)
4650
.await
4751
}
@@ -54,6 +58,7 @@ pub async fn from_msc4186(
5458
pub async fn from_sync_v2(
5559
response: &v3::Response,
5660
olm_machine: Option<&OlmMachine>,
61+
decryption_settings: &DecryptionSettings,
5762
) -> Result<Output> {
5863
process(
5964
olm_machine,
@@ -62,6 +67,7 @@ pub async fn from_sync_v2(
6267
&response.device_one_time_keys_count,
6368
response.device_unused_fallback_key_types.as_deref(),
6469
Some(response.next_batch.clone()),
70+
decryption_settings,
6571
)
6672
.await
6773
}
@@ -77,6 +83,7 @@ async fn process(
7783
one_time_keys_counts: &BTreeMap<OneTimeKeyAlgorithm, UInt>,
7884
unused_fallback_keys: Option<&[OneTimeKeyAlgorithm]>,
7985
next_batch_token: Option<String>,
86+
decryption_settings: &DecryptionSettings,
8087
) -> Result<Output> {
8188
let encryption_sync_changes = EncryptionSyncChanges {
8289
to_device_events,
@@ -92,7 +99,7 @@ async fn process(
9299
// This makes sure that we have the decryption keys for the room
93100
// events at hand.
94101
let (events, room_key_updates) =
95-
olm_machine.receive_sync_changes(encryption_sync_changes).await?;
102+
olm_machine.receive_sync_changes(encryption_sync_changes, decryption_settings).await?;
96103

97104
Output { processed_to_device_events: events, room_key_updates: Some(room_key_updates) }
98105
} else {

crates/matrix-sdk-base/src/sliding_sync.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,13 @@ impl BaseClient {
6363
let mut context = processors::Context::default();
6464

6565
let processors::e2ee::to_device::Output { processed_to_device_events, room_key_updates } =
66-
processors::e2ee::to_device::from_msc4186(to_device, e2ee, olm_machine.as_ref())
67-
.await?;
66+
processors::e2ee::to_device::from_msc4186(
67+
to_device,
68+
e2ee,
69+
olm_machine.as_ref(),
70+
&self.decryption_settings,
71+
)
72+
.await?;
6873

6974
processors::latest_event::decrypt_from_rooms(
7075
&mut context,

crates/matrix-sdk-crypto/README.md

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,10 @@ The state machine works in a push/pull manner:
1717
```rust,no_run
1818
use std::collections::BTreeMap;
1919
20-
use matrix_sdk_crypto::{EncryptionSyncChanges, OlmMachine, OlmError};
21-
use ruma::{
22-
api::client::sync::sync_events::{v3::ToDevice, DeviceLists},
23-
device_id, user_id,
20+
use matrix_sdk_crypto::{
21+
DecryptionSettings, EncryptionSyncChanges, OlmError, OlmMachine, TrustRequirement,
2422
};
23+
use ruma::{api::client::sync::sync_events::DeviceLists, device_id, user_id};
2524
2625
#[tokio::main]
2726
async fn main() -> Result<(), OlmError> {
@@ -33,19 +32,27 @@ async fn main() -> Result<(), OlmError> {
3332
let unused_fallback_keys = Some(Vec::new());
3433
let next_batch_token = "T0K3N".to_owned();
3534
35+
let decryption_settings =
36+
DecryptionSettings { sender_device_trust_requirement: TrustRequirement::Untrusted };
37+
3638
// Push changes that the server sent to us in a sync response.
37-
let decrypted_to_device = machine.receive_sync_changes(EncryptionSyncChanges {
38-
to_device_events: vec![],
39-
changed_devices: &changed_devices,
40-
one_time_keys_counts: &one_time_key_counts,
41-
unused_fallback_keys: unused_fallback_keys.as_deref(),
42-
next_batch_token: Some(next_batch_token),
43-
}).await?;
39+
let decrypted_to_device = machine
40+
.receive_sync_changes(
41+
EncryptionSyncChanges {
42+
to_device_events: vec![],
43+
changed_devices: &changed_devices,
44+
one_time_keys_counts: &one_time_key_counts,
45+
unused_fallback_keys: unused_fallback_keys.as_deref(),
46+
next_batch_token: Some(next_batch_token),
47+
},
48+
&decryption_settings,
49+
)
50+
.await?;
4451
4552
// Pull requests that we need to send out.
4653
let outgoing_requests = machine.outgoing_requests().await?;
4754
48-
// Send the requests here out and call machine.mark_request_as_sent().
55+
// Send the requests out here and call machine.mark_request_as_sent().
4956
5057
Ok(())
5158
}

crates/matrix-sdk-crypto/src/dehydrated_devices.rs

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,8 @@ use crate::{
6060
CryptoStoreWrapper, MemoryStore, Store,
6161
},
6262
verification::VerificationMachine,
63-
Account, CryptoStoreError, EncryptionSyncChanges, OlmError, OlmMachine, SignatureError,
63+
Account, CryptoStoreError, DecryptionSettings, EncryptionSyncChanges, OlmError, OlmMachine,
64+
SignatureError,
6465
};
6566

6667
/// Error type for device dehydration issues.
@@ -215,7 +216,9 @@ impl RehydratedDevice {
215216
///
216217
/// ```no_run
217218
/// # use anyhow::Result;
218-
/// # use matrix_sdk_crypto::{ OlmMachine, store::types::DehydratedDeviceKey };
219+
/// # use matrix_sdk_crypto::{
220+
/// DecryptionSettings, OlmMachine, TrustRequirement, store::types::DehydratedDeviceKey
221+
/// };
219222
/// # use ruma::{api::client::dehydrated_device, DeviceId};
220223
/// # async fn example() -> Result<()> {
221224
/// # let machine: OlmMachine = unimplemented!();
@@ -245,6 +248,9 @@ impl RehydratedDevice {
245248
///
246249
/// let mut since_token = None;
247250
/// let mut imported_room_keys = 0;
251+
/// let decryption_settings = DecryptionSettings {
252+
/// sender_device_trust_requirement: TrustRequirement::Untrusted
253+
/// };
248254
///
249255
/// loop {
250256
/// let response =
@@ -255,7 +261,7 @@ impl RehydratedDevice {
255261
/// }
256262
///
257263
/// since_token = response.next_batch.as_deref();
258-
/// imported_room_keys += rehydrated.receive_events(response.events).await?.len();
264+
/// imported_room_keys += rehydrated.receive_events(response.events, &decryption_settings).await?.len();
259265
/// }
260266
///
261267
/// println!("Successfully imported {imported_room_keys} from the dehydrated device.");
@@ -273,6 +279,7 @@ impl RehydratedDevice {
273279
pub async fn receive_events(
274280
&self,
275281
events: Vec<Raw<AnyToDeviceEvent>>,
282+
decryption_settings: &DecryptionSettings,
276283
) -> Result<Vec<RoomKeyInfo>, OlmError> {
277284
trace!("Receiving events for a rehydrated Device");
278285

@@ -290,7 +297,7 @@ impl RehydratedDevice {
290297

291298
let (_, changes) = self
292299
.rehydrated
293-
.preprocess_sync_changes(&mut rehydrated_transaction, sync_changes)
300+
.preprocess_sync_changes(&mut rehydrated_transaction, sync_changes, decryption_settings)
294301
.await?;
295302

296303
// Now take the room keys and persist them in our original `OlmMachine`.
@@ -423,7 +430,7 @@ mod tests {
423430
store::types::DehydratedDeviceKey,
424431
types::{events::ToDeviceEvent, DeviceKeys as DeviceKeysType},
425432
utilities::json_convert,
426-
EncryptionSettings, OlmMachine,
433+
DecryptionSettings, EncryptionSettings, OlmMachine, TrustRequirement,
427434
};
428435

429436
fn pickle_key() -> DehydratedDeviceKey {
@@ -568,9 +575,12 @@ mod tests {
568575
assert_eq!(rehydrated.rehydrated.device_id(), request.device_id);
569576
assert_eq!(rehydrated.original.device_id(), alice.device_id());
570577

578+
let decryption_settings =
579+
DecryptionSettings { sender_device_trust_requirement: TrustRequirement::Untrusted };
580+
571581
// Push the to-device event containing the room key into the rehydrated device.
572582
let ret = rehydrated
573-
.receive_events(vec![event])
583+
.receive_events(vec![event], &decryption_settings)
574584
.await
575585
.expect("We should be able to push to-device events into the rehydrated device");
576586

@@ -680,9 +690,12 @@ mod tests {
680690
assert_eq!(rehydrated.rehydrated.device_id(), &device_id);
681691
assert_eq!(rehydrated.original.device_id(), alice.device_id());
682692

693+
let decryption_settings =
694+
DecryptionSettings { sender_device_trust_requirement: TrustRequirement::Untrusted };
695+
683696
// Push the to-device event containing the room key into the rehydrated device.
684697
let ret = rehydrated
685-
.receive_events(vec![event])
698+
.receive_events(vec![event], &decryption_settings)
686699
.await
687700
.expect("We should be able to push to-device events into the rehydrated device");
688701

crates/matrix-sdk-crypto/src/gossiping/machine.rs

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1142,6 +1142,7 @@ mod tests {
11421142
EncryptedEvent, EncryptedToDeviceEvent, RoomEncryptedEventContent,
11431143
},
11441144
verification::VerificationMachine,
1145+
DecryptionSettings, TrustRequirement,
11451146
};
11461147

11471148
fn alice_id() -> &'static UserId {
@@ -2051,14 +2052,20 @@ mod tests {
20512052
let stream = bob_machine.store().secrets_stream();
20522053
pin_mut!(stream);
20532054

2055+
let decryption_settings =
2056+
DecryptionSettings { sender_device_trust_requirement: TrustRequirement::Untrusted };
2057+
20542058
bob_machine
2055-
.receive_sync_changes(EncryptionSyncChanges {
2056-
to_device_events: vec![event],
2057-
changed_devices: &Default::default(),
2058-
one_time_keys_counts: &Default::default(),
2059-
unused_fallback_keys: None,
2060-
next_batch_token: None,
2061-
})
2059+
.receive_sync_changes(
2060+
EncryptionSyncChanges {
2061+
to_device_events: vec![event],
2062+
changed_devices: &Default::default(),
2063+
one_time_keys_counts: &Default::default(),
2064+
unused_fallback_keys: None,
2065+
next_batch_token: None,
2066+
},
2067+
&decryption_settings,
2068+
)
20622069
.await
20632070
.unwrap();
20642071

crates/matrix-sdk-crypto/src/lib.rs

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -590,7 +590,9 @@ pub enum RoomEventDecryptionResult {
590590
///
591591
/// ```no_run
592592
/// # use anyhow::Result;
593-
/// # use matrix_sdk_crypto::{EncryptionSyncChanges, OlmMachine};
593+
/// # use matrix_sdk_crypto::{
594+
/// DecryptionSettings, EncryptionSyncChanges, OlmMachine, TrustRequirement
595+
/// };
594596
/// # use ruma::api::client::sync::sync_events::v3::Response;
595597
/// # #[tokio::main]
596598
/// # async fn main() -> Result<()> {
@@ -617,11 +619,15 @@ pub enum RoomEventDecryptionResult {
617619
/// next_batch_token: Some(response.next_batch),
618620
/// };
619621
///
622+
/// let decryption_settings = DecryptionSettings {
623+
/// sender_device_trust_requirement: TrustRequirement::Untrusted
624+
/// };
625+
///
620626
/// // Push the sync changes into the OlmMachine, make sure that this is
621627
/// // happening before the `next_batch` token of the sync is persisted.
622628
/// let to_device_events = client
623629
/// .olm_machine
624-
/// .receive_sync_changes(sync_changes)
630+
/// .receive_sync_changes(sync_changes, &decryption_settings)
625631
/// .await?;
626632
///
627633
/// // Send the outgoing requests out that the sync changes produced.
@@ -768,7 +774,9 @@ pub enum RoomEventDecryptionResult {
768774
/// ```no_run
769775
/// # use anyhow::Result;
770776
/// # use std::ops::Deref;
771-
/// # use matrix_sdk_crypto::{EncryptionSyncChanges, OlmMachine};
777+
/// # use matrix_sdk_crypto::{
778+
/// # DecryptionSettings, EncryptionSyncChanges, OlmMachine, TrustRequirement
779+
/// # };
772780
/// # use ruma::api::client::sync::sync_events::v3::{Response, JoinedRoom};
773781
/// # use ruma::{OwnedUserId, serde::Raw, events::AnySyncStateEvent};
774782
/// # #[tokio::main]
@@ -805,11 +813,15 @@ pub enum RoomEventDecryptionResult {
805813
/// next_batch_token: Some(response.next_batch),
806814
/// };
807815
///
816+
/// let decryption_settings = DecryptionSettings {
817+
/// sender_device_trust_requirement: TrustRequirement::Untrusted
818+
/// };
819+
///
808820
/// // Push the sync changes into the OlmMachine, make sure that this is
809821
/// // happening before the `next_batch` token of the sync is persisted.
810822
/// let to_device_events = client
811823
/// .olm_machine
812-
/// .receive_sync_changes(sync_changes)
824+
/// .receive_sync_changes(sync_changes, &decryption_settings)
813825
/// .await?;
814826
///
815827
/// // Send the outgoing requests out that the sync changes produced.

0 commit comments

Comments
 (0)