-
Notifications
You must be signed in to change notification settings - Fork 397
Expand file tree
/
Copy pathmod.rs
More file actions
2648 lines (2357 loc) · 99.7 KB
/
mod.rs
File metadata and controls
2648 lines (2357 loc) · 99.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 The Matrix.org Foundation C.I.C.
// Copyright 2021 Damir Jelić
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![doc = include_str!("../docs/encryption.md")]
#![cfg_attr(target_family = "wasm", allow(unused_imports))]
#[cfg(feature = "experimental-send-custom-to-device")]
use std::ops::Deref;
use std::{
collections::{BTreeMap, HashSet},
io::{Cursor, Read, Write},
iter,
path::{Path, PathBuf},
str::FromStr,
sync::Arc,
};
use eyeball::{SharedObservable, Subscriber};
use futures_core::Stream;
use futures_util::{
future::try_join,
stream::{self, StreamExt},
};
#[cfg(feature = "experimental-send-custom-to-device")]
use matrix_sdk_base::crypto::CollectStrategy;
use matrix_sdk_base::{
StateStoreDataKey, StateStoreDataValue,
cross_process_lock::CrossProcessLockError,
crypto::{
CrossSigningBootstrapRequests, OlmMachine,
store::{
SecretImportError,
types::{RoomKeyBundleInfo, RoomKeyInfo},
},
types::{
SecretsBundle, SignedKey,
requests::{
OutgoingRequest, OutgoingVerificationRequest, RoomMessageRequest, ToDeviceRequest,
},
},
},
};
use matrix_sdk_common::{executor::spawn, locks::Mutex as StdMutex};
use ruma::{
DeviceId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, TransactionId, UserId,
api::client::{
error::{ErrorBody, StandardErrorBody},
keys::{
get_keys, upload_keys, upload_signatures::v3::Request as UploadSignaturesRequest,
upload_signing_keys::v3::Request as UploadSigningKeysRequest,
},
message::send_message_event,
to_device::send_event_to_device::v3::{
Request as RumaToDeviceRequest, Response as ToDeviceResponse,
},
uiaa::{AuthData, AuthType, OAuthParams, UiaaInfo},
},
assign,
events::room::{MediaSource, ThumbnailInfo},
};
#[cfg(feature = "experimental-send-custom-to-device")]
use ruma::{events::AnyToDeviceEventContent, serde::Raw, to_device::DeviceIdOrAllDevices};
use serde::{Deserialize, de::Error as _};
use tasks::BundleReceiverTask;
use tokio::sync::{Mutex, RwLockReadGuard};
use tokio_stream::wrappers::errors::BroadcastStreamRecvError;
use tracing::{debug, error, instrument, warn};
use url::Url;
use vodozemac::Curve25519PublicKey;
use self::{
backups::{Backups, types::BackupClientState},
futures::UploadEncryptedFile,
identities::{Device, DeviceUpdates, IdentityUpdates, UserDevices, UserIdentity},
recovery::{Recovery, RecoveryState},
secret_storage::SecretStorage,
tasks::{BackupDownloadTask, BackupUploadingTask, ClientTasks},
verification::{SasVerification, Verification, VerificationRequest},
};
use crate::{
Client, Error, HttpError, Result, RumaApiError, TransmissionProgress,
attachment::Thumbnail,
client::{ClientInner, WeakClient},
cross_process_lock::CrossProcessLockGuard,
error::HttpResult,
};
pub mod backups;
pub mod futures;
pub mod identities;
pub mod recovery;
pub mod secret_storage;
pub(crate) mod tasks;
pub mod verification;
pub use matrix_sdk_base::crypto::{
CrossSigningStatus, CryptoStoreError, DecryptorError, EventError, KeyExportError, LocalTrust,
MediaEncryptionInfo, MegolmError, OlmError, RoomKeyImportResult, SessionCreationError,
SignatureError, VERSION,
olm::{
SessionCreationError as MegolmSessionCreationError,
SessionExportError as OlmSessionExportError,
},
vodozemac,
};
use matrix_sdk_common::cross_process_lock::CrossProcessLockConfig;
#[cfg(feature = "experimental-send-custom-to-device")]
use crate::config::RequestConfig;
pub use crate::error::RoomKeyImportError;
/// Error type describinfg failures that can happen while exporting a
/// [`SecretsBundle`] from a SQLite store.
#[cfg(feature = "sqlite")]
#[derive(Debug, thiserror::Error)]
pub enum BundleExportError {
/// The SQLite store couldn't be opened.
#[error(transparent)]
OpenStoreError(#[from] matrix_sdk_sqlite::OpenStoreError),
/// Data from the SQLite store coulnd't be exported.
#[error(transparent)]
StoreError(#[from] CryptoStoreError),
/// The store doesn't contain a secrets bundle or it couldn't be read from
/// the store.
#[error(transparent)]
SecretExport(#[from] matrix_sdk_base::crypto::store::SecretsBundleExportError),
}
/// Error type describinfg failures that can happen while importing a
/// [`SecretsBundle`].
#[derive(Debug, thiserror::Error)]
pub enum BundleImportError {
/// The bundle coulnd't be imported.
#[error(transparent)]
SecretImport(#[from] SecretImportError),
/// The cross-signed device keys coulnd't been uploaded.
#[error(transparent)]
DeviceKeys(#[from] Error),
}
/// Attempt to export a [`SecretsBundle`] from a crypto store.
///
/// This method can be used to retrieve a [`SecretsBundle`] from an existing
/// `matrix-sdk`-based client in order to import the [`SecretsBundle`] in
/// another [`Client`] instance.
///
/// This can be useful for migration purposes or to allow existing client
/// instances create new ones that will be fully verified.
#[cfg(feature = "sqlite")]
pub async fn export_secrets_bundle_from_store(
database_path: impl AsRef<Path>,
passphrase: Option<&str>,
) -> std::result::Result<Option<(OwnedUserId, SecretsBundle)>, BundleExportError> {
use matrix_sdk_base::crypto::store::CryptoStore;
let store = matrix_sdk_sqlite::SqliteCryptoStore::open(database_path, passphrase).await?;
let account =
store.load_account().await.map_err(|e| BundleExportError::StoreError(e.into()))?;
if let Some(account) = account {
let machine = OlmMachine::with_store(&account.user_id, &account.device_id, store, None)
.await
.map_err(BundleExportError::StoreError)?;
let bundle = machine.store().export_secrets_bundle().await?;
Ok(Some((account.user_id.to_owned(), bundle)))
} else {
Ok(None)
}
}
/// All the data related to the encryption state.
pub(crate) struct EncryptionData {
/// Background tasks related to encryption (key backup, initialization
/// tasks, etc.).
pub tasks: StdMutex<ClientTasks>,
/// End-to-end encryption settings.
pub encryption_settings: EncryptionSettings,
/// All state related to key backup.
pub backup_state: BackupClientState,
/// All state related to secret storage recovery.
pub recovery_state: SharedObservable<RecoveryState>,
}
impl EncryptionData {
pub fn new(encryption_settings: EncryptionSettings) -> Self {
Self {
encryption_settings,
tasks: StdMutex::new(Default::default()),
backup_state: Default::default(),
recovery_state: Default::default(),
}
}
pub fn initialize_tasks(&self, client: &Arc<ClientInner>) {
let weak_client = WeakClient::from_inner(client);
let mut tasks = self.tasks.lock();
tasks.upload_room_keys = Some(BackupUploadingTask::new(weak_client.clone()));
if self.encryption_settings.backup_download_strategy
== BackupDownloadStrategy::AfterDecryptionFailure
{
tasks.download_room_keys = Some(BackupDownloadTask::new(weak_client));
}
}
/// Initialize the background task which listens for changes in the
/// [`backups::BackupState`] and updataes the [`recovery::RecoveryState`].
///
/// This should happen after the usual tasks have been set up and after the
/// E2EE initialization tasks have been set up.
pub fn initialize_recovery_state_update_task(&self, client: &Client) {
let mut guard = self.tasks.lock();
let future = Recovery::update_state_after_backup_state_change(client);
let join_handle = spawn(future);
guard.update_recovery_state_after_backup = Some(join_handle);
}
}
/// Settings for end-to-end encryption features.
#[derive(Clone, Copy, Debug, Default)]
pub struct EncryptionSettings {
/// Automatically bootstrap cross-signing for a user once they're logged, in
/// case it's not already done yet.
///
/// This requires to login with a username and password, or that MSC3967 is
/// enabled on the server, as of 2023-10-20.
pub auto_enable_cross_signing: bool,
/// Select a strategy to download room keys from the backup, by default room
/// keys won't be downloaded from the backup automatically.
///
/// Take a look at the [`BackupDownloadStrategy`] enum for more options.
pub backup_download_strategy: BackupDownloadStrategy,
/// Automatically create a backup version if no backup exists.
pub auto_enable_backups: bool,
}
/// Settings for end-to-end encryption features.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
pub enum BackupDownloadStrategy {
/// Automatically download all room keys from the backup when the backup
/// recovery key has been received. The backup recovery key can be received
/// in two ways:
///
/// 1. Received as a `m.secret.send` to-device event, after a successful
/// interactive verification.
/// 2. Imported from secret storage (4S) using the
/// [`SecretStore::import_secrets()`] method.
///
/// [`SecretStore::import_secrets()`]: crate::encryption::secret_storage::SecretStore::import_secrets
OneShot,
/// Attempt to download a single room key if an event fails to be decrypted.
AfterDecryptionFailure,
/// Don't download any room keys automatically. The user can manually
/// download room keys using the [`Backups::download_room_key()`] methods.
///
/// This is the default option.
#[default]
Manual,
}
/// The verification state of our own device
///
/// This enum tells us if our own user identity trusts these devices, in other
/// words it tells us if the user identity has signed the device.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VerificationState {
/// The verification state is unknown for now.
Unknown,
/// The device is considered to be verified, it has been signed by its user
/// identity.
Verified,
/// The device is unverified.
Unverified,
}
/// Wraps together a `CrossProcessLockStoreGuard` and a generation number.
#[derive(Debug)]
pub struct CrossProcessLockStoreGuardWithGeneration {
_guard: CrossProcessLockGuard,
generation: u64,
}
impl CrossProcessLockStoreGuardWithGeneration {
/// Return the Crypto Store generation associated with this store lock.
pub fn generation(&self) -> u64 {
self.generation
}
}
/// A stateful struct remembering the cross-signing keys we need to upload.
///
/// Since the `/_matrix/client/v3/keys/device_signing/upload` might require
/// additional authentication, this struct will contain information on the type
/// of authentication the user needs to complete before the upload might be
/// continued.
///
/// More info can be found in the [spec].
///
/// [spec]: https://spec.matrix.org/v1.11/client-server-api/#post_matrixclientv3keysdevice_signingupload
#[derive(Debug)]
pub struct CrossSigningResetHandle {
client: Client,
upload_request: UploadSigningKeysRequest,
signatures_request: UploadSignaturesRequest,
auth_type: CrossSigningResetAuthType,
is_cancelled: Mutex<bool>,
}
impl CrossSigningResetHandle {
/// Set up a new `CrossSigningResetHandle`.
pub fn new(
client: Client,
upload_request: UploadSigningKeysRequest,
signatures_request: UploadSignaturesRequest,
auth_type: CrossSigningResetAuthType,
) -> Self {
Self {
client,
upload_request,
signatures_request,
auth_type,
is_cancelled: Mutex::new(false),
}
}
/// Get the [`CrossSigningResetAuthType`] this cross-signing reset process
/// is using.
pub fn auth_type(&self) -> &CrossSigningResetAuthType {
&self.auth_type
}
/// Continue the cross-signing reset by either waiting for the
/// authentication to be done on the side of the OAuth 2.0 server or by
/// providing additional [`AuthData`] the homeserver requires.
pub async fn auth(&self, auth: Option<AuthData>) -> Result<()> {
let mut upload_request = self.upload_request.clone();
upload_request.auth = auth;
while let Err(e) = self.client.send(upload_request.clone()).await {
if *self.is_cancelled.lock().await {
return Ok(());
}
match e.as_uiaa_response() {
Some(uiaa_info) => {
if uiaa_info.auth_error.is_some() {
return Err(e.into());
}
}
None => return Err(e.into()),
}
}
self.client.send(self.signatures_request.clone()).await?;
Ok(())
}
/// Cancel the ongoing identity reset process
pub async fn cancel(&self) {
*self.is_cancelled.lock().await = true;
}
}
/// information about the additional authentication that is required before the
/// cross-signing keys can be uploaded.
#[derive(Debug, Clone)]
pub enum CrossSigningResetAuthType {
/// The homeserver requires user-interactive authentication.
Uiaa(UiaaInfo),
/// OAuth 2.0 is used for authentication and the user needs to open a URL to
/// approve the upload of cross-signing keys.
OAuth(OAuthCrossSigningResetInfo),
}
impl CrossSigningResetAuthType {
fn new(error: &HttpError) -> Result<Option<Self>> {
if let Some(auth_info) = error.as_uiaa_response() {
if let Ok(Some(auth_info)) = OAuthCrossSigningResetInfo::from_auth_info(auth_info) {
Ok(Some(CrossSigningResetAuthType::OAuth(auth_info)))
} else {
Ok(Some(CrossSigningResetAuthType::Uiaa(auth_info.clone())))
}
} else {
Ok(None)
}
}
}
/// OAuth 2.0 specific information about the required authentication for the
/// upload of cross-signing keys.
#[derive(Debug, Clone, Deserialize)]
pub struct OAuthCrossSigningResetInfo {
/// The URL where the user can approve the reset of the cross-signing keys.
pub approval_url: Url,
}
impl OAuthCrossSigningResetInfo {
fn from_auth_info(auth_info: &UiaaInfo) -> Result<Option<Self>> {
let Some(parameters) = auth_info.params::<OAuthParams>(&AuthType::OAuth)? else {
return Ok(None);
};
Ok(Some(OAuthCrossSigningResetInfo { approval_url: parameters.url.as_str().try_into()? }))
}
}
/// A struct that helps to parse the custom error message Synapse posts if a
/// duplicate one-time key is uploaded.
#[derive(Clone, Debug)]
pub struct DuplicateOneTimeKeyErrorMessage {
/// The previously uploaded one-time key.
pub old_key: Curve25519PublicKey,
/// The one-time key we're attempting to upload right now.
pub new_key: Curve25519PublicKey,
}
impl FromStr for DuplicateOneTimeKeyErrorMessage {
type Err = serde_json::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
// First we split the string into two parts, the part containing the old key and
// the part containing the new key. The parts are conveniently separated
// by a `;` character.
let mut split = s.split_terminator(';');
let old_key = split
.next()
.ok_or(serde_json::Error::custom("Old key is missing in the error message"))?;
let new_key = split
.next()
.ok_or(serde_json::Error::custom("New key is missing in the error message"))?;
// Now we remove the lengthy prefix from the part containing the old key, we
// should be left with just the JSON of the signed key.
let old_key_index = old_key
.find("Old key:")
.ok_or(serde_json::Error::custom("Old key is missing the prefix"))?;
let old_key = old_key[old_key_index..]
.trim()
.strip_prefix("Old key:")
.ok_or(serde_json::Error::custom("Old key is missing the prefix"))?;
// The part containing the new key is much simpler, we just remove a static
// prefix.
let new_key = new_key
.trim()
.strip_prefix("new key:")
.ok_or(serde_json::Error::custom("New key is missing the prefix"))?;
// The JSON containing the new key is for some reason quoted using single
// quotes, so let's replace them with normal double quotes.
let new_key = new_key.replace("'", "\"");
// Let's deserialize now.
let old_key: SignedKey = serde_json::from_str(old_key)?;
let new_key: SignedKey = serde_json::from_str(&new_key)?;
// Pick out the Curve keys, we don't care about the rest that much.
let old_key = old_key.key();
let new_key = new_key.key();
Ok(Self { old_key, new_key })
}
}
impl Client {
pub(crate) async fn olm_machine(&self) -> RwLockReadGuard<'_, Option<OlmMachine>> {
self.base_client().olm_machine().await
}
pub(crate) async fn mark_request_as_sent(
&self,
request_id: &TransactionId,
response: impl Into<matrix_sdk_base::crypto::types::requests::AnyIncomingResponse<'_>>,
) -> Result<(), matrix_sdk_base::Error> {
Ok(self
.olm_machine()
.await
.as_ref()
.expect(
"We should have an olm machine once we try to mark E2EE related requests as sent",
)
.mark_request_as_sent(request_id, response)
.await?)
}
/// Query the server for users device keys.
///
/// # Panics
///
/// Panics if no key query needs to be done.
#[instrument(skip(self, device_keys))]
pub(crate) async fn keys_query(
&self,
request_id: &TransactionId,
device_keys: BTreeMap<OwnedUserId, Vec<OwnedDeviceId>>,
) -> Result<get_keys::v3::Response> {
let request = assign!(get_keys::v3::Request::new(), { device_keys });
let response = self.send(request).await?;
self.mark_request_as_sent(request_id, &response).await?;
self.encryption().update_state_after_keys_query(&response).await;
Ok(response)
}
/// Construct a [`EncryptedFile`][ruma::events::room::EncryptedFile] by
/// encrypting and uploading a provided reader.
///
/// # Arguments
///
/// * `content_type` - The content type of the file.
/// * `reader` - The reader that should be encrypted and uploaded.
///
/// # Examples
///
/// ```no_run
/// # use matrix_sdk::Client;
/// # use url::Url;
/// # use matrix_sdk::ruma::{room_id, OwnedRoomId};
/// use serde::{Deserialize, Serialize};
/// use matrix_sdk::ruma::events::{macros::EventContent, room::EncryptedFile};
///
/// #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
/// #[ruma_event(type = "com.example.custom", kind = MessageLike)]
/// struct CustomEventContent {
/// encrypted_file: EncryptedFile,
/// }
///
/// # async {
/// # let homeserver = Url::parse("http://example.com")?;
/// # let client = Client::new(homeserver).await?;
/// # let room = client.get_room(&room_id!("!test:example.com")).unwrap();
/// let mut reader = std::io::Cursor::new(b"Hello, world!");
/// let encrypted_file = client.upload_encrypted_file(&mut reader).await?;
///
/// room.send(CustomEventContent { encrypted_file }).await?;
/// # anyhow::Ok(()) };
/// ```
pub fn upload_encrypted_file<'a, R: Read + ?Sized + 'a>(
&'a self,
reader: &'a mut R,
) -> UploadEncryptedFile<'a, R> {
UploadEncryptedFile::new(self, reader)
}
/// Encrypt and upload the file and thumbnails, and return the source
/// information.
pub(crate) async fn upload_encrypted_media_and_thumbnail(
&self,
data: &[u8],
thumbnail: Option<Thumbnail>,
send_progress: SharedObservable<TransmissionProgress>,
) -> Result<(MediaSource, Option<(MediaSource, Box<ThumbnailInfo>)>)> {
let upload_thumbnail = self.upload_encrypted_thumbnail(thumbnail, send_progress.clone());
let upload_attachment = async {
let mut cursor = Cursor::new(data);
self.upload_encrypted_file(&mut cursor)
.with_send_progress_observable(send_progress)
.await
};
let (thumbnail, file) = try_join(upload_thumbnail, upload_attachment).await?;
Ok((MediaSource::Encrypted(Box::new(file)), thumbnail))
}
/// Uploads an encrypted thumbnail to the media repository, and returns
/// its source and extra information.
async fn upload_encrypted_thumbnail(
&self,
thumbnail: Option<Thumbnail>,
send_progress: SharedObservable<TransmissionProgress>,
) -> Result<Option<(MediaSource, Box<ThumbnailInfo>)>> {
let Some(thumbnail) = thumbnail else {
return Ok(None);
};
let (data, _, thumbnail_info) = thumbnail.into_parts();
let mut cursor = Cursor::new(data);
let file = self
.upload_encrypted_file(&mut cursor)
.with_send_progress_observable(send_progress)
.await?;
Ok(Some((MediaSource::Encrypted(Box::new(file)), thumbnail_info)))
}
/// Claim one-time keys creating new Olm sessions.
///
/// # Arguments
///
/// * `users` - The list of user/device pairs that we should claim keys for.
pub(crate) async fn claim_one_time_keys(
&self,
users: impl Iterator<Item = &UserId>,
) -> Result<()> {
let _lock = self.locks().key_claim_lock.lock().await;
if let Some((request_id, request)) = self
.olm_machine()
.await
.as_ref()
.ok_or(Error::NoOlmMachine)?
.get_missing_sessions(users)
.await?
{
let response = self.send(request).await?;
self.mark_request_as_sent(&request_id, &response).await?;
}
Ok(())
}
/// Upload the E2E encryption keys.
///
/// This uploads the long lived device keys as well as the required amount
/// of one-time keys.
///
/// # Panics
///
/// Panics if the client isn't logged in, or if no encryption keys need to
/// be uploaded.
#[instrument(skip(self, request))]
pub(crate) async fn keys_upload(
&self,
request_id: &TransactionId,
request: &upload_keys::v3::Request,
) -> Result<upload_keys::v3::Response> {
debug!(
device_keys = request.device_keys.is_some(),
one_time_key_count = request.one_time_keys.len(),
"Uploading public encryption keys",
);
let response = self.send(request.clone()).await?;
self.mark_request_as_sent(request_id, &response).await?;
Ok(response)
}
pub(crate) async fn room_send_helper(
&self,
request: &RoomMessageRequest,
) -> Result<send_message_event::v3::Response> {
let content = request.content.clone();
let txn_id = request.txn_id.clone();
let room_id = &request.room_id;
self.get_room(room_id)
.expect("Can't send a message to a room that isn't known to the store")
.send(*content)
.with_transaction_id(txn_id)
.await
.map(|result| result.response)
}
pub(crate) async fn send_to_device(
&self,
request: &ToDeviceRequest,
) -> HttpResult<ToDeviceResponse> {
let request = RumaToDeviceRequest::new_raw(
request.event_type.clone(),
request.txn_id.clone(),
request.messages.clone(),
);
self.send(request).await
}
pub(crate) async fn send_verification_request(
&self,
request: OutgoingVerificationRequest,
) -> Result<()> {
use matrix_sdk_base::crypto::types::requests::OutgoingVerificationRequest::*;
match request {
ToDevice(t) => {
self.send_to_device(&t).await?;
}
InRoom(r) => {
self.room_send_helper(&r).await?;
}
}
Ok(())
}
async fn send_outgoing_request(&self, r: OutgoingRequest) -> Result<()> {
use matrix_sdk_base::crypto::types::requests::AnyOutgoingRequest;
match r.request() {
AnyOutgoingRequest::KeysQuery(request) => {
self.keys_query(r.request_id(), request.device_keys.clone()).await?;
}
AnyOutgoingRequest::KeysUpload(request) => {
let response = self.keys_upload(r.request_id(), request).await;
if let Err(e) = &response {
match e.as_ruma_api_error() {
Some(RumaApiError::ClientApi(e)) if e.status_code == 400 => {
if let ErrorBody::Standard(StandardErrorBody { message, .. }) = &e.body
{
// This is one of the nastiest errors we can have. The server
// telling us that we already have a one-time key uploaded means
// that we forgot about some of our one-time keys. This will lead to
// UTDs.
{
let already_reported = self
.state_store()
.get_kv_data(StateStoreDataKey::OneTimeKeyAlreadyUploaded)
.await?
.is_some();
if message.starts_with("One time key") && !already_reported {
let error_message =
DuplicateOneTimeKeyErrorMessage::from_str(message);
if let Ok(message) = &error_message {
error!(
sentry = true,
old_key = %message.old_key,
new_key = %message.new_key,
"Duplicate one-time keys have been uploaded"
);
} else {
error!(
sentry = true,
"Duplicate one-time keys have been uploaded"
);
}
self.state_store()
.set_kv_data(
StateStoreDataKey::OneTimeKeyAlreadyUploaded,
StateStoreDataValue::OneTimeKeyAlreadyUploaded,
)
.await?;
if let Err(e) = self
.inner
.duplicate_key_upload_error_sender
.send(error_message.ok())
{
error!(
"Failed to dispatch duplicate key upload error notification: {}",
e
);
}
}
}
}
}
_ => {}
}
response?;
}
}
AnyOutgoingRequest::ToDeviceRequest(request) => {
let response = self.send_to_device(request).await?;
self.mark_request_as_sent(r.request_id(), &response).await?;
}
AnyOutgoingRequest::SignatureUpload(request) => {
let response = self.send(request.clone()).await?;
self.mark_request_as_sent(r.request_id(), &response).await?;
}
AnyOutgoingRequest::RoomMessage(request) => {
let response = self.room_send_helper(request).await?;
self.mark_request_as_sent(r.request_id(), &response).await?;
}
AnyOutgoingRequest::KeysClaim(request) => {
let response = self.send(request.clone()).await?;
self.mark_request_as_sent(r.request_id(), &response).await?;
}
}
Ok(())
}
#[instrument(skip_all)]
pub(crate) async fn send_outgoing_requests(&self) -> Result<()> {
const MAX_CONCURRENT_REQUESTS: usize = 20;
// This is needed because sometimes we need to automatically
// claim some one-time keys to unwedge an existing Olm session.
if let Err(e) = self.claim_one_time_keys(iter::empty()).await {
warn!("Error while claiming one-time keys {:?}", e);
}
let outgoing_requests = stream::iter(
self.olm_machine()
.await
.as_ref()
.ok_or(Error::NoOlmMachine)?
.outgoing_requests()
.await?,
)
.map(|r| self.send_outgoing_request(r));
let requests = outgoing_requests.buffer_unordered(MAX_CONCURRENT_REQUESTS);
requests
.for_each(|r| async move {
match r {
Ok(_) => (),
Err(e) => warn!(error = ?e, "Error when sending out an outgoing E2EE request"),
}
})
.await;
Ok(())
}
}
#[cfg(any(feature = "testing", test))]
impl Client {
/// Get the olm machine, for testing purposes only.
pub async fn olm_machine_for_testing(&self) -> RwLockReadGuard<'_, Option<OlmMachine>> {
self.olm_machine().await
}
/// Aborts the client's bundle receiver task, for testing purposes only.
pub fn abort_bundle_receiver_task(&self) {
let tasks = self.inner.e2ee.tasks.lock();
if let Some(task) = tasks.receive_historic_room_key_bundles.as_ref() {
task.abort()
}
}
}
/// A high-level API to manage the client's encryption.
///
/// To get this, use [`Client::encryption()`].
#[derive(Debug, Clone)]
pub struct Encryption {
/// The underlying client.
client: Client,
}
impl Encryption {
pub(crate) fn new(client: Client) -> Self {
Self { client }
}
/// Returns the current encryption settings for this client.
pub(crate) fn settings(&self) -> EncryptionSettings {
self.client.inner.e2ee.encryption_settings
}
/// Get the public ed25519 key of our own device. This is usually what is
/// called the fingerprint of the device.
pub async fn ed25519_key(&self) -> Option<String> {
self.client.olm_machine().await.as_ref().map(|o| o.identity_keys().ed25519.to_base64())
}
/// Get the public Curve25519 key of our own device.
pub async fn curve25519_key(&self) -> Option<Curve25519PublicKey> {
self.client.olm_machine().await.as_ref().map(|o| o.identity_keys().curve25519)
}
/// Get the current device creation timestamp.
pub async fn device_creation_timestamp(&self) -> MilliSecondsSinceUnixEpoch {
match self.get_own_device().await {
Ok(Some(device)) => device.first_time_seen_ts(),
// Should not happen, there should always be an own device
_ => MilliSecondsSinceUnixEpoch::now(),
}
}
/// This method will import all the private cross-signing keys and, if
/// available, the private part of a backup key and its accompanying
/// version into the store.
///
/// Importing all the secrets will mark the device as verified and enable
/// backups if a backup key was available in the bundle.
///
/// **Warning**: Only import this from a trusted source, i.e. if an existing
/// device is sharing this with a new device.
///
/// **Warning*: Only call this method before right after logging in and
/// before the initial sync has been started.
pub async fn import_secrets_bundle(
&self,
bundle: &SecretsBundle,
) -> Result<(), BundleImportError> {
self.import_secrets_bundle_impl(bundle).await?;
// Upload the device keys, this will ensure that other devices see us as a fully
// verified device as soon as this method returns.
self.ensure_device_keys_upload().await?;
self.wait_for_e2ee_initialization_tasks().await;
Ok(())
}
pub(crate) async fn import_secrets_bundle_impl(
&self,
bundle: &SecretsBundle,
) -> Result<(), SecretImportError> {
let olm_machine = self.client.olm_machine().await;
let olm_machine =
olm_machine.as_ref().expect("This should only be called once we have an OlmMachine");
olm_machine.store().import_secrets_bundle(bundle).await
}
/// Get the status of the private cross signing keys.
///
/// This can be used to check which private cross signing keys we have
/// stored locally.
pub async fn cross_signing_status(&self) -> Option<CrossSigningStatus> {
let olm = self.client.olm_machine().await;
let machine = olm.as_ref()?;
Some(machine.cross_signing_status().await)
}
/// Does the user have other devices that the current device can verify
/// against?
///
/// The device must be signed by the user's cross-signing key, must have an
/// identity, and must not be a dehydrated device.
pub async fn has_devices_to_verify_against(&self) -> Result<bool> {
let olm_machine = self.client.olm_machine().await;
let olm_machine = olm_machine.as_ref().ok_or(Error::NoOlmMachine)?;
let user_id = olm_machine.user_id();
self.ensure_initial_key_query().await?;
let devices = self.get_user_devices(user_id).await?;
let ret = devices.devices().any(|device| {
device.is_cross_signed_by_owner()
&& device.curve25519_key().is_some()
&& !device.is_dehydrated()
});
Ok(ret)
}
/// Get all the tracked users we know about
///
/// Tracked users are users for which we keep the device list of E2EE
/// capable devices up to date.
pub async fn tracked_users(&self) -> Result<HashSet<OwnedUserId>, CryptoStoreError> {
if let Some(machine) = self.client.olm_machine().await.as_ref() {
machine.tracked_users().await
} else {
Ok(HashSet::new())
}
}
/// Get a [`Subscriber`] for the [`VerificationState`].
///
/// # Examples
///
/// ```no_run
/// use matrix_sdk::{Client, encryption};
/// use url::Url;
///
/// # async {
/// let homeserver = Url::parse("http://example.com")?;
/// let client = Client::new(homeserver).await?;
/// let mut subscriber = client.encryption().verification_state();
///
/// let current_value = subscriber.get();
///
/// println!("The current verification state is: {current_value:?}");
///
/// if let Some(verification_state) = subscriber.next().await {