Struct matrix_sdk_crypto::OlmMachine
source · [−]pub struct OlmMachine { /* private fields */ }
Expand description
State machine implementation of the Olm/Megolm encryption protocol used for Matrix end to end encryption.
Implementations
sourceimpl OlmMachine
impl OlmMachine
sourcepub async fn new(user_id: &UserId, device_id: &DeviceId) -> Self
pub async fn new(user_id: &UserId, device_id: &DeviceId) -> Self
Create a new memory based OlmMachine.
The created machine will keep the encryption keys only in memory and once the object is dropped the keys will be lost.
Arguments
-
user_id
- The unique id of the user that owns this machine. -
device_id
- The unique id of the device that owns this machine.
sourcepub async fn with_store(
user_id: &UserId,
device_id: &DeviceId,
store: Arc<dyn CryptoStore>
) -> StoreResult<Self>
pub async fn with_store(
user_id: &UserId,
device_id: &DeviceId,
store: Arc<dyn CryptoStore>
) -> StoreResult<Self>
Create a new OlmMachine with the given CryptoStore
.
The created machine will keep the encryption keys only in memory and once the object is dropped the keys will be lost.
If the store already contains encryption keys for the given user/device pair those will be re-used. Otherwise new ones will be created and stored.
Arguments
-
user_id
- The unique id of the user that owns this machine. -
device_id
- The unique id of the device that owns this machine. -
store
- ACryptostore
implementation that will be used to store the encryption keys.
sourcepub fn identity_keys(&self) -> IdentityKeys
pub fn identity_keys(&self) -> IdentityKeys
Get the public parts of our Olm identity keys.
sourcepub async fn display_name(&self) -> StoreResult<Option<String>>
pub async fn display_name(&self) -> StoreResult<Option<String>>
Get the display name of our own device
sourcepub fn tracked_users(&self) -> HashSet<OwnedUserId>
pub fn tracked_users(&self) -> HashSet<OwnedUserId>
Get all the tracked users we know about
sourcepub async fn outgoing_requests(&self) -> StoreResult<Vec<OutgoingRequest>>
pub async fn outgoing_requests(&self) -> StoreResult<Vec<OutgoingRequest>>
Get the outgoing requests that need to be sent out.
This returns a list of OutGoingRequest
, those requests need to be sent
out to the server and the responses need to be passed back to the state
machine using mark_request_as_sent
.
sourcepub async fn mark_request_as_sent<'a>(
&self,
request_id: &TransactionId,
response: impl Into<IncomingResponse<'a>>
) -> Result<(), OlmError>
pub async fn mark_request_as_sent<'a>(
&self,
request_id: &TransactionId,
response: impl Into<IncomingResponse<'a>>
) -> Result<(), OlmError>
Mark the request with the given request id as sent.
Arguments
-
request_id
- The unique id of the request that was sent out. This is needed to couple the response with the now sent out request. -
response
- The response that was received from the server after the outgoing request was sent out.
sourcepub async fn bootstrap_cross_signing(
&self,
reset: bool
) -> StoreResult<(UploadSigningKeysRequest, UploadSignaturesRequest)>
pub async fn bootstrap_cross_signing(
&self,
reset: bool
) -> StoreResult<(UploadSigningKeysRequest, UploadSignaturesRequest)>
Create a new cross signing identity and get the upload request to push the new public keys to the server.
Warning: This will delete any existing cross signing keys that might exist on the server and thus will reset the trust between all the devices.
Uploading these keys will require user interactive auth.
sourcepub async fn get_missing_sessions(
&self,
users: impl Iterator<Item = &UserId>
) -> StoreResult<Option<(OwnedTransactionId, KeysClaimRequest)>>
pub async fn get_missing_sessions(
&self,
users: impl Iterator<Item = &UserId>
) -> StoreResult<Option<(OwnedTransactionId, KeysClaimRequest)>>
Get the a key claiming request for the user/device pairs that we are missing Olm sessions for.
Returns None if no key claiming request needs to be sent out.
Sessions need to be established between devices so group sessions for a room can be shared with them.
This should be called every time a group session needs to be shared as well as between sync calls. After a sync some devices may request room keys without us having a valid Olm session with them, making it impossible to server the room key request, thus it’s necessary to check for missing sessions between sync as well.
Note: Care should be taken that only one such request at a time is in flight, e.g. using a lock.
The response of a successful key claiming requests needs to be passed to
the OlmMachine
with the mark_request_as_sent
.
Arguments
users
- The list of users that we should check if we lack a session
with one of their devices. This can be an empty iterator when calling
this method between sync requests.
sourcepub async fn encrypt_room_event(
&self,
room_id: &RoomId,
content: impl MessageLikeEventContent
) -> Result<RoomEncryptedEventContent, MegolmError>
pub async fn encrypt_room_event(
&self,
room_id: &RoomId,
content: impl MessageLikeEventContent
) -> Result<RoomEncryptedEventContent, MegolmError>
Encrypt a room message for the given room.
Beware that a room key needs to be shared before this method
can be called using the OlmMachine::share_room_key
method.
Arguments
-
room_id
- The id of the room for which the message should be encrypted. -
content
- The plaintext content of the message that should be encrypted.
Panics
Panics if a room key for the given room wasn’t shared beforehand.
sourcepub async fn encrypt_room_event_raw(
&self,
room_id: &RoomId,
content: Value,
event_type: &str
) -> Result<RoomEncryptedEventContent, MegolmError>
pub async fn encrypt_room_event_raw(
&self,
room_id: &RoomId,
content: Value,
event_type: &str
) -> Result<RoomEncryptedEventContent, MegolmError>
Encrypt a json Value
content for the given room.
This method is equivalent to the OlmMachine::encrypt_room_event()
method but operates on an arbitrary JSON value instead of strongly-typed
event content struct.
Arguments
-
room_id
- The id of the room for which the message should be encrypted. -
content
- The plaintext content of the message that should be encrypted as a jsonValue
. -
event_type
- The plaintext type of the event.
Panics
Panics if a group session for the given room wasn’t shared beforehand.
sourcepub async fn invalidate_group_session(
&self,
room_id: &RoomId
) -> StoreResult<bool>
pub async fn invalidate_group_session(
&self,
room_id: &RoomId
) -> StoreResult<bool>
Invalidate the currently active outbound group session for the given room.
Returns true if a session was invalidated, false if there was no session to invalidate.
Get to-device requests to share a room key with users in a room.
Arguments
room_id
- The room id of the room where the room key will be
used.
users
- The list of users that should receive the room key.
sourcepub async fn receive_unencrypted_verification_event(
&self,
event: &AnyMessageLikeEvent
) -> StoreResult<()>
pub async fn receive_unencrypted_verification_event(
&self,
event: &AnyMessageLikeEvent
) -> StoreResult<()>
Receive an unencrypted verification event.
This method can be used to pass verification events that are happening
in unencrypted rooms to the OlmMachine
.
Note: This does not need to be called for encrypted events since
those will get passed to the OlmMachine
during decryption.
sourcepub fn get_verification(
&self,
user_id: &UserId,
flow_id: &str
) -> Option<Verification>
pub fn get_verification(
&self,
user_id: &UserId,
flow_id: &str
) -> Option<Verification>
Get a verification object for the given user id with the given flow id.
sourcepub fn get_verification_request(
&self,
user_id: &UserId,
flow_id: impl AsRef<str>
) -> Option<VerificationRequest>
pub fn get_verification_request(
&self,
user_id: &UserId,
flow_id: impl AsRef<str>
) -> Option<VerificationRequest>
Get a verification request object with the given flow id.
sourcepub fn get_verification_requests(
&self,
user_id: &UserId
) -> Vec<VerificationRequest>ⓘNotable traits for Vec<u8, A>impl<A> Write for Vec<u8, A> where
A: Allocator,
pub fn get_verification_requests(
&self,
user_id: &UserId
) -> Vec<VerificationRequest>ⓘNotable traits for Vec<u8, A>impl<A> Write for Vec<u8, A> where
A: Allocator,
A: Allocator,
Get all the verification requests of a given user.
sourcepub async fn receive_sync_changes(
&self,
to_device_events: ToDevice,
changed_devices: &DeviceLists,
one_time_keys_counts: &BTreeMap<DeviceKeyAlgorithm, UInt>,
unused_fallback_keys: Option<&[DeviceKeyAlgorithm]>
) -> Result<ToDevice, OlmError>
pub async fn receive_sync_changes(
&self,
to_device_events: ToDevice,
changed_devices: &DeviceLists,
one_time_keys_counts: &BTreeMap<DeviceKeyAlgorithm, UInt>,
unused_fallback_keys: Option<&[DeviceKeyAlgorithm]>
) -> Result<ToDevice, OlmError>
Handle a to-device and one-time key counts from a sync response.
This will decrypt and handle to-device events returning the decrypted versions of them.
To decrypt an event from the room timeline call decrypt_room_event
.
Arguments
-
to_device_events
- The to-device events of the current sync response. -
changed_devices
- The list of devices that changed in this sync response. -
one_time_keys_count
- The current one-time keys counts that the sync response returned.
sourcepub async fn request_room_key(
&self,
event: &OriginalSyncRoomEncryptedEvent,
room_id: &RoomId
) -> Result<(Option<OutgoingRequest>, OutgoingRequest), MegolmError>
pub async fn request_room_key(
&self,
event: &OriginalSyncRoomEncryptedEvent,
room_id: &RoomId
) -> Result<(Option<OutgoingRequest>, OutgoingRequest), MegolmError>
Request a room key from our devices.
This method will return a request cancellation and a new key request if the key was already requested, otherwise it will return just the key request.
The request cancellation must be sent out before the request is sent out, otherwise devices will ignore the key request.
Arguments
-
room_id
- The id of the room where the key is used in. -
sender_key
- The curve25519 key of the sender that owns the key. -
session_id
- The id that uniquely identifies the session.
sourcepub async fn decrypt_room_event(
&self,
event: &OriginalSyncRoomEncryptedEvent,
room_id: &RoomId
) -> Result<RoomEvent, MegolmError>
pub async fn decrypt_room_event(
&self,
event: &OriginalSyncRoomEncryptedEvent,
room_id: &RoomId
) -> Result<RoomEvent, MegolmError>
Decrypt an event from a room timeline.
Arguments
-
event
- The event that should be decrypted. -
room_id
- The ID of the room where the event was sent to.
sourcepub async fn update_tracked_users(
&self,
users: impl IntoIterator<Item = &UserId>
)
pub async fn update_tracked_users(
&self,
users: impl IntoIterator<Item = &UserId>
)
Update the tracked users.
Arguments
users
- An iterator over user ids that should be marked for tracking.
This will mark users that weren’t seen before for a key query and tracking.
If the user is already known to the Olm machine it will not be considered for a key query.
sourcepub async fn get_device(
&self,
user_id: &UserId,
device_id: &DeviceId,
timeout: Option<Duration>
) -> StoreResult<Option<Device>>
pub async fn get_device(
&self,
user_id: &UserId,
device_id: &DeviceId,
timeout: Option<Duration>
) -> StoreResult<Option<Device>>
Get a specific device of a user.
Arguments
-
user_id
- The unique id of the user that the device belongs to. -
device_id
- The unique id of the device. -
timeout
- The amount of time we should wait before returning if the user’s device list has been marked as stale. Note, this assumes that the requests fromOlmMachine::outgoing_requests
are being processed and sent out.
Returns a Device
if one is found and the crypto store didn’t throw an
error.
Example
let device = machine.get_device(&alice, device_id!("DEVICEID"), None).await;
println!("{:?}", device);
sourcepub async fn get_identity(
&self,
user_id: &UserId,
timeout: Option<Duration>
) -> StoreResult<Option<UserIdentities>>
pub async fn get_identity(
&self,
user_id: &UserId,
timeout: Option<Duration>
) -> StoreResult<Option<UserIdentities>>
Get the cross signing user identity of a user.
Arguments
-
user_id
- The unique id of the user that the identity belongs to -
timeout
- The amount of time we should wait before returning if the user’s device list has been marked as stale. Note, this assumes that the requests fromOlmMachine::outgoing_requests
are being processed and sent out.
Returns a UserIdentities
enum if one is found and the crypto store
didn’t throw an error.
sourcepub async fn get_user_devices(
&self,
user_id: &UserId,
timeout: Option<Duration>
) -> StoreResult<UserDevices>
pub async fn get_user_devices(
&self,
user_id: &UserId,
timeout: Option<Duration>
) -> StoreResult<UserDevices>
Get a map holding all the devices of an user.
Arguments
-
user_id
- The unique id of the user that the devices belong to. -
timeout
- The amount of time we should wait before returning if the user’s device list has been marked as stale. Note, this assumes that the requests fromOlmMachine::outgoing_requests
are being processed and sent out.
Example
let devices = machine.get_user_devices(&alice, None).await.unwrap();
for device in devices.devices() {
println!("{:?}", device);
}
sourcepub async fn import_keys(
&self,
exported_keys: Vec<ExportedRoomKey>,
from_backup: bool,
progress_listener: impl Fn(usize, usize)
) -> StoreResult<RoomKeyImportResult>
pub async fn import_keys(
&self,
exported_keys: Vec<ExportedRoomKey>,
from_backup: bool,
progress_listener: impl Fn(usize, usize)
) -> StoreResult<RoomKeyImportResult>
Import the given room keys into our store.
Arguments
-
exported_keys
- A list of previously exported keys that should be imported into our store. If we already have a better version of a key the key will not be imported. -
from_backup
- Were the room keys imported from the backup, if true will mark the room keys as already backed up. This will prevent backing up keys that are already backed up.
Returns a tuple of numbers that represent the number of sessions that were imported and the total number of sessions that were found in the key export.
Examples
let exported_keys = decrypt_key_export(export, "1234").unwrap();
machine.import_keys(exported_keys, false, |_, _| {}).await.unwrap();
sourcepub async fn export_keys(
&self,
predicate: impl FnMut(&InboundGroupSession) -> bool
) -> StoreResult<Vec<ExportedRoomKey>>
pub async fn export_keys(
&self,
predicate: impl FnMut(&InboundGroupSession) -> bool
) -> StoreResult<Vec<ExportedRoomKey>>
Export the keys that match the given predicate.
Arguments
predicate
- A closure that will be called for every knownInboundGroupSession
, which represents a room key. If the closure returnstrue
theInboundGroupSession
will be included in the export, if the closure returnsfalse
it will not be included.
Panics
This method will panic if it can’t get enough randomness from the OS to encrypt the exported keys securely.
Examples
let room_id = room_id!("!test:localhost");
let exported_keys = machine.export_keys(|s| s.room_id() == room_id).await.unwrap();
let encrypted_export = encrypt_key_export(&exported_keys, "1234", 1);
sourcepub async fn cross_signing_status(&self) -> CrossSigningStatus
pub async fn cross_signing_status(&self) -> CrossSigningStatus
Get the status of the private cross signing keys.
This can be used to check which private cross signing keys we have stored locally.
sourcepub async fn export_cross_signing_keys(&self) -> Option<CrossSigningKeyExport>
pub async fn export_cross_signing_keys(&self) -> Option<CrossSigningKeyExport>
Export all the private cross signing keys we have.
The export will contain the seed for the ed25519 keys as a unpadded base64 encoded string.
This method returns None
if we don’t have any private cross signing
keys.
sourcepub async fn import_cross_signing_keys(
&self,
export: CrossSigningKeyExport
) -> Result<CrossSigningStatus, SecretImportError>
pub async fn import_cross_signing_keys(
&self,
export: CrossSigningKeyExport
) -> Result<CrossSigningStatus, SecretImportError>
Import our private cross signing keys.
The export needs to contain the seed for the ed25519 keys as an unpadded base64 encoded string.
sourcepub async fn sign(&self, message: &str) -> Signatures
pub async fn sign(&self, message: &str) -> Signatures
Sign the given message using our device key and if available cross signing master key.
Presently, this should only be used for signing the server-side room key backups.
Trait Implementations
sourceimpl Clone for OlmMachine
impl Clone for OlmMachine
sourcefn clone(&self) -> OlmMachine
fn clone(&self) -> OlmMachine
Returns a copy of the value. Read more
1.0.0 · sourcefn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source
. Read more
Auto Trait Implementations
impl !RefUnwindSafe for OlmMachine
impl Send for OlmMachine
impl Sync for OlmMachine
impl Unpin for OlmMachine
impl !UnwindSafe for OlmMachine
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
sourcefn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
sourceimpl<T> WithSubscriber for T
impl<T> WithSubscriber for T
sourcefn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
Attaches the provided Subscriber
to this type, returning a
WithDispatch
wrapper. Read more
sourcefn with_current_subscriber(self) -> WithDispatch<Self>
fn with_current_subscriber(self) -> WithDispatch<Self>
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more