matrix_sdk_crypto::store

Struct Store

Source
pub struct Store { /* private fields */ }
Expand description

A wrapper for our CryptoStore trait object.

This is needed because we want to have a generic interface so we can store/restore objects that we can serialize. Since trait objects and generics don’t mix let the CryptoStore store strings and this wrapper adds the generic interface on top.

Implementations§

Source§

impl Store

Source

pub async fn export_secret( &self, secret_name: &SecretName, ) -> Result<Option<String>, CryptoStoreError>

Try to export the secret with the given secret name.

The exported secret will be encoded as unpadded base64. Returns Null if the secret can’t be found.

§Arguments
  • secret_name - The name of the secret that should be exported.
Source

pub async fn export_cross_signing_keys( &self, ) -> Result<Option<CrossSigningKeyExport>, CryptoStoreError>

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.

Source

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.

Source

pub async fn export_secrets_bundle( &self, ) -> Result<SecretsBundle, SecretsBundleExportError>

Export all the secrets we have in the store into a SecretsBundle.

This method will export all the private cross-signing keys and, if available, the private part of a backup key and its accompanying version.

The method will fail if we don’t have all three private cross-signing keys available.

Warning: Only export this and share it with a trusted recipient, i.e. if an existing device is sharing this with a new device.

Source

pub async fn import_secrets_bundle( &self, bundle: &SecretsBundle, ) -> Result<(), SecretImportError>

Import and persists secrets from a SecretsBundle.

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.

Warning: Only import this from a trusted source, i.e. if an existing device is sharing this with a new device. The imported cross-signing keys will create a OwnUserIdentity and mark it as verified.

The backup key will be persisted in the store and can be enabled using the BackupMachine.

Source

pub async fn import_secret( &self, secret: &GossippedSecret, ) -> Result<(), SecretImportError>

Import the given secret named secret_name into the keystore.

Source

pub async fn get_only_allow_trusted_devices(&self) -> Result<bool>

Check whether there is a global flag to only encrypt messages for trusted devices or for everyone.

Source

pub async fn set_only_allow_trusted_devices( &self, block_untrusted_devices: bool, ) -> Result<()>

Set global flag whether to encrypt messages for untrusted devices, or whether they should be excluded from the conversation.

Source

pub async fn get_value<T: DeserializeOwned>( &self, key: &str, ) -> Result<Option<T>>

Get custom stored value associated with a key

Source

pub async fn set_value(&self, key: &str, value: &impl Serialize) -> Result<()>

Store custom value associated with a key

Source

pub fn room_keys_received_stream( &self, ) -> impl Stream<Item = Result<Vec<RoomKeyInfo>, BroadcastStreamRecvError>>

Receive notifications of room keys being received as a Stream.

Each time a room key is updated in any way, an update will be sent to the stream. Updates that happen at the same time are batched into a Vec.

If the reader of the stream lags too far behind an error will be sent to the reader.

The stream will terminate once all references to the underlying CryptoStoreWrapper are dropped.

Source

pub fn room_keys_withheld_received_stream( &self, ) -> impl Stream<Item = Vec<RoomKeyWithheldInfo>>

Receive notifications of received m.room_key.withheld messages.

Each time an m.room_key.withheld is received and stored, an update will be sent to the stream. Updates that happen at the same time are batched into a Vec.

If the reader of the stream lags too far behind, a warning will be logged and items will be dropped.

Source

pub fn user_identities_stream(&self) -> impl Stream<Item = IdentityUpdates>

Returns a stream of user identity updates, allowing users to listen for notifications about new or changed user identities.

The stream produced by this method emits updates whenever a new user identity is discovered or when an existing identities information is changed. Users can subscribe to this stream and receive updates in real-time.

Caution: the returned stream will never terminate, and it holds a reference to the CryptoStore. Listeners should be careful to avoid resource leaks.

§Examples
let identities_stream = machine.store().user_identities_stream();
pin_mut!(identities_stream);

for identity_updates in identities_stream.next().await {
    for (_, identity) in identity_updates.new {
        println!("A new identity has been added {}", identity.user_id());
    }
}
Source

pub fn devices_stream(&self) -> impl Stream<Item = DeviceUpdates>

Returns a stream of device updates, allowing users to listen for notifications about new or changed devices.

The stream produced by this method emits updates whenever a new device is discovered or when an existing device’s information is changed. Users can subscribe to this stream and receive updates in real-time.

Caution: the returned stream will never terminate, and it holds a reference to the CryptoStore. Listeners should be careful to avoid resource leaks.

§Examples
let devices_stream = machine.store().devices_stream();
pin_mut!(devices_stream);

for device_updates in devices_stream.next().await {
    if let Some(user_devices) = device_updates.new.get(machine.user_id()) {
        for device in user_devices.values() {
            println!("A new device has been added {}", device.device_id());
        }
    }
}
Source

pub fn identities_stream_raw( &self, ) -> impl Stream<Item = (IdentityChanges, DeviceChanges)>

Returns a Stream of user identity and device updates

The stream returned by this method returns the same data as Store::user_identities_stream and Store::devices_stream but does not include references to the VerificationMachine. It is therefore a lower-level view on that data.

The stream will terminate once all references to the underlying CryptoStoreWrapper are dropped.

Source

pub fn create_store_lock( &self, lock_key: String, lock_value: String, ) -> CrossProcessStoreLock<LockableCryptoStore>

