Crate matrix_sdk_crypto

Source
Expand description

A no-network-IO implementation of a state machine that handles end-to-end encryption for Matrix clients.

If you’re just trying to write a Matrix client or bot in Rust, you’re probably looking for matrix-sdk instead.

However, if you’re looking to add end-to-end encryption to an existing Matrix client or library, read on.

The state machine works in a push/pull manner:

  • you push state changes and events retrieved from a Matrix homeserver /sync response into the state machine
  • you pull requests that you’ll need to send back to the homeserver out of the state machine
use std::collections::BTreeMap;

use matrix_sdk_crypto::{EncryptionSyncChanges, OlmMachine, OlmError};
use ruma::{
    api::client::sync::sync_events::{v3::ToDevice, DeviceLists},
    device_id, user_id,
};

#[tokio::main]
async fn main() -> Result<(), OlmError> {
    let alice = user_id!("@alice:example.org");
    let machine = OlmMachine::new(&alice, device_id!("DEVICEID")).await;

    let changed_devices = DeviceLists::default();
    let one_time_key_counts = BTreeMap::default();
    let unused_fallback_keys = Some(Vec::new());
    let next_batch_token = "T0K3N".to_owned();

    // Push changes that the server sent to us in a sync response.
    let decrypted_to_device = machine.receive_sync_changes(EncryptionSyncChanges {
        to_device_events: vec![],
        changed_devices: &changed_devices,
        one_time_keys_counts: &one_time_key_counts,
        unused_fallback_keys: unused_fallback_keys.as_deref(),
        next_batch_token: Some(next_batch_token),
    }).await?;

    // Pull requests that we need to send out.
    let outgoing_requests = machine.outgoing_requests().await?;

    // Send the requests here out and call machine.mark_request_as_sent().

    Ok(())
}

It is recommended to use the tutorial to understand how end-to-end encryption works in Matrix and how to add end-to-end encryption support in your Matrix client library.

§Crate Feature Flags

The following crate feature flags are available:

FeatureDefaultDescription
qrcodeNoEnables QR code based interactive verification
jsNoEnables JavaScript API usage for things like the current system time on WASM (does nothing on other targets)
testingNoProvides facilities and functions for tests, in particular for integration testing store implementations. ATTENTION: do not ever use outside of tests, we do not provide any stability warantees on these, these are merely helpers. If you find you need any function provided here outside of tests, please open a Github Issue and inform us about your use case for us to consider.
  • testing: Provides facilities and functions for tests, in particular for integration testing store implementations. ATTENTION: do not ever use outside of tests, we do not provide any stability warantees on these, these are merely helpers. If you find you need any function provided here outside of tests, please open a Github Issue and inform us about your use case for us to consider.

  • _disable-minimum-rotation-period-ms: Do not use except for testing. Disables the floor on the rotation period of room keys.

§Enabling logging

Users of the matrix-sdk-crypto crate can enable log output by depending on the tracing-subscriber crate and including the following line in their application (e.g. at the start of main):

tracing_subscriber::fmt::init();

The log output is controlled via the RUST_LOG environment variable by setting it to one of the error, warn, info, debug or trace levels. The output is printed to stdout.

The RUST_LOG variable also supports a more advanced syntax for filtering log output more precisely, for instance with crate-level granularity. For more information on this, check out the tracing-subscriber documentation.

Re-exports§

pub use olm::Account;
pub use olm::CrossSigningStatus;
pub use olm::EncryptionSettings;
pub use olm::Session;
pub use store::CrossSigningKeyExport;
pub use store::CryptoStoreError;
pub use store::SecretImportError;
pub use store::SecretInfo;
pub use store::TrackedUser;
pub use vodozemac;
pub use matrix_sdk_qrcode;qrcode

Modules§

backups
Server-side backup support for room keys
dehydrated_devices
Submodule for device dehydration support.
olm
The crypto specific Olm objects.
secret_storage
Helpers for implementing the Secrets Storage mechanism from the Matrix spec.
store
Types and traits to implement the storage layer for the OlmMachine
testingtesting
Testing facilities and helpers for crypto tests
tutorial
A step by step guide that explains how to include end-to-end-encryption support in a Matrix client library.
types
Module containing customized types modeling Matrix keys and events.

