From 8079da7b0a62e4b539b20f66f401674faeb4067d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Thu, 24 Mar 2022 10:10:53 +0100 Subject: [PATCH] chore(crypto-ffi): Use the the latest matrix-sdk-crypto crate. --- crates/matrix-crypto-ffi/Cargo.toml | 16 +++-- .../src/backup_recovery_key.rs | 4 +- crates/matrix-crypto-ffi/src/device.rs | 2 +- crates/matrix-crypto-ffi/src/error.rs | 10 +-- crates/matrix-crypto-ffi/src/machine.rs | 69 ++++++++++++------- crates/matrix-crypto-ffi/src/olm.udl | 2 +- crates/matrix-crypto-ffi/src/responses.rs | 35 +++++----- crates/matrix-crypto-ffi/src/users.rs | 13 ++-- crates/matrix-crypto-ffi/src/verification.rs | 4 +- 9 files changed, 88 insertions(+), 67 deletions(-) diff --git a/crates/matrix-crypto-ffi/Cargo.toml b/crates/matrix-crypto-ffi/Cargo.toml index 22cbac2ab..21f5fc19f 100644 --- a/crates/matrix-crypto-ffi/Cargo.toml +++ b/crates/matrix-crypto-ffi/Cargo.toml @@ -9,6 +9,7 @@ crate-type = ["cdylib", "lib"] name = "matrix_crypto" [dependencies] +anyhow = "1.0.56" base64 = "0.13.0" hmac = "0.11.0" http = "0.2.4" @@ -27,13 +28,16 @@ version = "0.2.1" features = ["lax_deserialize"] [dependencies.matrix-sdk-common] -git = "https://github.com/matrix-org/matrix-rust-sdk/" -rev = "009ead2eeaf365e1fb0f790557f20d4eaf6874ae" +path = "../matrix-sdk-common" [dependencies.matrix-sdk-crypto] -git = "https://github.com/matrix-org/matrix-rust-sdk/" -rev = "009ead2eeaf365e1fb0f790557f20d4eaf6874ae" -features = ["sled_cryptostore", "qrcode", "backups_v1"] +path = "../matrix-sdk-crypto" +features = ["qrcode", "backups_v1"] + +[dependencies.matrix-sdk-sled] +path = "../matrix-sdk-sled" +default_features = false +features = ["crypto-store"] [dependencies.tokio] version = "1.7.1" @@ -42,7 +46,7 @@ features = ["rt-multi-thread"] [dependencies.ruma] git = "https://github.com/ruma/ruma" -rev = "fdbc4d6d1dd273c8a6ac95b329943ed8c68df70d" +rev = "deea762b8" features = ["client-api-c"] [build-dependencies] diff --git a/crates/matrix-crypto-ffi/src/backup_recovery_key.rs b/crates/matrix-crypto-ffi/src/backup_recovery_key.rs index fe790018c..ad14200d6 100644 --- a/crates/matrix-crypto-ffi/src/backup_recovery_key.rs +++ b/crates/matrix-crypto-ffi/src/backup_recovery_key.rs @@ -2,8 +2,8 @@ use std::{collections::HashMap, iter}; use hmac::Hmac; use matrix_sdk_crypto::{ - backups::{OlmPkDecryptionError, RecoveryKey}, - store::CryptoStoreError as InnerStoreError, + backups::OlmPkDecryptionError, + store::{CryptoStoreError as InnerStoreError, RecoveryKey}, }; use pbkdf2::pbkdf2; use rand::{distributions::Alphanumeric, thread_rng, Rng}; diff --git a/crates/matrix-crypto-ffi/src/device.rs b/crates/matrix-crypto-ffi/src/device.rs index c21b4be76..ed8ae0e3a 100644 --- a/crates/matrix-crypto-ffi/src/device.rs +++ b/crates/matrix-crypto-ffi/src/device.rs @@ -31,7 +31,7 @@ impl From for Device { Device { user_id: d.user_id().to_string(), device_id: d.device_id().to_string(), - keys: d.keys().iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(), + keys: d.keys().iter().map(|(k, v)| (k.to_string(), v.to_base64())).collect(), algorithms: d.algorithms().iter().map(|a| a.to_string()).collect(), display_name: d.display_name().map(|d| d.to_owned()), is_blocked: d.is_blacklisted(), diff --git a/crates/matrix-crypto-ffi/src/error.rs b/crates/matrix-crypto-ffi/src/error.rs index a86b39bf7..c8ddb8a23 100644 --- a/crates/matrix-crypto-ffi/src/error.rs +++ b/crates/matrix-crypto-ffi/src/error.rs @@ -4,7 +4,7 @@ use matrix_sdk_crypto::{ store::CryptoStoreError as InnerStoreError, KeyExportError, MegolmError, OlmError, SecretImportError as RustSecretImportError, SignatureError as InnerSignatureError, }; -use ruma::{identifiers::Error as RumaIdentifierError, UserId}; +use ruma::{IdParseError, UserId}; #[derive(Debug, thiserror::Error)] pub enum KeyImportError { @@ -29,7 +29,7 @@ pub enum SignatureError { #[error(transparent)] Signature(#[from] InnerSignatureError), #[error(transparent)] - Identifier(#[from] RumaIdentifierError), + Identifier(#[from] IdParseError), #[error(transparent)] CryptoStore(#[from] InnerStoreError), #[error("Unknown device {0} {1}")] @@ -47,9 +47,9 @@ pub enum CryptoStoreError { #[error(transparent)] Serialization(#[from] serde_json::Error), #[error("The given string is not a valid user ID: source {0}, error {1}")] - InvalidUserId(String, RumaIdentifierError), + InvalidUserId(String, IdParseError), #[error(transparent)] - Identifier(#[from] RumaIdentifierError), + Identifier(#[from] IdParseError), } #[derive(Debug, thiserror::Error)] @@ -57,7 +57,7 @@ pub enum DecryptionError { #[error(transparent)] Serialization(#[from] serde_json::Error), #[error(transparent)] - Identifier(#[from] RumaIdentifierError), + Identifier(#[from] IdParseError), #[error(transparent)] Megolm(#[from] MegolmError), } diff --git a/crates/matrix-crypto-ffi/src/machine.rs b/crates/matrix-crypto-ffi/src/machine.rs index 2c3c6cee3..797d0c6ed 100644 --- a/crates/matrix-crypto-ffi/src/machine.rs +++ b/crates/matrix-crypto-ffi/src/machine.rs @@ -5,36 +5,36 @@ use std::{ ops::Deref, }; +use anyhow::anyhow; use base64::{decode_config, encode, STANDARD_NO_PAD}; use js_int::UInt; -use matrix_sdk_common::{deserialized_responses::AlgorithmInfo, uuid::Uuid}; +use matrix_sdk_common::deserialized_responses::AlgorithmInfo; use matrix_sdk_crypto::{ - backups::{MegolmV1BackupKey as RustBackupKey, RecoveryKey}, - decrypt_key_export, encrypt_key_export, - matrix_qrcode::QrVerificationData, - olm::ExportedRoomKey, + backups::MegolmV1BackupKey as RustBackupKey, decrypt_key_export, encrypt_key_export, + matrix_qrcode::QrVerificationData, olm::ExportedRoomKey, store::RecoveryKey, EncryptionSettings, LocalTrust, OlmMachine as InnerMachine, UserIdentities, Verification as RustVerification, }; use ruma::{ api::{ - client::r0::{ - backup::add_backup_keys::Response as KeysBackupResponse, + client::{ + backup::add_backup_keys::v3::Response as KeysBackupResponse, keys::{ - claim_keys::Response as KeysClaimResponse, get_keys::Response as KeysQueryResponse, - upload_keys::Response as KeysUploadResponse, - upload_signatures::Response as SignatureUploadResponse, + claim_keys::v3::Response as KeysClaimResponse, + get_keys::v3::Response as KeysQueryResponse, + upload_keys::v3::Response as KeysUploadResponse, + upload_signatures::v3::Response as SignatureUploadResponse, }, - sync::sync_events::{DeviceLists as RumaDeviceLists, ToDevice}, - to_device::send_event_to_device::Response as ToDeviceResponse, + sync::sync_events::v3::{DeviceLists as RumaDeviceLists, ToDevice}, + to_device::send_event_to_device::v3::Response as ToDeviceResponse, }, IncomingResponse, }, events::{ key::verification::VerificationMethod, room::encrypted::RoomEncryptedEventContent, - AnyMessageEventContent, EventContent, SyncMessageEvent, + AnyMessageLikeEventContent, EventContent, SyncMessageLikeEvent, }, - DeviceKeyAlgorithm, EventId, RoomId, UserId, + DeviceKeyAlgorithm, EventId, RoomId, TransactionId, UserId, }; use serde::{Deserialize, Serialize}; use serde_json::{value::RawValue, Value}; @@ -82,9 +82,22 @@ impl OlmMachine { let device_id = device_id.into(); let runtime = Runtime::new().expect("Couldn't create a tokio runtime"); + let store = + Box::new(matrix_sdk_sled::CryptoStore::open_with_passphrase(path, None).map_err( + |e| match e { + // This is a bit of an error in the sled store, the + // CryptoStore returns an `OpenStoreError` which has a + // variant for the state store. Not sure what to do about + // this. + matrix_sdk_sled::OpenStoreError::Crypto(r) => r.into(), + matrix_sdk_sled::OpenStoreError::Sled(s) => { + CryptoStoreError::CryptoStore(anyhow!(s).into()) + } + }, + )?); + Ok(OlmMachine { - inner: runtime - .block_on(InnerMachine::new_with_default_store(&user_id, device_id, path, None))?, + inner: runtime.block_on(InnerMachine::with_store(user_id, device_id, store))?, runtime, }) } @@ -239,7 +252,11 @@ impl OlmMachine { /// Get our own identity keys. pub fn identity_keys(&self) -> HashMap { - self.inner.identity_keys().iter().map(|(k, v)| (k.to_owned(), v.to_owned())).collect() + let identity_keys = self.inner.identity_keys(); + let curve_key = identity_keys.curve25519.to_base64(); + let ed25519_key = identity_keys.ed25519.to_base64(); + + HashMap::from([("ed25519".to_owned(), ed25519_key), ("curve25519".to_owned(), curve_key)]) } /// Get the list of outgoing requests that need to be sent to the @@ -275,7 +292,7 @@ impl OlmMachine { request_type: RequestType, response_body: &str, ) -> Result<(), CryptoStoreError> { - let id = Uuid::parse_str(request_id).expect("Can't parse request id"); + let id: Box = request_id.into(); let response = response_from_string(response_body); @@ -485,7 +502,7 @@ impl OlmMachine { let room_id = Box::::try_from(room_id)?; let content: Box = serde_json::from_str(content)?; - let content = AnyMessageEventContent::from_parts(event_type, &content)?; + let content = AnyMessageLikeEventContent::from_parts(event_type, &content)?; let encrypted_content = self .runtime .block_on(self.inner.encrypt(&room_id, content)) @@ -517,7 +534,7 @@ impl OlmMachine { content: &'a RawValue, } - let event: SyncMessageEvent = serde_json::from_str(event)?; + let event: SyncMessageLikeEvent = serde_json::from_str(event)?; let room_id = Box::::try_from(room_id)?; let decrypted = self.runtime.block_on(self.inner.decrypt_room_event(&event, &room_id))?; @@ -555,7 +572,7 @@ impl OlmMachine { event: &str, room_id: &str, ) -> Result { - let event: SyncMessageEvent = serde_json::from_str(event)?; + let event: SyncMessageLikeEvent = serde_json::from_str(event)?; let room_id = Box::::try_from(room_id)?; let (cancel, request) = @@ -954,15 +971,17 @@ impl OlmMachine { Ok(if let Some(verification) = self.inner.get_verification(&user_id, flow_id) { match verification { RustVerification::SasV1(v) => { - let (request, signature_request) = self.runtime.block_on(v.confirm())?; + let (requests, signature_request) = self.runtime.block_on(v.confirm())?; - request.map(|r| ConfirmVerificationResult { - request: r.into(), + let requests = requests.into_iter().map(|r| r.into()).collect(); + + Some(ConfirmVerificationResult { + requests, signature_request: signature_request.map(|s| s.into()), }) } RustVerification::QrV1(v) => v.confirm_scanning().map(|r| { - ConfirmVerificationResult { request: r.into(), signature_request: None } + ConfirmVerificationResult { requests: vec![r.into()], signature_request: None } }), } } else { diff --git a/crates/matrix-crypto-ffi/src/olm.udl b/crates/matrix-crypto-ffi/src/olm.udl index b93a39823..ea16aa2d9 100644 --- a/crates/matrix-crypto-ffi/src/olm.udl +++ b/crates/matrix-crypto-ffi/src/olm.udl @@ -189,7 +189,7 @@ dictionary RequestVerificationResult { }; dictionary ConfirmVerificationResult { - OutgoingVerificationRequest request; + sequence requests; SignatureUploadRequest? signature_request; }; diff --git a/crates/matrix-crypto-ffi/src/responses.rs b/crates/matrix-crypto-ffi/src/responses.rs index d7184edc9..d26865e4a 100644 --- a/crates/matrix-crypto-ffi/src/responses.rs +++ b/crates/matrix-crypto-ffi/src/responses.rs @@ -3,28 +3,27 @@ use std::{collections::HashMap, convert::TryFrom}; use http::Response; -use matrix_sdk_common::uuid::Uuid; use matrix_sdk_crypto::{ IncomingResponse, OutgoingRequest, OutgoingVerificationRequest as SdkVerificationRequest, RoomMessageRequest, ToDeviceRequest, UploadSigningKeysRequest as RustUploadSigningKeysRequest, }; use ruma::{ - api::client::r0::{ - backup::add_backup_keys::Response as KeysBackupResponse, + api::client::{ + backup::add_backup_keys::v3::Response as KeysBackupResponse, keys::{ - claim_keys::{Request as KeysClaimRequest, Response as KeysClaimResponse}, - get_keys::Response as KeysQueryResponse, - upload_keys::Response as KeysUploadResponse, - upload_signatures::{ + claim_keys::v3::{Request as KeysClaimRequest, Response as KeysClaimResponse}, + get_keys::v3::Response as KeysQueryResponse, + upload_keys::v3::Response as KeysUploadResponse, + upload_signatures::v3::{ Request as RustSignatureUploadRequest, Response as SignatureUploadResponse, }, }, - sync::sync_events::DeviceLists as RumaDeviceLists, - to_device::send_event_to_device::Response as ToDeviceResponse, + sync::sync_events::v3::DeviceLists as RumaDeviceLists, + to_device::send_event_to_device::v3::Response as ToDeviceResponse, }, assign, events::EventContent, - identifiers::UserId, + TransactionId, UserId, }; use serde_json::json; @@ -96,7 +95,7 @@ impl From for OutgoingVerificationRequest { room_id: r.room_id.to_string(), content: serde_json::to_string(&r.content) .expect("Can't serialize message content"), - event_type: r.content.event_type().to_owned(), + event_type: r.content.event_type().to_string(), }, } } @@ -105,7 +104,7 @@ impl From for OutgoingVerificationRequest { impl From for OutgoingVerificationRequest { fn from(r: ToDeviceRequest) -> Self { Self::ToDevice { - request_id: r.txn_id_string(), + request_id: r.txn_id.to_string(), event_type: r.event_type.to_string(), body: serde_json::to_string(&r.messages).expect("Can't serialize to-device body"), } @@ -151,7 +150,7 @@ impl From for Request { .expect("Can't serialize signature upload request"), }, RoomMessage(r) => Request::from(r), - KeysClaim(c) => (*r.request_id(), c.clone()).into(), + KeysClaim(c) => (r.request_id().to_owned(), c.clone()).into(), KeysBackup(b) => Request::KeysBackup { request_id: r.request_id().to_string(), version: b.version.to_owned(), @@ -165,15 +164,15 @@ impl From for Request { impl From for Request { fn from(r: ToDeviceRequest) -> Self { Request::ToDevice { - request_id: r.txn_id_string(), + request_id: r.txn_id.to_string(), event_type: r.event_type.to_string(), body: serde_json::to_string(&r.messages).expect("Can't serialize to-device body"), } } } -impl From<(Uuid, KeysClaimRequest)> for Request { - fn from(request_tuple: (Uuid, KeysClaimRequest)) -> Self { +impl From<(Box, KeysClaimRequest)> for Request { + fn from(request_tuple: (Box, KeysClaimRequest)) -> Self { let (request_id, request) = request_tuple; Request::KeysClaim { @@ -195,7 +194,7 @@ impl From<(Uuid, KeysClaimRequest)> for Request { impl From<&ToDeviceRequest> for Request { fn from(r: &ToDeviceRequest) -> Self { Request::ToDevice { - request_id: r.txn_id_string(), + request_id: r.txn_id.to_string(), event_type: r.event_type.to_string(), body: serde_json::to_string(&r.messages).expect("Can't serialize to-device body"), } @@ -207,7 +206,7 @@ impl From<&RoomMessageRequest> for Request { Self::RoomMessage { request_id: r.txn_id.to_string(), room_id: r.room_id.to_string(), - event_type: r.content.event_type().to_owned(), + event_type: r.content.event_type().to_string(), content: serde_json::to_string(&r.content).expect("Can't serialize message content"), } } diff --git a/crates/matrix-crypto-ffi/src/users.rs b/crates/matrix-crypto-ffi/src/users.rs index 4c1a05a55..77b59d04c 100644 --- a/crates/matrix-crypto-ffi/src/users.rs +++ b/crates/matrix-crypto-ffi/src/users.rs @@ -1,5 +1,4 @@ -use matrix_sdk_crypto::UserIdentities; -use ruma::encryption::CrossSigningKey; +use matrix_sdk_crypto::{types::CrossSigningKey, UserIdentities}; use crate::CryptoStoreError; @@ -34,9 +33,9 @@ impl UserIdentity { pub(crate) async fn from_rust(i: UserIdentities) -> Result { Ok(match i { UserIdentities::Own(i) => { - let master: CrossSigningKey = i.master_key().to_owned().into(); - let user_signing: CrossSigningKey = i.user_signing_key().to_owned().into(); - let self_signing: CrossSigningKey = i.self_signing_key().to_owned().into(); + let master: CrossSigningKey = i.master_key().as_ref().to_owned(); + let user_signing: CrossSigningKey = i.user_signing_key().as_ref().to_owned(); + let self_signing: CrossSigningKey = i.self_signing_key().as_ref().to_owned(); UserIdentity::Own { user_id: i.user_id().to_string(), @@ -47,8 +46,8 @@ impl UserIdentity { } } UserIdentities::Other(i) => { - let master: CrossSigningKey = i.master_key().to_owned().into(); - let self_signing: CrossSigningKey = i.self_signing_key().to_owned().into(); + let master: CrossSigningKey = i.master_key().as_ref().to_owned(); + let self_signing: CrossSigningKey = i.self_signing_key().as_ref().to_owned(); UserIdentity::Other { user_id: i.user_id().to_string(), diff --git a/crates/matrix-crypto-ffi/src/verification.rs b/crates/matrix-crypto-ffi/src/verification.rs index 13d7204d9..ad4ce52c6 100644 --- a/crates/matrix-crypto-ffi/src/verification.rs +++ b/crates/matrix-crypto-ffi/src/verification.rs @@ -167,9 +167,9 @@ pub struct RequestVerificationResult { /// A result type for confirming verifications. pub struct ConfirmVerificationResult { - /// The request that needs to be sent out to notify the other side that we + /// The requests that needs to be sent out to notify the other side that we /// confirmed the verification. - pub request: OutgoingVerificationRequest, + pub requests: Vec, /// A request that will upload signatures of the verified device or user, if /// the verification is completed and we're able to sign devices or users pub signature_request: Option,