Creates a CrossProcessStoreLock for this store, that will contain the given key and value when hold.

Source

pub fn secrets_stream(&self) -> impl Stream<Item = GossippedSecret>

Receive notifications of gossipped secrets being received and stored in the secret inbox as a Stream.

The gossipped secrets are received using the m.secret.send event type and are guaranteed to have been received over a 1-to-1 Olm Session from a verified Device.

The GossippedSecret can also be later found in the secret inbox and retrieved using the CryptoStore::get_secrets_from_inbox() method.

After a suitable secret of a certain type has been found it can be removed from the store using the CryptoStore::delete_secrets_from_inbox() method.

The only secret this will currently broadcast is the m.megolm_backup.v1.

If the reader of the stream lags too far behind, a warning will be logged and items will be dropped.

§Examples

let secret_stream = machine.store().secrets_stream();
pin_mut!(secret_stream);

for secret in secret_stream.next().await {
    // Accept the secret if it's valid, then delete all the secrets of this type.
    machine.store().delete_secrets_from_inbox(&secret.secret_name);
}
Source

pub async fn import_room_keys( &self, exported_keys: Vec<ExportedRoomKey>, from_backup_version: Option<&str>, progress_listener: impl Fn(usize, usize), ) -> Result<RoomKeyImportResult>

Import the given room keys into the store.

§Arguments
  • exported_keys - The keys to be imported.
  • from_backup_version - If the keys came from key backup, the key backup version. This will cause the keys to be marked as already backed up, and therefore not requiring another backup.
  • progress_listener - Callback which will be called after each key is processed. Called with arguments (processed, total) where processed is the number of keys processed so far, and total is the total number of keys (i.e., exported_keys.len()).
Source

pub async fn import_exported_room_keys( &self, exported_keys: Vec<ExportedRoomKey>, progress_listener: impl Fn(usize, usize), ) -> Result<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.

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_room_key_export(export, "1234").unwrap();
machine.store().import_exported_room_keys(exported_keys, |_, _| {}).await.unwrap();
Source

pub async fn export_room_keys( &self, predicate: impl FnMut(&InboundGroupSession) -> bool, ) -> Result<Vec<ExportedRoomKey>>

Export the keys that match the given predicate.

§Arguments
  • predicate - A closure that will be called for every known InboundGroupSession, which represents a room key. If the closure returns true the InboundGroupSession will be included in the export, if the closure returns false it will not be included.
§Examples
let room_id = room_id!("!test:localhost");
let exported_keys = machine.store().export_room_keys(|s| s.room_id() == room_id).await.unwrap();
let encrypted_export = encrypt_room_key_export(&exported_keys, "1234", 1);
Source

pub async fn export_room_keys_stream( &self, predicate: impl FnMut(&InboundGroupSession) -> bool, ) -> Result<impl Stream<Item = ExportedRoomKey>>

Export room keys matching a predicate, providing them as an async Stream.

§Arguments
  • predicate - A closure that will be called for every known InboundGroupSession, which represents a room key. If the closure returns true the InboundGroupSession will be included in the export, if the closure returns false it will not be included.
§Examples
use std::pin::pin;

use matrix_sdk_crypto::{olm::ExportedRoomKey, OlmMachine};
use ruma::{device_id, room_id, user_id};
use tokio_stream::StreamExt;
let alice = user_id!("@alice:example.org");
let machine = OlmMachine::new(&alice, device_id!("DEVICEID")).await;
let room_id = room_id!("!test:localhost");
let mut keys = pin!(machine
    .store()
    .export_room_keys_stream(|s| s.room_id() == room_id)
    .await
    .unwrap());
while let Some(key) = keys.next().await {
    println!("{}", key.room_id);
}

Trait Implementations§

Source§

impl Clone for Store

Source§

fn clone(&self) -> Store

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Store

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for Store

Source§

type Target = dyn CryptoStore<Error = CryptoStoreError>

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.

Auto Trait Implementations§

§

impl Freeze for Store

§

impl !RefUnwindSafe for Store

§

impl Send for Store

§

impl Sync for Store

§

impl Unpin for Store

§

impl !UnwindSafe for Store

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
§

impl<T> CompatExt for T

§

fn compat(self) -> Compat<T>

Applies the [Compat] adapter by value. Read more
§

fn compat_ref(&self) -> Compat<&T>

Applies the [Compat] adapter by shared reference. Read more
§

fn compat_mut(&mut self) -> Compat<&mut T>

Applies the [Compat] adapter by mutable reference. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, UT> HandleAlloc<UT> for T
where T: Send + Sync,

Source§

fn new_handle(value: Arc<T>) -> Handle

Create a new handle for an Arc value Read more
Source§

fn clone_handle(handle: Handle) -> Handle

Clone a handle Read more
Source§

fn consume_handle(handle: Handle) -> Arc<T>

Consume a handle, getting back the initial Arc<>
Source§

fn get_arc(handle: Handle) -> Arc<Self>

Get a clone of the Arc<> using a “borrowed” handle. Read more
Source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

Source§

const WITNESS: W = W::MAKE

A constant of the type witness
Source§

impl<T> Identity for T
where T: ?Sized,

Source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
Source§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
Available on non-bootstrap only.
The target type on which the method may be called.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
Source§

impl<T> AsyncTraitDeps for T

Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T

Source§

impl<T> SendOutsideWasm for T
where T: Send,

Source§

impl<T> SyncOutsideWasm for T
where T: Sync,