Skip to main content

matrix_sdk_crypto/
lib.rs

1// Copyright 2020 The Matrix.org Foundation C.I.C.
2// Copyright 2024 Damir Jelić
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16#![doc = include_str!("../README.md")]
17#![cfg_attr(docsrs, feature(doc_cfg))]
18#![warn(missing_docs, missing_debug_implementations)]
19#![cfg_attr(target_family = "wasm", allow(clippy::arc_with_non_send_sync))]
20#![recursion_limit = "256"]
21
22pub mod backups;
23mod ciphers;
24pub mod dehydrated_devices;
25mod error;
26mod file_encryption;
27mod gossiping;
28mod identities;
29mod machine;
30pub mod olm;
31pub mod secret_storage;
32mod session_manager;
33pub mod store;
34pub mod types;
35mod utilities;
36mod verification;
37pub mod x509;
38
39#[cfg(any(test, feature = "testing"))]
40/// Testing facilities and helpers for crypto tests
41pub mod testing {
42    pub use crate::{
43        identities::{
44            device::testing::get_device,
45            user::testing::{
46                get_other_identity, get_own_identity, simulate_key_query_response_for_verification,
47            },
48        },
49        store::{
50            HISTORIC_ROOM_KEY_BUNDLES_BROADCASTER_CAPACITY, IDENTITIES_BROADCASTER_CAPACITY,
51            ROOM_KEYS_RECEIVED_CAPACITY, ROOM_KEYS_WITHHELD_RECEIVED_CAPACITY,
52            SECRETS_BROADCASTER_CAPACITY,
53        },
54    };
55}
56
57use std::collections::{BTreeMap, BTreeSet};
58
59pub use identities::room_identity_state::{
60    IdentityState, IdentityStatusChange, RoomIdentityChange, RoomIdentityProvider,
61    RoomIdentityState,
62};
63use ruma::OwnedRoomId;
64
65/// Return type for the room key importing.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct RoomKeyImportResult {
68    /// The number of room keys that were imported.
69    pub imported_count: usize,
70    /// The total number of room keys that were found in the export.
71    pub total_count: usize,
72    /// The map of keys that were imported.
73    ///
74    /// It's a map from room id to a map of the sender key to a set of session
75    /// ids.
76    pub keys: BTreeMap<OwnedRoomId, BTreeMap<String, BTreeSet<String>>>,
77}
78
79impl RoomKeyImportResult {
80    pub(crate) fn new(
81        imported_count: usize,
82        total_count: usize,
83        keys: BTreeMap<OwnedRoomId, BTreeMap<String, BTreeSet<String>>>,
84    ) -> Self {
85        Self { imported_count, total_count, keys }
86    }
87}
88
89pub use error::{
90    EventError, MegolmError, OlmError, SessionCreationError, SessionRecipientCollectionError,
91    SetRoomSettingsError, SignatureError,
92};
93pub use file_encryption::{
94    AttachmentDecryptor, AttachmentEncryptor, DecryptorError, KeyExportError, MediaEncryptionInfo,
95    decrypt_room_key_export, encrypt_room_key_export,
96};
97pub use gossiping::{GossipRequest, GossippedSecret};
98pub use identities::{
99    Device, DeviceData, LocalTrust, OtherUserIdentity, OtherUserIdentityData, OwnUserIdentity,
100    OwnUserIdentityData, UserDevices, UserIdentity, UserIdentityData,
101};
102pub use machine::{
103    BootstrapCrossSigningError, CrossSigningBootstrapRequests, EncryptionSyncChanges, OlmMachine,
104    OlmMachineBuilder, UncommittedCrossSigningReset,
105};
106use matrix_sdk_common::deserialized_responses::{DecryptedRoomEvent, UnableToDecryptInfo};
107#[cfg(feature = "qrcode")]
108pub use matrix_sdk_qrcode;
109pub use olm::{Account, CrossSigningStatus, EncryptionSettings, Session};
110use serde::{Deserialize, Serialize};
111pub use session_manager::CollectStrategy;
112pub use store::{
113    CryptoStoreError, SecretImportError, SecretInfo,
114    types::{CrossSigningKeyExport, TrackedUser},
115};
116pub use verification::{
117    AcceptSettings, AcceptedProtocols, CancelInfo, Emoji, EmojiShortAuthString, Sas, SasState,
118    Verification, VerificationRequest, VerificationRequestState, format_emojis,
119};
120#[cfg(feature = "qrcode")]
121pub use verification::{QrVerification, QrVerificationState, ScanError};
122#[doc(no_inline)]
123pub use vodozemac;
124
125/// The version of the matrix-sdk-cypto crate being used
126pub const VERSION: &str = env!("CARGO_PKG_VERSION");
127
128#[cfg(test)]
129matrix_sdk_test_utils::init_tracing_for_tests!();
130
131#[cfg(feature = "uniffi")]
132uniffi::setup_scaffolding!();
133
134/// The trust level in the sender's device that is required to decrypt an event.
135#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
136#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
137pub enum TrustRequirement {
138    /// Decrypt events from everyone regardless of trust.
139    ///
140    /// Not recommended, per the guidance of [MSC4153].
141    ///
142    /// [MSC4153]: https://github.com/matrix-org/matrix-doc/pull/4153
143    Untrusted,
144
145    /// Only decrypt events from cross-signed devices or legacy sessions (Megolm
146    /// sessions created before we started collecting trust information).
147    CrossSignedOrLegacy,
148
149    /// Only decrypt events from cross-signed devices.
150    CrossSigned,
151}
152
153/// Settings for decrypting messages
154#[derive(Clone, Debug, Deserialize, Serialize)]
155#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
156pub struct DecryptionSettings {
157    /// The trust level in the sender's device that is required to decrypt the
158    /// event. If the sender's device is not sufficiently trusted,
159    /// [`MegolmError::SenderIdentityNotTrusted`] will be returned.
160    pub sender_device_trust_requirement: TrustRequirement,
161}
162
163/// The result of an attempt to decrypt a room event: either a successful
164/// decryption, or information on a failure.
165#[derive(Clone, Debug, Serialize, Deserialize)]
166pub enum RoomEventDecryptionResult {
167    /// A successfully-decrypted encrypted event.
168    Decrypted(DecryptedRoomEvent),
169
170    /// We were unable to decrypt the event
171    UnableToDecrypt(UnableToDecryptInfo),
172}
173
174#[cfg_attr(doc, doc = include_str!("../.cargo/mermaid.html"))]
175/// A step by step guide that explains how to include [end-to-end-encryption]
176/// support in a [Matrix] client library.
177///
178/// This crate implements a [sans-network-io](https://sans-io.readthedocs.io/)
179/// state machine that allows you to add [end-to-end-encryption] support to a
180/// [Matrix] client library.
181///
182/// This guide aims to provide a comprehensive understanding of end-to-end
183/// encryption in Matrix without any prior knowledge requirements. However, it
184/// is recommended that the reader has a basic understanding of Matrix and its
185/// [client-server specification] for a more informed and efficient learning
186/// experience.
187///
188/// The [introductory](#introduction) section provides a simplified explanation
189/// of end-to-end encryption and its implementation in Matrix for those who may
190/// not have prior knowledge. If you already have a solid understanding of
191/// end-to-end encryption, including the [Olm] and [Megolm] protocols, you may
192/// choose to skip directly to the [Getting Started](#getting-started) section.
193///
194/// # Table of contents
195///
196/// 1. [Introduction](#introduction)
197/// 2. [Getting started](#getting-started)
198/// 3. [Decrypting room events](#decryption)
199/// 4. [Encrypting room events](#encryption)
200/// 5. [Interactively verifying devices and user identities](#verification)
201///
202/// # Introduction
203///
204/// Welcome to the first part of this guide, where we will introduce the
205/// fundamental concepts of end-to-end encryption and its implementation in
206/// Matrix.
207///
208/// This section will provide a clear and concise overview of what end-to-end
209/// encryption is and why it is important for secure communication. You will
210/// also learn about how Matrix uses end-to-end encryption to protect the
211/// privacy and security of its users' communications. Whether you are new to
212/// the topic or simply want to improve your understanding, this section will
213/// serve as a solid foundation for the rest of the guide.
214///
215/// Let's dive in!
216///
217/// ## Notation
218///
219/// ## End-to-end-encryption
220///
221/// End-to-end encryption (E2EE) is a method of secure communication where only
222/// the communicating devices, also known as "the ends," can read the data being
223/// transmitted. This means that the data is encrypted on one device, and can
224/// only be decrypted on the other device. The server is used only as a
225/// transport mechanism to deliver messages between devices.
226///
227/// The following chart displays how communication between two clients using a
228/// server in the middle usually works.
229///
230/// ```mermaid
231/// flowchart LR
232///     alice[Alice]
233///     bob[Bob]
234///     subgraph Homeserver
235///         direction LR
236///         outbox[Alice outbox]
237///         inbox[Bob inbox]
238///         outbox -. unencrypted .-> inbox
239///     end
240///
241///     alice -- encrypted --> outbox
242///     inbox -- encrypted --> bob
243/// ```
244///
245/// The next chart, instead, displays how the same flow is happening in a
246/// end-to-end-encrypted world.
247///
248/// ```mermaid
249/// flowchart LR
250///     alice[Alice]
251///     bob[Bob]
252///     subgraph Homeserver
253///         direction LR
254///         outbox[Alice outbox]
255///         inbox[Bob inbox]
256///         outbox == encrypted ==> inbox
257///     end
258///
259///     alice == encrypted ==> outbox
260///     inbox == encrypted ==> bob
261/// ```
262///
263/// Note that the path from the outbox to the inbox is now encrypted as well.
264///
265/// Alice and Bob have created a secure communication channel through which they
266/// can exchange messages confidentially, without the risk of the server
267/// accessing the contents of their messages.
268///
269/// ## Publishing cryptographic identities of devices
270///
271/// If Alice and Bob want to establish a secure channel over which they can
272/// exchange messages, they first need learn about each others cryptographic
273/// identities. This is achieved by using the homeserver as a public key
274/// directory.
275///
276/// A public key directory is used to store and distribute public keys of users
277/// in an end-to-end encrypted system. The basic idea behind a public key
278/// directory is that it allows users to easily discover and download the public
279/// keys of other users with whom they wish to establish an end-to-end encrypted
280/// communication.
281///
282/// Each user generates a pair of public and private keys. The user then uploads
283/// their public key to the public key directory. Other users can then search
284/// the directory to find the public key of the user they wish to communicate
285/// with, and download it to their own device.
286///
287/// ```mermaid
288/// flowchart LR
289///     alice[Alice]
290///     subgraph homeserver[Homeserver]
291///         direction LR
292///         directory[(Public key directory)]
293///     end
294///     bob[Bob]
295///
296///     alice -- upload keys --> directory
297///     directory -- download keys --> bob
298/// ```
299///
300/// Once a user has the other user's public key, they can use it to establish an
301/// end-to-end encrypted channel using a [key-agreement protocol].
302///
303/// ## Using the triple Diffie-Hellman key-agreement protocol
304///
305/// In the triple Diffie-Hellman key agreement protocol (3DH in short), each
306/// user generates a long-term identity key pair and a set of one-time prekeys.
307/// When two users want to establish a shared secret key, they exchange their
308/// public identity keys and one of their prekeys. These public keys are then
309/// used in a [Diffie-Hellman] key exchange to compute a shared secret key.
310///
311/// The use of one-time prekeys ensures that the shared secret key is different
312/// for each session, even if the same identity keys are used.
313///
314/// ```mermaid
315/// flowchart LR
316/// subgraph alice_keys[Alice Keys]
317///     direction TB
318///     alice_key[Alice's identity key]
319///     alice_base_key[Alice's one-time key]
320/// end
321///
322/// subgraph bob_keys[Bob Keys]
323///     direction TB
324///     bob_key[Bob's identity key]
325///     bob_one_time[Bob's one-time key]
326/// end
327///
328/// alice_key <--> bob_one_time
329/// alice_base_key <--> bob_one_time
330/// alice_base_key <--> bob_key
331/// ```
332///
333/// Similar to [X3DH] (Extended Triple Diffie-Hellman) key agreement protocol
334///
335/// ## Speeding up encryption for large groups
336///
337/// In the previous section we learned how to utilize a key agreement protocol
338/// to establish secure 1-to-1 encrypted communication channels. These channels
339/// allow us to encrypt a message for each device separately.
340///
341/// One critical property of these channels is that, if you want to send a
342/// message to a group of devices, we'll need to encrypt the message for each
343/// device individually.
344///
345/// TODO Explain how megolm fits into this
346///
347/// # Getting started
348///
349/// Before we start writing any code, let us get familiar with the basic
350/// principle upon which this library is built.
351///
352/// The central piece of the library is the [`OlmMachine`] which acts as a state
353/// machine which consumes data that gets received from the homeserver and
354/// outputs data which should be sent to the homeserver.
355///
356/// ## Push/pull mechanism
357///
358/// The [`OlmMachine`] at the heart of it acts as a state machine that operates
359/// in a push/pull manner. HTTP responses which were received from the
360/// homeserver get forwarded into the [`OlmMachine`] and in turn the internal
361/// state gets updated which produces HTTP requests that need to be sent to the
362/// homeserver.
363///
364/// In a manner, we're pulling data from the server, we update our internal
365/// state based on the data and in turn push data back to the server.
366///
367/// ```mermaid
368/// flowchart LR
369///     homeserver[Homeserver]
370///     client[OlmMachine]
371///
372///     homeserver -- pull --> client
373///     client -- push --> homeserver
374/// ```
375///
376/// ## Initializing the state machine
377///
378/// ```
379/// use anyhow::Result;
380/// use matrix_sdk_crypto::OlmMachine;
381/// use ruma::user_id;
382///
383/// # #[tokio::main]
384/// # async fn main() -> Result<()> {
385/// let user_id = user_id!("@alice:localhost");
386/// let device_id = "DEVICEID".into();
387///
388/// let machine = OlmMachine::new(user_id, device_id).await;
389/// # Ok(())
390/// # }
391/// ```
392///
393/// This will create a [`OlmMachine`] that does not persist any data TODO
394///
395/// ```ignore
396/// use anyhow::Result;
397/// use matrix_sdk_crypto::OlmMachine;
398/// use matrix_sdk_sqlite::SqliteCryptoStore;
399/// use ruma::user_id;
400///
401/// # #[tokio::main]
402/// # async fn main() -> Result<()> {
403/// let user_id = user_id!("@alice:localhost");
404/// let device_id = "DEVICEID".into();
405///
406/// let store = SqliteCryptoStore::open("/home/example/matrix-client/", None).await?;
407///
408/// let machine = OlmMachine::with_store(user_id, device_id, store).await;
409/// # Ok(())
410/// # }
411/// ```
412///
413/// # Decryption
414///
415/// In the world of encrypted communication, it is common to start with the
416/// encryption step when implementing a protocol. However, in the case of adding
417/// end-to-end encryption support to a Matrix client library, a simpler approach
418/// is to first focus on the decryption process. This is because there are
419/// already Matrix clients in existence that support encryption, which means
420/// that our client library can simply receive encrypted messages and then
421/// decrypt them.
422///
423/// In this section, we will guide you through the minimal steps necessary to
424/// get the decryption process up and running using the matrix-sdk-crypto Rust
425/// crate. By the end of this section you should have a Matrix client that is
426/// able to decrypt room events that other clients have sent.
427///
428/// To enable decryption the following three steps are needed:
429///
430/// 1. [The cryptographic identity of your device needs to be published to the
431///    homeserver](#uploading-identity-and-one-time-keys).
432/// 2. [Decryption keys coming in from other devices need to be processed and
433///    stored](#receiving-room-keys-and-related-changes).
434/// 3. [Individual messages need to be decrypted](#decrypting-room-events).
435///
436/// The simplified flowchart
437///
438/// ```mermaid
439/// graph TD
440///     sync[Sync with the homeserver]
441///     receive_changes[Push E2EE related changes into the state machine]
442///     send_outgoing_requests[Send all outgoing requests to the homeserver]
443///     decrypt[Process the rest of the sync]
444///
445///     sync --> receive_changes;
446///     receive_changes --> send_outgoing_requests;
447///     send_outgoing_requests --> decrypt;
448///     decrypt -- repeat --> sync;
449/// ```
450///
451/// ## Uploading identity and one-time keys
452///
453/// To enable end-to-end encryption in a Matrix client, the first step is to
454/// announce the support for it to other users in the network. This is done by
455/// publishing the client's long-term device keys and a set of one-time prekeys
456/// to the Matrix homeserver. The homeserver then makes this information
457/// available to other devices in the network.
458///
459/// The long-term device keys and one-time prekeys allow other devices to
460/// encrypt messages specifically for your device.
461///
462/// To achieve this, you will need to extract any requests that need to be sent
463/// to the homeserver from the [`OlmMachine`] and send them to the homeserver.
464/// The following snippet showcases how to achieve this using the
465/// [`OlmMachine::outgoing_requests()`] method:
466///
467/// ```no_run
468/// # use std::collections::BTreeMap;
469/// # use ruma::api::client::keys::upload_keys::v3::Response;
470/// # use anyhow::Result;
471/// # use matrix_sdk_crypto::{OlmMachine, types::requests::OutgoingRequest};
472/// # async fn send_request(request: OutgoingRequest) -> Result<Response> {
473/// #     let response = unimplemented!();
474/// #     Ok(response)
475/// # }
476/// # #[tokio::main]
477/// # async fn main() -> Result<()> {
478/// # let machine: OlmMachine = unimplemented!();
479/// // Get all the outgoing requests.
480/// let outgoing_requests = machine.outgoing_requests().await?;
481///
482/// // Send each request to the server and push the response into the state machine.
483/// // You can safely send these requests out in parallel.
484/// for request in outgoing_requests {
485///     let request_id = request.request_id();
486///     // Send the request to the server and await a response.
487///     let response = send_request(request).await?;
488///     // Push the response into the state machine.
489///     machine.mark_request_as_sent(&request_id, &response).await?;
490/// }
491/// # Ok(())
492/// # }
493/// ```
494///
495/// ### πŸ”’ locking rule
496///
497/// It's important to note that the outgoing requests method in the
498/// [`OlmMachine`], while thread-safe, may return the same request multiple
499/// times if it is called multiple times before the request has been marked as
500/// sent. To prevent this issue, it is advisable to encapsulate the outgoing
501/// request handling logic into a separate helper method and protect it from
502/// being called multiple times concurrently using a lock.
503///
504/// This helps to ensure that the request is only handled once and prevents
505/// multiple identical requests from being sent.
506///
507/// Additionally, if an error occurs while sending a request using the
508/// [`OlmMachine::outgoing_requests()`] method, the request will be naturally
509/// retried the next time the method is called.
510///
511/// A more complete example, which uses a helper method, might look like this:
512///
513/// ```no_run
514/// # use std::collections::BTreeMap;
515/// # use ruma::api::client::keys::upload_keys::v3::Response;
516/// # use anyhow::Result;
517/// # use matrix_sdk_crypto::{OlmMachine, types::requests::OutgoingRequest};
518/// # async fn send_request(request: &OutgoingRequest) -> Result<Response> {
519/// #     let response = unimplemented!();
520/// #     Ok(response)
521/// # }
522/// # #[tokio::main]
523/// # async fn main() -> Result<()> {
524/// struct Client {
525///     outgoing_requests_lock: tokio::sync::Mutex<()>,
526///     olm_machine: OlmMachine,
527/// }
528///
529/// async fn process_outgoing_requests(client: &Client) -> Result<()> {
530///     // Let's acquire a lock so we know that we don't send out the same request out multiple
531///     // times.
532///     let guard = client.outgoing_requests_lock.lock().await;
533///
534///     for request in client.olm_machine.outgoing_requests().await? {
535///         let request_id = request.request_id();
536///
537///         match send_request(&request).await {
538///             Ok(response) => {
539///                 client.olm_machine.mark_request_as_sent(&request_id, &response).await?;
540///             }
541///             Err(error) => {
542///                 // It's OK to ignore transient HTTP errors since requests will be retried.
543///                 eprintln!(
544///                     "Error while sending out a end-to-end encryption \
545///                     related request: {error:?}"
546///                 );
547///             }
548///         }
549///     }
550///
551///     Ok(())
552/// }
553/// # Ok(())
554/// # }
555/// ```
556///
557/// Once we have the helper method that processes our outgoing requests we can
558/// structure our sync method as follows:
559///
560/// ```no_run
561/// # use anyhow::Result;
562/// # use matrix_sdk_crypto::OlmMachine;
563/// # #[tokio::main]
564/// # async fn main() -> Result<()> {
565/// # struct Client {
566/// #     outgoing_requests_lock: tokio::sync::Mutex<()>,
567/// #     olm_machine: OlmMachine,
568/// # }
569/// # async fn process_outgoing_requests(client: &Client) -> Result<()> {
570/// #    unimplemented!();
571/// # }
572/// # async fn send_out_sync_request(client: &Client) -> Result<()> {
573/// #    unimplemented!();
574/// # }
575/// async fn sync(client: &Client) -> Result<()> {
576///     // This is happening at the top of the method so we advertise our
577///     // end-to-end encryption capabilities as soon as possible.
578///     process_outgoing_requests(client).await?;
579///
580///     // We can sync with the homeserver now.
581///     let response = send_out_sync_request(client).await?;
582///
583///     // Process the sync response here.
584///
585///     Ok(())
586/// }
587/// # Ok(())
588/// # }
589/// ```
590///
591/// ## Receiving room keys and related changes
592///
593/// The next step in our implementation is to forward messages that were sent
594/// directly to the client's device, and state updates about the one-time
595/// prekeys, to the [`OlmMachine`]. This is achieved using the
596/// [`OlmMachine::receive_sync_changes()`] method.
597///
598/// The method performs two tasks:
599///
600/// 1. It processes and, if necessary, decrypts each [to-device] event that was
601///    pushed into it, and returns the decrypted events. The original events are
602///    replaced with their decrypted versions.
603///
604/// 2. It produces internal state changes that may trigger the creation of new
605///    outgoing requests. For example, if the server informs the client that its
606///    one-time prekeys have been depleted, the OlmMachine will create an
607///    outgoing request to replenish them.
608///
609/// Our updated sync method now looks like this:
610///
611/// ```no_run
612/// # use anyhow::Result;
613/// # use matrix_sdk_crypto::{
614///     DecryptionSettings, EncryptionSyncChanges, OlmMachine, TrustRequirement
615/// };
616/// # use ruma::api::client::sync::sync_events::v3::Response;
617/// # #[tokio::main]
618/// # async fn main() -> Result<()> {
619/// # struct Client {
620/// #     outgoing_requests_lock: tokio::sync::Mutex<()>,
621/// #     olm_machine: OlmMachine,
622/// # }
623/// # async fn process_outgoing_requests(client: &Client) -> Result<()> {
624/// #    unimplemented!();
625/// # }
626/// # async fn send_out_sync_request(client: &Client) -> Result<Response> {
627/// #    unimplemented!();
628/// # }
629/// async fn sync(client: &Client) -> Result<()> {
630///     process_outgoing_requests(client).await?;
631///
632///     let response = send_out_sync_request(client).await?;
633///
634///     let sync_changes = EncryptionSyncChanges {
635///         to_device_events: response.to_device.events,
636///         changed_devices: &response.device_lists,
637///         one_time_keys_counts: &response.device_one_time_keys_count,
638///         unused_fallback_keys: response.device_unused_fallback_key_types.as_deref(),
639///         next_batch_token: Some(response.next_batch),
640///     };
641///
642///     let decryption_settings = DecryptionSettings {
643///         sender_device_trust_requirement: TrustRequirement::Untrusted
644///     };
645///
646///     // Push the sync changes into the OlmMachine, make sure that this is
647///     // happening before the `next_batch` token of the sync is persisted.
648///     let to_device_events = client
649///         .olm_machine
650///         .receive_sync_changes(sync_changes, &decryption_settings)
651///         .await?;
652///
653///     // Send the outgoing requests out that the sync changes produced.
654///     process_outgoing_requests(client).await?;
655///
656///     // Process the rest of the sync response here.
657///
658///     Ok(())
659/// }
660/// # Ok(())
661/// # }
662/// ```
663///
664/// It is important to note that the names of the fields in the response shown
665/// in the example match the names of the fields specified in the [sync]
666/// response specification.
667///
668/// It is critical to note that due to the ephemeral nature of to-device
669/// events[[1]], it is important to process these events before persisting the
670/// `next_batch` sync token. This is because if the `next_batch` sync token is
671/// persisted before processing the to-device events, some messages might be
672/// lost, leading to decryption failures.
673///
674/// ## Decrypting room events
675///
676/// The final step in the decryption process is to decrypt the room events that
677/// are received from the server. To do this, the encrypted events must be
678/// passed to the [`OlmMachine`], which will use the keys that were previously
679/// exchanged between devices to decrypt the events. The decrypted events can
680/// then be processed and displayed to the user in the Matrix client.
681///
682/// Room message [events] can be decrypted using the
683/// [`OlmMachine::decrypt_room_event()`] method:
684///
685/// ```no_run
686/// # use std::collections::BTreeMap;
687/// # use anyhow::Result;
688/// # use matrix_sdk_crypto::{OlmMachine, DecryptionSettings, TrustRequirement};
689/// # #[tokio::main]
690/// # async fn main() -> Result<()> {
691/// # let encrypted = unimplemented!();
692/// # let room_id = unimplemented!();
693/// # let machine: OlmMachine = unimplemented!();
694/// # let settings = DecryptionSettings { sender_device_trust_requirement: TrustRequirement::Untrusted };
695/// // Decrypt your room events now.
696/// let decrypted = machine
697///     .decrypt_room_event(encrypted, room_id, &settings)
698///     .await?;
699/// # Ok(())
700/// # }
701/// ```
702///
703/// It's worth mentioning that the [`OlmMachine::decrypt_room_event()`] method
704/// is designed to be thread-safe and can be safely called concurrently. This
705/// means that room message [events] can be processed in parallel, improving the
706/// overall efficiency of the end-to-end encryption implementation.
707///
708/// By allowing room message [events] to be processed concurrently, the client's
709/// implementation can take full advantage of the capabilities of modern
710/// hardware and achieve better performance, especially when dealing with a
711/// large number of messages at once.
712///
713/// # Encryption
714///
715/// In this section of the guide, we will focus on enabling the encryption of
716/// messages in our Matrix client library. Up until this point, we have been
717/// discussing the process of decrypting messages that have been encrypted by
718/// other devices. Now, we will shift our focus to the process of encrypting
719/// messages on the client side, so that they can be securely transmitted over
720/// the Matrix network to other devices.
721///
722/// This section will guide you through the steps required to set up the
723/// encryption process, including establishing the necessary sessions and
724/// encrypting messages using the Megolm group session. The specific steps are
725/// outlined below:
726///
727/// 1. [Cryptographic devices of other users need to be
728///    discovered](#tracking-users)
729/// 2. [Secure channels between the devices need to be
730///    established](#establishing-end-to-end-encrypted-channels)
731/// 3. [A room key needs to be exchanged with the group](#exchanging-room-keys)
732/// 4. [Individual messages need to be encrypted using the room
733///    key](#encrypting-room-events)
734///
735/// The process for enabling encryption in a two-device scenario is also
736/// depicted in the following sequence diagram:
737///
738/// ```mermaid
739/// sequenceDiagram
740/// actor Alice
741/// participant Homeserver
742/// actor Bob
743///
744/// Alice->>Homeserver: Download Bob's one-time prekey
745/// Homeserver->>Alice: Bob's one-time prekey
746/// Alice->>Alice: Encrypt the room key
747/// Alice->>Homeserver: Send the room key to each of Bob's devices
748/// Homeserver->>Bob: Deliver the room key
749/// Alice->>Alice: Encrypt the message
750/// Alice->>Homeserver: Send the encrypted message
751/// Homeserver->>Bob: Deliver the encrypted message
752/// ```
753///
754/// In the following subsections, we will provide a step-by-step guide on how to
755/// enable the encryption of messages using the OlmMachine. We will outline the
756/// specific method calls and usage patterns that are required to establish the
757/// necessary sessions, encrypt messages, and send them over the Matrix network.
758///
759/// ## Tracking users
760///
761/// The first step in the process of encrypting a message and sending it to a
762/// device is to discover the devices that the recipient user has. This can be
763/// achieved by sending a request to the homeserver to retrieve a list of the
764/// recipient's device keys. The response to this request will include the
765/// device keys for all of the devices that belong to the recipient, as well as
766/// information about their current status and whether or not they support
767/// end-to-end encryption.
768///
769/// The process for discovering and keeping track of devices for a user is
770/// outlined in the Matrix specification in the
771/// "[Tracking the device list for a user]" section.
772///
773/// A simplified sequence diagram of the process can also be found below.
774///
775/// ```mermaid
776/// sequenceDiagram
777/// actor Alice
778/// participant Homeserver
779///
780/// Alice->>Homeserver: Sync with the homeserver
781/// Homeserver->>Alice: Users whose device list has changed
782/// Alice->>Alice: Mark user's devicel list as outdated
783/// Alice->>Homeserver: Ask the server for the new device list of all the outdated users
784/// Alice->>Alice: Update the local device list and mark the users as up-to-date
785/// ```
786///
787/// The OlmMachine refers to users whose devices we are tracking as "tracked
788/// users" and utilizes the [`OlmMachine::update_tracked_users()`] method to
789/// start considering users to be tracked. Keeping the above diagram in mind, we
790/// can now update our sync method as follows:
791///
792/// ```no_run
793/// # use anyhow::Result;
794/// # use std::ops::Deref;
795/// # use matrix_sdk_crypto::{
796/// #     DecryptionSettings, EncryptionSyncChanges, OlmMachine, TrustRequirement
797/// # };
798/// # use ruma::api::client::sync::sync_events::v3::{Response, State, JoinedRoom};
799/// # use ruma::{OwnedUserId, serde::Raw, events::AnySyncStateEvent};
800/// # #[tokio::main]
801/// # async fn main() -> Result<()> {
802/// # struct Client {
803/// #     outgoing_requests_lock: tokio::sync::Mutex<()>,
804/// #     olm_machine: OlmMachine,
805/// # }
806/// # async fn process_outgoing_requests(client: &Client) -> Result<()> {
807/// #    unimplemented!();
808/// # }
809/// # async fn send_out_sync_request(client: &Client) -> Result<Response> {
810/// #    unimplemented!();
811/// # }
812/// # fn is_member_event_of_a_joined_user(event: &Raw<AnySyncStateEvent>) -> bool {
813/// #     true
814/// # }
815/// # fn get_user_id(event: &Raw<AnySyncStateEvent>) -> OwnedUserId {
816/// #     unimplemented!();
817/// # }
818/// # fn is_room_encrypted(room: &JoinedRoom) -> bool {
819/// #     true
820/// # }
821/// async fn sync(client: &Client) -> Result<()> {
822///     process_outgoing_requests(client).await?;
823///
824///     let response = send_out_sync_request(client).await?;
825///
826///     let sync_changes = EncryptionSyncChanges {
827///         to_device_events: response.to_device.events,
828///         changed_devices: &response.device_lists,
829///         one_time_keys_counts: &response.device_one_time_keys_count,
830///         unused_fallback_keys: response.device_unused_fallback_key_types.as_deref(),
831///         next_batch_token: Some(response.next_batch),
832///     };
833///
834///     let decryption_settings = DecryptionSettings {
835///         sender_device_trust_requirement: TrustRequirement::Untrusted
836///     };
837///
838///     // Push the sync changes into the OlmMachine, make sure that this is
839///     // happening before the `next_batch` token of the sync is persisted.
840///     let to_device_events = client
841///         .olm_machine
842///         .receive_sync_changes(sync_changes, &decryption_settings)
843///         .await?;
844///
845///     // Send the outgoing requests out that the sync changes produced.
846///     process_outgoing_requests(client).await?;
847///
848///     // Collect all the joined and invited users of our end-to-end encrypted rooms here.
849///     let mut users = Vec::new();
850///
851///     for (_, room) in &response.rooms.join {
852///         // For simplicity reasons we're only looking at the state field of a joined room, but
853///         // the events in the timeline are important as well.
854///         if let State::Before(state) = &room.state {
855///            for event in &state.events {
856///                 if is_member_event_of_a_joined_user(event) && is_room_encrypted(room) {
857///                     let user_id = get_user_id(event);
858///                     users.push(user_id);
859///                 }
860///             }
861///         }
862///     }
863///
864///     // Mark all the users that we consider to be in a end-to-end encrypted room with us to be
865///     // tracked. We need to know about all the devices each user has so we can later encrypt
866///     // messages for each of their devices.
867///     client.olm_machine.update_tracked_users(users.iter().map(Deref::deref)).await?;
868///
869///     // Process the rest of the sync response here.
870///
871///     Ok(())
872/// }
873/// # Ok(())
874/// # }
875/// ```
876///
877/// Now that we have discovered the devices of the users we'd like to
878/// communicate with in an end-to-end encrypted manner, we can start considering
879/// encrypting messages for those devices. This concludes the sync processing
880/// method, we are now ready to move on to the next section, which will explain
881/// how to begin the encryption process.
882///
883/// ## Establishing end-to-end encrypted channels
884///
885/// In the
886/// [Triple Diffie-Hellman](#
887/// using-the-triple-diffie-hellman-key-agreement-protocol) section, we
888/// described the need for two Curve25519 keys from the recipient
889/// device to establish a 1-to-1 secure channel: the long-term identity key of a
890/// device and a one-time prekey. In the previous section, we started tracking
891/// the device keys, including the long-term identity key that we need. The next
892/// step is to download the one-time prekey on an on-demand basis and establish
893/// the 1-to-1 secure channel.
894///
895/// To accomplish this, we can use the [`OlmMachine::get_missing_sessions()`]
896/// method in bulk, which will claim the one-time prekey for all the devices of
897/// a user that we're not already sharing a 1-to-1 encrypted channel with.
898///
899/// ### πŸ”’ locking rule
900///
901/// As with the [`OlmMachine::outgoing_requests()`] method, it is necessary to
902/// protect this method with a lock, otherwise we will be creating more 1-to-1
903/// encrypted channels than necessary.
904///
905/// ```no_run
906/// # use std::collections::{BTreeMap, HashSet};
907/// # use std::ops::Deref;
908/// # use anyhow::Result;
909/// # use ruma::UserId;
910/// # use ruma::api::client::keys::claim_keys::v3::{Response, Request};
911/// # use matrix_sdk_crypto::OlmMachine;
912/// # async fn send_request(request: &Request) -> Result<Response> {
913/// #     let response = unimplemented!();
914/// #     Ok(response)
915/// # }
916/// # #[tokio::main]
917/// # async fn main() -> Result<()> {
918/// # let users: HashSet<&UserId> = HashSet::new();
919/// # let machine: OlmMachine = unimplemented!();
920/// // Mark all the users that are part of an encrypted room as tracked
921/// if let Some((request_id, request)) =
922///     machine.get_missing_sessions(users.iter().map(Deref::deref)).await?
923/// {
924///     let response = send_request(&request).await?;
925///     machine.mark_request_as_sent(&request_id, &response).await?;
926/// }
927/// # Ok(())
928/// # }
929/// ```
930///
931/// With the ability to exchange messages directly with devices, we can now
932/// start sharing room keys over the 1-to-1 encrypted channel.
933///
934/// ## Exchanging room keys
935///
936/// To exchange a room key with our group, we will once again take a bulk
937/// approach. The [`OlmMachine::share_room_key()`] method is used to accomplish
938/// this step. This method will create a new room key, if necessary, and encrypt
939/// it for each device belonging to the users provided as an argument. It will
940/// then output an array of sendToDevice requests that we must send to the
941/// server, and mark the requests as sent.
942///
943/// ### πŸ”’ locking rule
944///
945/// Like some of the previous methods, OlmMachine::share_room_key() needs to be
946/// protected by a lock to prevent the possibility of creating and sending
947/// multiple room keys simultaneously for the same group. The lock can be
948/// implemented on a per-room basis, which allows for parallel room key
949/// exchanges across different rooms.
950///
951/// ```no_run
952/// # use std::collections::{BTreeMap, HashSet};
953/// # use std::ops::Deref;
954/// # use anyhow::Result;
955/// # use ruma::UserId;
956/// # use ruma::api::client::keys::claim_keys::v3::{Response, Request};
957/// # use matrix_sdk_crypto::{OlmMachine, types::requests::ToDeviceRequest, EncryptionSettings};
958/// # async fn send_request(request: &ToDeviceRequest) -> Result<Response> {
959/// #     let response = unimplemented!();
960/// #     Ok(response)
961/// # }
962/// # #[tokio::main]
963/// # async fn main() -> Result<()> {
964/// # let users: HashSet<&UserId> = HashSet::new();
965/// # let room_id = unimplemented!();
966/// # let settings = EncryptionSettings::default();
967/// # let machine: OlmMachine = unimplemented!();
968/// // Let's share a room key with our group.
969/// let requests = machine.share_room_key(
970///     room_id,
971///     users.iter().map(Deref::deref),
972///     EncryptionSettings::default(),
973/// ).await?;
974///
975/// // Make sure each request is sent out
976/// for request in requests {
977///     let request_id = &request.txn_id;
978///     let response = send_request(&request).await?;
979///     machine.mark_request_as_sent(&request_id, &response).await?;
980/// }
981/// # Ok(())
982/// # }
983/// ```
984///
985/// In order to ensure that room keys are rotated and exchanged when needed, the
986/// [`OlmMachine::share_room_key()`] method should be called before sending each
987/// room message in an end-to-end encrypted room. If a room key has already been
988/// exchanged, the method becomes a no-op.
989///
990/// ## Encrypting room events
991///
992/// After the room key has been successfully shared, a plaintext can be
993/// encrypted.
994///
995/// ```no_run
996/// # use anyhow::Result;
997/// # use matrix_sdk_crypto::{DecryptionSettings, OlmMachine, TrustRequirement};
998/// # use ruma::events::{AnyMessageLikeEventContent, room::message::RoomMessageEventContent};
999/// # #[tokio::main]
1000/// # async fn main() -> Result<()> {
1001/// # let room_id = unimplemented!();
1002/// # let event = unimplemented!();
1003/// # let machine: OlmMachine = unimplemented!();
1004/// # let settings = DecryptionSettings { sender_device_trust_requirement: TrustRequirement::Untrusted };
1005/// let content = AnyMessageLikeEventContent::RoomMessage(RoomMessageEventContent::text_plain("It's a secret to everybody."));
1006/// let encrypted_content = machine.encrypt_room_event(room_id, content).await?;
1007/// # Ok(())
1008/// # }
1009/// ```
1010///
1011/// ## Appendix: combining the session creation and room key exchange
1012///
1013/// The steps from the previous three sections should combined into a single
1014/// method that is used to send messages.
1015///
1016/// ```no_run
1017/// # use std::collections::{BTreeMap, HashSet};
1018/// # use std::ops::Deref;
1019/// # use anyhow::Result;
1020/// # use serde_json::json;
1021/// # use ruma::{UserId, RoomId, serde::Raw};
1022/// # use ruma::api::client::keys::claim_keys::v3::{Response, Request};
1023/// # use matrix_sdk_crypto::{EncryptionSettings, OlmMachine, types::requests::ToDeviceRequest};
1024/// # use tokio::sync::MutexGuard;
1025/// # async fn send_request(request: &Request) -> Result<Response> {
1026/// #     let response = unimplemented!();
1027/// #     Ok(response)
1028/// # }
1029/// # async fn send_to_device_request(request: &ToDeviceRequest) -> Result<Response> {
1030/// #     let response = unimplemented!();
1031/// #     Ok(response)
1032/// # }
1033/// # async fn acquire_per_room_lock(room_id: &RoomId) -> MutexGuard<()> {
1034/// #     unimplemented!();
1035/// # }
1036/// # async fn get_joined_members(room_id: &RoomId) -> Vec<&UserId> {
1037/// #    unimplemented!();
1038/// # }
1039/// # fn is_room_encrypted(room_id: &RoomId) -> bool {
1040/// #     true
1041/// # }
1042/// # #[tokio::main]
1043/// # async fn main() -> Result<()> {
1044/// # let users: HashSet<&UserId> = HashSet::new();
1045/// # let machine: OlmMachine = unimplemented!();
1046/// struct Client {
1047///     session_establishment_lock: tokio::sync::Mutex<()>,
1048///     olm_machine: OlmMachine,
1049/// }
1050///
1051/// async fn establish_sessions(client: &Client, users: &[&UserId]) -> Result<()> {
1052///     if let Some((request_id, request)) =
1053///         client.olm_machine.get_missing_sessions(users.iter().map(Deref::deref)).await?
1054///     {
1055///         let response = send_request(&request).await?;
1056///         client.olm_machine.mark_request_as_sent(&request_id, &response).await?;
1057///     }
1058///
1059///     Ok(())
1060/// }
1061///
1062/// async fn share_room_key(machine: &OlmMachine, room_id: &RoomId, users: &[&UserId]) -> Result<()> {
1063///     let _lock = acquire_per_room_lock(room_id).await;
1064///
1065///     let requests = machine.share_room_key(
1066///             room_id,
1067///             users.iter().map(Deref::deref),
1068///             EncryptionSettings::default(),
1069///     ).await?;
1070///
1071///     // Make sure each request is sent out
1072///     for request in requests {
1073///         let request_id = &request.txn_id;
1074///         let response = send_to_device_request(&request).await?;
1075///         machine.mark_request_as_sent(&request_id, &response).await?;
1076///     }
1077///
1078///     Ok(())
1079/// }
1080///
1081/// async fn send_message(client: &Client, room_id: &RoomId, message: &str) -> Result<()> {
1082///     let mut content = json!({
1083///         "body": message,
1084///             "msgtype": "m.text",
1085///     });
1086///
1087///     if is_room_encrypted(room_id) {
1088///         let content = Raw::new(&json!({
1089///             "body": message,
1090///             "msgtype": "m.text",
1091///         }))?.cast_unchecked();
1092///
1093///         let users = get_joined_members(room_id).await;
1094///
1095///         establish_sessions(client, &users).await?;
1096///         share_room_key(&client.olm_machine, room_id, &users).await?;
1097///
1098///         let encrypted = client
1099///             .olm_machine
1100///             .encrypt_room_event_raw(room_id, "m.room.message", &content)
1101///             .await?;
1102///     }
1103///
1104///     Ok(())
1105/// }
1106/// # Ok(())
1107/// # }
1108/// ```
1109///
1110/// TODO
1111///
1112/// [Matrix]: https://matrix.org/
1113/// [Olm]: https://gitlab.matrix.org/matrix-org/olm/-/blob/master/docs/olm.md
1114/// [Diffie-Hellman]: https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange
1115/// [Megolm]: https://gitlab.matrix.org/matrix-org/olm/blob/master/docs/megolm.md
1116/// [end-to-end-encryption]: https://en.wikipedia.org/wiki/End-to-end_encryption
1117/// [homeserver]: https://spec.matrix.org/unstable/#architecture
1118/// [key-agreement protocol]: https://en.wikipedia.org/wiki/Key-agreement_protocol
1119/// [client-server specification]: https://spec.matrix.org/latest/client-server-api
1120/// [forward secrecy]: https://en.wikipedia.org/wiki/Forward_secrecy
1121/// [replay attacks]: https://en.wikipedia.org/wiki/Replay_attack
1122/// [Tracking the device list for a user]: https://spec.matrix.org/unstable/client-server-api/#tracking-the-device-list-for-a-user
1123/// [X3DH]: https://signal.org/docs/specifications/x3dh/
1124/// [to-device]: https://spec.matrix.org/unstable/client-server-api/#send-to-device-messaging
1125/// [sync]: https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3sync
1126/// [events]: https://spec.matrix.org/unstable/client-server-api/#events
1127///
1128/// [1]: https://spec.matrix.org/unstable/client-server-api/#server-behaviour-4
1129pub mod tutorial {}
1130
1131#[cfg(test)]
1132mod test {
1133    use insta::assert_json_snapshot;
1134
1135    use crate::{DecryptionSettings, TrustRequirement};
1136
1137    #[test]
1138    fn snapshot_trust_requirement() {
1139        assert_json_snapshot!(TrustRequirement::Untrusted);
1140        assert_json_snapshot!(TrustRequirement::CrossSignedOrLegacy);
1141        assert_json_snapshot!(TrustRequirement::CrossSigned);
1142    }
1143
1144    #[test]
1145    fn snapshot_decryption_settings() {
1146        assert_json_snapshot!(DecryptionSettings {
1147            sender_device_trust_requirement: TrustRequirement::Untrusted,
1148        });
1149    }
1150}