Macros§

cryptostore_integration_teststesting
A macro which will run the CryptoStore integration test suite.
cryptostore_integration_tests_timetesting

Structs§

AcceptSettings
Customize the accept-reply for a verification process
AcceptedProtocols
Struct containing the protocols that were agreed to be used for the SAS flow.
AttachmentDecryptor
A wrapper that transparently encrypts anything that implements Read as an Matrix attachment.
AttachmentEncryptor
A wrapper that transparently encrypts anything that implements Read.
CancelInfo
Information about the cancellation of a verification request or verification flow.
CrossSigningBootstrapRequests
A set of requests to be executed when bootstrapping cross-signing using OlmMachine::bootstrap_cross_signing.
DecryptionSettings
Settings for decrypting messages
Device
A device represents a E2EE capable client of an user.
DeviceData
A read-only version of a Device.
Emoji
An emoji that is used for interactive verification using a short auth string.
EmojiShortAuthString
The short auth string for the emoji method of SAS verification.
EncryptionSyncChanges
Data contained from a sync response and that needs to be processed by the OlmMachine.
GossipRequest
A struct describing an outgoing key request.
GossippedSecret
Struct containing a m.secret.send event and its acompanying info.
IdentityStatusChange
A change in the status of the identity of a member of the room. Returned by RoomIdentityState::process_change to indicate that something significant changed in this room and we should either show or hide a warning.
MediaEncryptionInfo
Struct holding all the information that is needed to decrypt an encrypted file.
OlmMachine
State machine implementation of the Olm/Megolm encryption protocol used for Matrix end to end encryption.
OtherUserIdentity
Struct representing a cross signing identity of a user.
OtherUserIdentityData
Struct representing a cross signing identity of a user.
OwnUserIdentity
Struct representing a cross signing identity of a user.
OwnUserIdentityData
Struct representing a cross signing identity of our own user.
QrVerificationqrcode
An object controlling QR code style key verification flows.
RoomIdentityState
The state of the identities in a given room - whether they are:
RoomKeyImportResult
Return type for the room key importing.
Sas
Short authentication string object.
UserDevices
A read only view over all devices belonging to a user.
VerificationRequest
An object controlling key verification requests.

Enums§

CollectStrategy
Strategy to collect the devices that should receive room keys for the current discussion.
DecryptorError
Error type for attachment decryption.
EventError
Error that occurs when decrypting an event that is malformed.
IdentityState
The state of an identity - verified, pinned etc.
KeyExportError
Error representing a failure during key export or import.
LocalTrust
The local trust state of a device.
MegolmError
Error representing a failure during a group encryption operation.
OlmError
Error representing a failure during a device to device cryptographic operation.
QrVerificationStateqrcode
An Enum describing the state the QrCode verification is in.
RoomEventDecryptionResult
The result of an attempt to decrypt a room event: either a successful decryption, or information on a failure.
RoomIdentityChange
The type of update that can be received by RoomIdentityState::process_change - either a change of someone’s identity, or a change of room membership.
SasState
An Enum describing the state the SAS verification is in.
ScanErrorqrcode
An error for the different failure modes that can happen during the validation of a scanned QR code.
SessionCreationError
Error that occurs when a room key can’t be converted into a valid Megolm session.
SessionRecipientCollectionError
Error representing a problem when collecting the recipient devices for the room key, during an encryption operation.
SetRoomSettingsError
Errors that can be returned by crate::machine::OlmMachine::set_room_settings.
SignatureError
Error type describing different errors that happen when we check or create signatures for a Matrix JSON object.
TrustRequirement
The trust level in the sender’s device that is required to decrypt an event.
UserIdentity
Enum over the different user identity types we can have.
UserIdentityData
Enum over the different user identity types we can have.
Verification
An enum over the different verification types the SDK supports.
VerificationRequestState
An Enum describing the state the verification request is in.

Constants§

VERSION
The version of the matrix-sdk-cypto crate being used

Traits§

RoomIdentityProvider
Something that can answer questions about the membership of a room and the identities of users.

Functions§

decrypt_room_key_export
Try to decrypt a reader into a list of exported room keys.
encrypt_room_key_export
Encrypt the list of exported room keys using the given passphrase.
format_emojis
Format the list of emojis as a two line string.