diff --git a/matrix_sdk/Cargo.toml b/matrix_sdk/Cargo.toml index 608f6c57..76e4283f 100644 --- a/matrix_sdk/Cargo.toml +++ b/matrix_sdk/Cargo.toml @@ -72,7 +72,7 @@ async-trait = "0.1.41" async-std = { version = "1.6.5", features = ["unstable"] } dirs = "3.0.1" matrix-sdk-test = { version = "0.1.0", path = "../matrix_sdk_test" } -tokio = { version = "0.2.22", features = ["rt-threaded", "macros"] } +tokio = { version = "0.2.22", default-features = false, features = ["rt-threaded", "macros"] } serde_json = "1.0.59" tracing-subscriber = "0.2.13" tempfile = "3.1.0" diff --git a/matrix_sdk/examples/command_bot.rs b/matrix_sdk/examples/command_bot.rs index 4f2d9fea..8c12fd5a 100644 --- a/matrix_sdk/examples/command_bot.rs +++ b/matrix_sdk/examples/command_bot.rs @@ -38,12 +38,8 @@ impl EventEmitter for CommandBot { }; if msg_body.contains("!party") { - let content = AnyMessageEventContent::RoomMessage(MessageEventContent::Text( - TextMessageEventContent { - body: "🎉🎊🥳 let's PARTY!! 🥳🎊🎉".to_string(), - formatted: None, - relates_to: None, - }, + let content = AnyMessageEventContent::RoomMessage(MessageEventContent::text_plain( + "🎉🎊🥳 let's PARTY!! 🥳🎊🎉", )); // we clone here to hold the lock for as little time as possible. let room_id = room.read().await.room_id.clone(); diff --git a/matrix_sdk/src/client.rs b/matrix_sdk/src/client.rs index 7abfa5df..f5d971c0 100644 --- a/matrix_sdk/src/client.rs +++ b/matrix_sdk/src/client.rs @@ -1467,10 +1467,10 @@ impl Client { sync_settings: SyncSettings<'_>, ) -> Result { let request = assign!(sync_events::Request::new(), { - filter: sync_settings.filter, + filter: sync_settings.filter.as_ref(), since: sync_settings.token.as_deref(), full_state: sync_settings.full_state, - set_presence: PresenceState::Online, + set_presence: &PresenceState::Online, timeout: sync_settings.timeout, }); @@ -1561,13 +1561,11 @@ impl Client { #[instrument(skip(callback))] pub async fn sync_with_callback( &self, - sync_settings: SyncSettings<'_>, + mut sync_settings: SyncSettings<'_>, callback: impl Fn(sync_events::Response) -> C, ) where C: Future, { - let mut sync_settings = sync_settings; - let filter = sync_settings.filter; let mut last_sync_time: Option = None; if sync_settings.token.is_none() { @@ -1575,6 +1573,7 @@ impl Client { } loop { + let filter = sync_settings.filter.clone(); let response = self.sync_once(sync_settings.clone()).await; let response = match response { @@ -1651,8 +1650,8 @@ impl Client { .await .expect("No sync token found after initial sync"), ); - if let Some(f) = filter.as_ref() { - sync_settings = sync_settings.filter(*f); + if let Some(f) = filter { + sync_settings = sync_settings.filter(f); } } } @@ -1895,12 +1894,12 @@ impl Client { let (request, signature_request) = olm.bootstrap_cross_signing(false).await?; - let request = UploadSigningKeysRequest { + let request = assign!(UploadSigningKeysRequest::new(), { auth: auth_data, master_key: request.master_key, self_signing_key: request.self_signing_key, user_signing_key: request.user_signing_key, - }; + }); self.send(request).await?; self.send(signature_request).await?; @@ -2107,10 +2106,7 @@ mod test { }, assign, directory::Filter, - events::{ - room::message::{MessageEventContent, TextMessageEventContent}, - AnyMessageEventContent, - }, + events::{room::message::MessageEventContent, AnyMessageEventContent}, identifiers::{event_id, room_id, user_id}, thirdparty, }; @@ -2655,13 +2651,8 @@ mod test { let room_id = room_id!("!testroom:example.org"); - let content = AnyMessageEventContent::RoomMessage(MessageEventContent::Text( - TextMessageEventContent { - body: "Hello world".to_owned(), - relates_to: None, - formatted: None, - }, - )); + let content = + AnyMessageEventContent::RoomMessage(MessageEventContent::text_plain("Hello world")); let txn_id = Uuid::new_v4(); let response = client .room_send(&room_id, content, Some(txn_id)) diff --git a/matrix_sdk_base/Cargo.toml b/matrix_sdk_base/Cargo.toml index 5eb04c64..530ca9a3 100644 --- a/matrix_sdk_base/Cargo.toml +++ b/matrix_sdk_base/Cargo.toml @@ -25,7 +25,7 @@ docs = ["encryption", "sqlite_cryptostore", "messages"] [dependencies] async-trait = "0.1.41" -serde = "1.0.116" +serde = "1.0.117" serde_json = "1.0.59" zeroize = "1.1.1" tracing = "0.1.21" @@ -51,7 +51,7 @@ tempfile = "3.1.0" mockito = "0.27.0" [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] -tokio = { version = "0.2.22", features = ["rt-threaded", "macros"] } +tokio = { version = "0.2.22", default-features = false, features = ["rt-threaded", "macros"] } [target.'cfg(target_arch = "wasm32")'.dev-dependencies] wasm-bindgen-test = "0.3.18" diff --git a/matrix_sdk_base/src/client.rs b/matrix_sdk_base/src/client.rs index e4cae5bc..55142e98 100644 --- a/matrix_sdk_base/src/client.rs +++ b/matrix_sdk_base/src/client.rs @@ -2387,97 +2387,6 @@ mod test { assert!(passed.load(Ordering::SeqCst)) } - #[async_test] - async fn test_unrecognized_custom_event() { - use super::*; - - use crate::{EventEmitter, SyncRoom}; - use matrix_sdk_common::{api::r0::sync::sync_events, locks::RwLock}; - use std::sync::{ - atomic::{AtomicBool, Ordering}, - Arc, - }; - - struct EE(Arc); - #[async_trait] - impl EventEmitter for EE { - async fn on_custom_event(&self, room: SyncRoom, event: &CustomEvent<'_>) { - if let SyncRoom::Joined(_) = room { - if let CustomEvent::Message(custom) = event { - if custom.content.event_type == "m.reaction" - && custom.content.json.get("m.relates_to").is_some() - { - self.0.swap(true, Ordering::SeqCst); - } - } - } - } - } - - let room_id = get_room_id(); - let passed = Arc::new(AtomicBool::default()); - let emitter = EE(Arc::clone(&passed)); - let mut client = get_client().await; - - client.event_emitter = Arc::new(RwLock::new(Some(Box::new(emitter)))); - - // This is needed other wise the `EventBuilder` goes through a de/ser cycle and the `prev_content` is lost. - let event: &serde_json::Value = &test_json::REACTION; - - let mut joined_rooms: HashMap = HashMap::new(); - let joined_room = serde_json::json!({ - "summary": {}, - "account_data": { - "events": [], - }, - "ephemeral": { - "events": [], - }, - "state": { - "events": [], - }, - "timeline": { - "events": vec![ event ], - "limited": true, - "prev_batch": "t392-516_47314_0_7_1_1_1_11444_1" - }, - "unread_notifications": { - "highlight_count": 0, - "notification_count": 11 - } - }); - joined_rooms.insert(room_id, joined_room); - - let empty_room: HashMap = HashMap::new(); - let body = serde_json::json!({ - "device_one_time_keys_count": {}, - "next_batch": "s526_47314_0_7_1_1_1_11444_1", - "device_lists": { - "changed": [], - "left": [] - }, - "rooms": { - "invite": empty_room, - "join": joined_rooms, - "leave": empty_room, - }, - "to_device": { - "events": [] - }, - "presence": { - "events": [] - } - }); - let response = http::Response::builder() - .body(serde_json::to_vec(&body).unwrap()) - .unwrap(); - let mut sync = sync_events::Response::try_from(response).unwrap(); - - client.receive_sync_response(&mut sync).await.unwrap(); - - assert!(passed.load(Ordering::SeqCst)) - } - #[cfg(feature = "messages")] #[async_test] async fn message_queue_redaction_event_store_deser() { diff --git a/matrix_sdk_base/src/models/room.rs b/matrix_sdk_base/src/models/room.rs index 6892c50a..0b65abcb 100644 --- a/matrix_sdk_base/src/models/room.rs +++ b/matrix_sdk_base/src/models/room.rs @@ -934,7 +934,7 @@ impl Room { member.currently_active = *currently_active; member.display_name = displayname.clone(); member.last_active_ago = *last_active_ago; - member.presence = Some(*presence); + member.presence = Some(presence.clone()); member.status_msg = status_msg.clone(); true @@ -1091,6 +1091,7 @@ impl Describe for MembershipState { Self::Join => "is a member of", Self::Knock => "is requesting access to", Self::Leave => "has left", + _ => "unhandled case of MembershipState", } .to_string() } @@ -1123,6 +1124,7 @@ impl Describe for MembershipChange { Self::None => "did nothing in", Self::NotImplemented => "NOT IMPLEMENTED", Self::Error => "ERROR", + _ => "unhandled case of MembershipChange", } .to_string() } diff --git a/matrix_sdk_common/Cargo.toml b/matrix_sdk_common/Cargo.toml index b9fc3024..d348a0d1 100644 --- a/matrix_sdk_common/Cargo.toml +++ b/matrix_sdk_common/Cargo.toml @@ -21,17 +21,17 @@ js_int = "0.1.9" [dependencies.ruma] version = "0.0.1" git = "https://github.com/ruma/ruma" -rev = "c0eee624311c12ee9c3eb14737988e3f0a60fb3f" -features = ["client-api", "unstable-pre-spec", "unstable-exhaustive-types"] +rev = "48d1c9747561686e1c5627405780f6de01ee17b1" +features = ["client-api", "unstable-pre-spec"] [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -uuid = { version = "0.8.1", features = ["v4", "serde"] } +uuid = { version = "0.8.1", default-features = false, features = ["v4", "serde"] } [target.'cfg(not(target_arch = "wasm32"))'.dependencies.tokio] version = "0.2.22" default-features = false -features = ["sync", "time", "fs"] +features = ["sync"] [target.'cfg(target_arch = "wasm32")'.dependencies] futures-locks = { version = "0.6.0", default-features = false } -uuid = { version = "0.8.1", features = ["v4", "wasm-bindgen"] } +uuid = { version = "0.8.1", default-features = false, features = ["v4", "wasm-bindgen"] } diff --git a/matrix_sdk_common_macros/Cargo.toml b/matrix_sdk_common_macros/Cargo.toml index fab5eea7..d8219ac7 100644 --- a/matrix_sdk_common_macros/Cargo.toml +++ b/matrix_sdk_common_macros/Cargo.toml @@ -14,5 +14,5 @@ version = "0.1.0" proc-macro = true [dependencies] -syn = "1.0.44" +syn = { version = "1.0.45", features = ["proc-macro"], default-features = false } quote = "1.0.7" diff --git a/matrix_sdk_crypto/Cargo.toml b/matrix_sdk_crypto/Cargo.toml index 4e7ee157..927d104b 100644 --- a/matrix_sdk_crypto/Cargo.toml +++ b/matrix_sdk_crypto/Cargo.toml @@ -27,9 +27,8 @@ matrix-sdk-common = { version = "0.1.0", path = "../matrix_sdk_common" } olm-rs = { version = "1.0.0", features = ["serde"] } getrandom = "0.2.0" -serde = { version = "1.0.116", features = ["derive", "rc"] } +serde = { version = "1.0.117", features = ["derive", "rc"] } serde_json = "1.0.59" -cjson = "0.1.1" zeroize = { version = "1.1.1", features = ["zeroize_derive"] } url = "2.1.1" @@ -40,17 +39,12 @@ atomic = "0.5.0" dashmap = "3.11.10" sha2 = "0.9.1" aes-gcm = "0.7.0" -aes-ctr = "0.5.0" -pbkdf2 = { version = "0.5.0", default-features = false } -hmac = "0.9.0" +aes-ctr = "0.6.0" +pbkdf2 = { version = "0.6.0", default-features = false } +hmac = "0.10.1" base64 = "0.13.0" byteorder = "1.3.4" -[dependencies.tracing-futures] -version = "0.2.4" -default-features = false -features = ["std", "std-future"] - [target.'cfg(not(target_arch = "wasm32"))'.dependencies.sqlx] git = "https://github.com/launchbadge/sqlx/" rev = "fd25a7530cf087e1529553ff854f192738db3461" @@ -59,7 +53,7 @@ default-features = false features = ["runtime-tokio", "sqlite", "macros"] [dev-dependencies] -tokio = { version = "0.2.22", features = ["rt-threaded", "macros"] } +tokio = { version = "0.2.22", default-features = false, features = ["rt-threaded", "macros"] } futures = "0.3.6" proptest = "0.10.1" serde_json = "1.0.59" diff --git a/matrix_sdk_crypto/src/error.rs b/matrix_sdk_crypto/src/error.rs index 1692bd54..6d9aacdc 100644 --- a/matrix_sdk_crypto/src/error.rs +++ b/matrix_sdk_crypto/src/error.rs @@ -12,7 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -use cjson::Error as CjsonError; use matrix_sdk_common::identifiers::{DeviceId, Error as IdentifierError, UserId}; use olm_rs::errors::{OlmGroupSessionError, OlmSessionError}; use serde_json::Error as SerdeError; @@ -145,14 +144,11 @@ pub enum SignatureError { #[error("the provided JSON object doesn't contain a signatures field")] NoSignatureFound, - #[error("the provided JSON object can't be converted to a canonical representation")] - CanonicalJsonError(CjsonError), + #[error("the signature didn't match the provided key")] + VerificationError, #[error(transparent)] JsonError(#[from] SerdeError), - - #[error("the signature didn't match the provided key")] - VerificationError, } #[derive(Error, Debug)] @@ -177,9 +173,3 @@ pub(crate) enum SessionCreationError { #[error("Error creating new Olm session for {0} {1}: {2:?}")] OlmError(UserId, Box, OlmSessionError), } - -impl From for SignatureError { - fn from(error: CjsonError) -> Self { - Self::CanonicalJsonError(error) - } -} diff --git a/matrix_sdk_crypto/src/file_encryption/attachments.rs b/matrix_sdk_crypto/src/file_encryption/attachments.rs index 9fbaa6ff..675e9ed7 100644 --- a/matrix_sdk_crypto/src/file_encryption/attachments.rs +++ b/matrix_sdk_crypto/src/file_encryption/attachments.rs @@ -27,7 +27,7 @@ use matrix_sdk_common::events::room::JsonWebKey; use getrandom::getrandom; use aes_ctr::{ - stream_cipher::{NewStreamCipher, SyncStreamCipher}, + cipher::{NewStreamCipher, SyncStreamCipher}, Aes256Ctr, }; use base64::DecodeError; diff --git a/matrix_sdk_crypto/src/file_encryption/key_export.rs b/matrix_sdk_crypto/src/file_encryption/key_export.rs index dcbdd440..f41d5825 100644 --- a/matrix_sdk_crypto/src/file_encryption/key_export.rs +++ b/matrix_sdk_crypto/src/file_encryption/key_export.rs @@ -20,7 +20,7 @@ use byteorder::{BigEndian, ReadBytesExt}; use getrandom::getrandom; use aes_ctr::{ - stream_cipher::{NewStreamCipher, SyncStreamCipher}, + cipher::{NewStreamCipher, SyncStreamCipher}, Aes256Ctr, }; use hmac::{Hmac, Mac, NewMac}; diff --git a/matrix_sdk_crypto/src/identities/device.rs b/matrix_sdk_crypto/src/identities/device.rs index 568d80f9..4dc44298 100644 --- a/matrix_sdk_crypto/src/identities/device.rs +++ b/matrix_sdk_crypto/src/identities/device.rs @@ -60,7 +60,7 @@ use crate::{ pub struct ReadOnlyDevice { user_id: Arc, device_id: Arc>, - algorithms: Arc>, + algorithms: Arc<[EventEncryptionAlgorithm]>, keys: Arc>, pub(crate) signatures: Arc>>, display_name: Arc>, @@ -257,7 +257,7 @@ impl ReadOnlyDevice { display_name: Arc::new(display_name), trust_state: Arc::new(Atomic::new(trust_state)), signatures: Arc::new(signatures), - algorithms: Arc::new(algorithms), + algorithms: algorithms.into(), keys: Arc::new(keys), deleted: Arc::new(AtomicBool::new(false)), } @@ -419,7 +419,7 @@ impl ReadOnlyDevice { let display_name = Arc::new(device_keys.unsigned.device_display_name.clone()); - self.algorithms = Arc::new(device_keys.algorithms.clone()); + self.algorithms = device_keys.algorithms.as_slice().into(); self.keys = Arc::new(device_keys.keys.clone()); self.signatures = Arc::new(device_keys.signatures.clone()); self.display_name = display_name; @@ -443,14 +443,13 @@ impl ReadOnlyDevice { } pub(crate) fn as_device_keys(&self) -> DeviceKeys { - DeviceKeys { - user_id: self.user_id().clone(), - device_id: self.device_id().into(), - keys: self.keys().clone(), - algorithms: self.algorithms().to_vec(), - signatures: self.signatures().to_owned(), - unsigned: Default::default(), - } + DeviceKeys::new( + self.user_id().clone(), + self.device_id().into(), + self.algorithms().to_vec(), + self.keys().clone(), + self.signatures().to_owned(), + ) } pub(crate) fn as_signature_message(&self) -> Value { @@ -467,7 +466,8 @@ impl ReadOnlyDevice { &self, device_keys: &DeviceKeys, ) -> Result<(), SignatureError> { - self.is_signed_by_device(&mut json!(&device_keys)) + let mut device_keys = serde_json::to_value(device_keys).unwrap(); + self.is_signed_by_device(&mut device_keys) } pub(crate) fn verify_one_time_key( @@ -501,7 +501,7 @@ impl TryFrom<&DeviceKeys> for ReadOnlyDevice { let device = Self { user_id: Arc::new(device_keys.user_id.clone()), device_id: Arc::new(device_keys.device_id.clone()), - algorithms: Arc::new(device_keys.algorithms.clone()), + algorithms: device_keys.algorithms.as_slice().into(), signatures: Arc::new(device_keys.signatures.clone()), keys: Arc::new(device_keys.keys.clone()), display_name: Arc::new(device_keys.unsigned.device_display_name.clone()), diff --git a/matrix_sdk_crypto/src/key_request.rs b/matrix_sdk_crypto/src/key_request.rs index afb07840..55f5b569 100644 --- a/matrix_sdk_crypto/src/key_request.rs +++ b/matrix_sdk_crypto/src/key_request.rs @@ -25,7 +25,7 @@ use serde::{Deserialize, Serialize}; use serde_json::value::to_raw_value; use std::{collections::BTreeMap, sync::Arc}; use thiserror::Error; -use tracing::{error, info, instrument, trace, warn}; +use tracing::{error, info, trace, warn}; use matrix_sdk_common::{ api::r0::to_device::DeviceIdOrAllDevices, @@ -293,12 +293,11 @@ impl KeyRequestMachine { } /// Handle a single incoming key request. - #[instrument] async fn handle_key_request( &self, event: &ToDeviceEvent, ) -> OlmResult> { - let key_info = match event.content.action { + let key_info = match &event.content.action { Action::Request => { if let Some(info) = &event.content.body { info @@ -313,6 +312,10 @@ impl KeyRequestMachine { } // We ignore cancellations here since there's nothing to serve. Action::CancelRequest => return Ok(None), + action => { + warn!("Unknown room key request action: {:?}", action); + return Ok(None); + } }; let session = self diff --git a/matrix_sdk_crypto/src/machine.rs b/matrix_sdk_crypto/src/machine.rs index 16821b18..83b5939a 100644 --- a/matrix_sdk_crypto/src/machine.rs +++ b/matrix_sdk_crypto/src/machine.rs @@ -17,8 +17,7 @@ use std::path::Path; use std::{collections::BTreeMap, mem, sync::Arc}; use dashmap::DashMap; -use matrix_sdk_common::locks::Mutex; -use tracing::{debug, error, info, instrument, trace, warn}; +use tracing::{debug, error, info, trace, warn}; use matrix_sdk_common::{ api::r0::{ @@ -40,6 +39,7 @@ use matrix_sdk_common::{ DeviceId, DeviceIdBox, DeviceKeyAlgorithm, EventEncryptionAlgorithm, RoomId, UserId, }, js_int::UInt, + locks::Mutex, uuid::Uuid, Raw, }; @@ -262,7 +262,6 @@ impl OlmMachine { /// /// * `device_id` - The unique id of the device that owns this machine. #[cfg(feature = "sqlite_cryptostore")] - #[instrument(skip(path, passphrase))] #[cfg_attr(feature = "docs", doc(cfg(r#sqlite_cryptostore)))] pub async fn new_with_default_store( user_id: &UserId, @@ -460,7 +459,6 @@ impl OlmMachine { /// /// * `response` - The keys upload response of the request that the client /// performed. - #[instrument] async fn receive_keys_upload_response( &self, response: &upload_keys::Response, @@ -777,7 +775,6 @@ impl OlmMachine { /// * `response` - The sync latest sync response. /// /// [`decrypt_room_event`]: #method.decrypt_room_event - #[instrument(skip(response))] pub async fn receive_sync_response(&self, response: &mut SyncResponse) -> OlmResult<()> { // Remove verification objects that have expired or are done. self.verification_machine.garbage_collect(); diff --git a/matrix_sdk_crypto/src/olm/account.rs b/matrix_sdk_crypto/src/olm/account.rs index 150bef6c..ed57b893 100644 --- a/matrix_sdk_crypto/src/olm/account.rs +++ b/matrix_sdk_crypto/src/olm/account.rs @@ -52,7 +52,7 @@ use olm_rs::{ }; use crate::{ - error::{EventError, OlmResult, SessionCreationError, SignatureError}, + error::{EventError, OlmResult, SessionCreationError}, identities::ReadOnlyDevice, requests::UploadSigningKeysRequest, store::Store, @@ -651,7 +651,15 @@ impl ReadOnlyAccount { /// uploaded. pub(crate) async fn device_keys(&self) -> DeviceKeys { let mut device_keys = self.unsigned_device_keys(); - let jsond_device_keys = serde_json::to_value(&device_keys).unwrap(); + + // Create a copy of the device keys containing only fields that will + // get signed. + let json_device_keys = json!({ + "user_id": device_keys.user_id, + "device_id": device_keys.device_id, + "algorithms": device_keys.algorithms, + "keys": device_keys.keys, + }); device_keys .signatures @@ -659,9 +667,7 @@ impl ReadOnlyAccount { .or_insert_with(BTreeMap::new) .insert( DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, &self.device_id), - self.sign_json(jsond_device_keys) - .await - .expect("Can't sign own device keys"), + self.sign_json(&json_device_keys).await, ); device_keys @@ -688,13 +694,8 @@ impl ReadOnlyAccount { /// # Panic /// /// Panics if the json value can't be serialized. - pub async fn sign_json(&self, mut json: Value) -> Result { - let json_object = json.as_object_mut().ok_or(SignatureError::NotAnObject)?; - let _ = json_object.remove("unsigned"); - let _ = json_object.remove("signatures"); - - let canonical_json = cjson::to_string(&json)?; - Ok(self.sign(&canonical_json).await) + pub async fn sign_json(&self, json: &Value) -> String { + self.sign(&json.to_string()).await } pub(crate) async fn signed_one_time_keys_helper( @@ -708,10 +709,7 @@ impl ReadOnlyAccount { "key": key, }); - let signature = self - .sign_json(key_json) - .await - .expect("Can't sign own one-time keys"); + let signature = self.sign_json(&key_json).await; let mut signature_map = BTreeMap::new(); @@ -779,8 +777,8 @@ impl ReadOnlyAccount { device_id: self.device_id.clone(), our_identity_keys: self.identity_keys.clone(), inner: Arc::new(Mutex::new(session)), - session_id: Arc::new(session_id), - sender_key: Arc::new(their_identity_key.to_owned()), + session_id: session_id.into(), + sender_key: their_identity_key.into(), creation_time: Arc::new(now), last_use_time: Arc::new(now), }) @@ -884,8 +882,8 @@ impl ReadOnlyAccount { device_id: self.device_id.clone(), our_identity_keys: self.identity_keys.clone(), inner: Arc::new(Mutex::new(session)), - session_id: Arc::new(session_id), - sender_key: Arc::new(their_identity_key.to_owned()), + session_id: session_id.into(), + sender_key: their_identity_key.into(), creation_time: Arc::new(now), last_use_time: Arc::new(now), }) diff --git a/matrix_sdk_crypto/src/olm/group_sessions/inbound.rs b/matrix_sdk_crypto/src/olm/group_sessions/inbound.rs index 9e8a5c11..a7249563 100644 --- a/matrix_sdk_crypto/src/olm/group_sessions/inbound.rs +++ b/matrix_sdk_crypto/src/olm/group_sessions/inbound.rs @@ -56,8 +56,8 @@ use crate::error::{EventError, MegolmResult}; #[derive(Clone)] pub struct InboundGroupSession { inner: Arc>, - session_id: Arc, - pub(crate) sender_key: Arc, + session_id: Arc, + pub(crate) sender_key: Arc, pub(crate) signing_key: Arc>, pub(crate) room_id: Arc, forwarding_chains: Arc>>>, @@ -95,8 +95,8 @@ impl InboundGroupSession { Ok(InboundGroupSession { inner: Arc::new(Mutex::new(session)), - session_id: Arc::new(session_id), - sender_key: Arc::new(sender_key.to_owned()), + session_id: session_id.into(), + sender_key: sender_key.to_owned().into(), signing_key: Arc::new(keys), room_id: Arc::new(room_id.clone()), forwarding_chains: Arc::new(Mutex::new(None)), @@ -145,8 +145,8 @@ impl InboundGroupSession { Ok(InboundGroupSession { inner: Arc::new(Mutex::new(session)), - session_id: Arc::new(content.session_id.clone()), - sender_key: Arc::new(content.sender_key.clone()), + session_id: content.session_id.as_str().into(), + sender_key: content.sender_key.as_str().into(), signing_key: Arc::new(sender_claimed_key), room_id: Arc::new(content.room_id.clone()), forwarding_chains: Arc::new(Mutex::new(Some(forwarding_chains))), @@ -225,8 +225,8 @@ impl InboundGroupSession { Ok(InboundGroupSession { inner: Arc::new(Mutex::new(session)), - session_id: Arc::new(session_id), - sender_key: Arc::new(pickle.sender_key), + session_id: session_id.into(), + sender_key: pickle.sender_key.into(), signing_key: Arc::new(pickle.signing_key), room_id: Arc::new(pickle.room_id), forwarding_chains: Arc::new(Mutex::new(pickle.forwarding_chains)), @@ -377,8 +377,8 @@ impl TryFrom for InboundGroupSession { Ok(InboundGroupSession { inner: Arc::new(Mutex::new(session)), - session_id: Arc::new(key.session_id), - sender_key: Arc::new(key.sender_key), + session_id: key.session_id.into(), + sender_key: key.sender_key.into(), signing_key: Arc::new(key.sender_claimed_keys), room_id: Arc::new(key.room_id), forwarding_chains: Arc::new(Mutex::new(forwarding_chains)), diff --git a/matrix_sdk_crypto/src/olm/group_sessions/outbound.rs b/matrix_sdk_crypto/src/olm/group_sessions/outbound.rs index d2daab7e..adecc4e1 100644 --- a/matrix_sdk_crypto/src/olm/group_sessions/outbound.rs +++ b/matrix_sdk_crypto/src/olm/group_sessions/outbound.rs @@ -99,7 +99,7 @@ pub struct OutboundGroupSession { inner: Arc>, device_id: Arc, account_identity_keys: Arc, - session_id: Arc, + session_id: Arc, room_id: Arc, pub(crate) creation_time: Arc, message_count: Arc, @@ -140,7 +140,7 @@ impl OutboundGroupSession { room_id: Arc::new(room_id.to_owned()), device_id, account_identity_keys: identity_keys, - session_id: Arc::new(session_id), + session_id: session_id.into(), creation_time: Arc::new(Instant::now()), message_count: Arc::new(AtomicU64::new(0)), shared: Arc::new(AtomicBool::new(false)), @@ -240,12 +240,7 @@ impl OutboundGroupSession { "type": content.event_type(), }); - let plaintext = cjson::to_string(&json_content).unwrap_or_else(|_| { - panic!(format!( - "Can't serialize {} to canonical JSON", - json_content - )) - }); + let plaintext = json_content.to_string(); let ciphertext = self.encrypt_helper(plaintext).await; diff --git a/matrix_sdk_crypto/src/olm/session.rs b/matrix_sdk_crypto/src/olm/session.rs index 554e75cb..a68f8230 100644 --- a/matrix_sdk_crypto/src/olm/session.rs +++ b/matrix_sdk_crypto/src/olm/session.rs @@ -46,8 +46,8 @@ pub struct Session { pub(crate) device_id: Arc>, pub(crate) our_identity_keys: Arc, pub(crate) inner: Arc>, - pub(crate) session_id: Arc, - pub(crate) sender_key: Arc, + pub(crate) session_id: Arc, + pub(crate) sender_key: Arc, pub(crate) creation_time: Arc, pub(crate) last_use_time: Arc, } @@ -126,7 +126,7 @@ impl Session { "content": content, }); - let plaintext = cjson::to_string(&payload) + let plaintext = serde_json::to_string(&payload) .unwrap_or_else(|_| panic!(format!("Can't serialize {} to canonical JSON", payload))); let ciphertext = self.encrypt_helper(&plaintext).await.to_tuple(); @@ -232,8 +232,8 @@ impl Session { device_id, our_identity_keys, inner: Arc::new(Mutex::new(session)), - session_id: Arc::new(session_id), - sender_key: Arc::new(pickle.sender_key), + session_id: session_id.into(), + sender_key: pickle.sender_key.into(), creation_time: Arc::new(creation_time), last_use_time: Arc::new(last_use_time), }) diff --git a/matrix_sdk_crypto/src/olm/signing/mod.rs b/matrix_sdk_crypto/src/olm/signing/mod.rs index 3cc9e3c0..926ceab9 100644 --- a/matrix_sdk_crypto/src/olm/signing/mod.rs +++ b/matrix_sdk_crypto/src/olm/signing/mod.rs @@ -149,7 +149,7 @@ impl PrivateCrossSigningIdentity { .sign_user(&user_identity) .await?; - Ok(SignatureUploadRequest { signed_keys }) + Ok(SignatureUploadRequest::new(signed_keys)) } /// Sign the given device keys with this identity. @@ -192,7 +192,7 @@ impl PrivateCrossSigningIdentity { serde_json::to_value(device_keys)?, ); - Ok(SignatureUploadRequest { signed_keys }) + Ok(SignatureUploadRequest::new(signed_keys)) } /// Create a new identity for the given Olm Account. @@ -215,11 +215,11 @@ impl PrivateCrossSigningIdentity { master.cross_signing_key(account.user_id().to_owned(), KeyUsage::Master); let signature = account .sign_json( - serde_json::to_value(&public_key) + &serde_json::to_value(&public_key) .expect("Can't convert own public master key to json"), ) - .await - .expect("Can't sign own public master key"); + .await; + public_key .signatures .entry(account.user_id().to_owned()) diff --git a/matrix_sdk_crypto/src/olm/signing/pk_signing.rs b/matrix_sdk_crypto/src/olm/signing/pk_signing.rs index 838dca56..656448a4 100644 --- a/matrix_sdk_crypto/src/olm/signing/pk_signing.rs +++ b/matrix_sdk_crypto/src/olm/signing/pk_signing.rs @@ -23,7 +23,7 @@ use matrix_sdk_common::{ identifiers::{DeviceKeyAlgorithm, DeviceKeyId}, }; use serde::{Deserialize, Serialize}; -use serde_json::{Error as JsonError, Value}; +use serde_json::{json, Error as JsonError, Value}; use std::{collections::BTreeMap, sync::Arc}; use thiserror::Error; use zeroize::Zeroizing; @@ -171,14 +171,13 @@ impl MasterSigning { pub async fn sign_subkey<'a>(&self, subkey: &mut CrossSigningKey) { // TODO create a borrowed version of a cross singing key. - let subkey_wihtout_signatures = CrossSigningKey { - user_id: subkey.user_id.clone(), - keys: subkey.keys.clone(), - usage: subkey.usage.clone(), - signatures: BTreeMap::new(), - }; + let subkey_wihtout_signatures = json!({ + "user_id": subkey.user_id.clone(), + "keys": subkey.keys.clone(), + "usage": subkey.usage.clone(), + }); - let message = cjson::to_string(&subkey_wihtout_signatures) + let message = serde_json::to_string(&subkey_wihtout_signatures) .expect("Can't serialize cross signing subkey"); let signature = self.inner.sign(&message).await; @@ -257,7 +256,15 @@ impl SelfSigning { } pub async fn sign_device(&self, device_keys: &mut DeviceKeys) -> Result<(), SignatureError> { - let json_device = serde_json::to_value(&device_keys)?; + // Create a copy of the device keys containing only fields that will + // get signed. + let json_device = json!({ + "user_id": device_keys.user_id, + "device_id": device_keys.device_id, + "algorithms": device_keys.algorithms, + "keys": device_keys.keys, + }); + let signature = self.sign_device_helper(json_device).await?; device_keys @@ -407,7 +414,7 @@ impl Signing { pub async fn sign_json(&self, mut json: Value) -> Result { let json_object = json.as_object_mut().ok_or(SignatureError::NotAnObject)?; let _ = json_object.remove("signatures"); - let canonical_json = cjson::to_string(json_object)?; + let canonical_json = serde_json::to_string(json_object)?; Ok(self.sign(&canonical_json).await) } diff --git a/matrix_sdk_crypto/src/olm/utility.rs b/matrix_sdk_crypto/src/olm/utility.rs index afa73a6b..5994a453 100644 --- a/matrix_sdk_crypto/src/olm/utility.rs +++ b/matrix_sdk_crypto/src/olm/utility.rs @@ -63,7 +63,7 @@ impl Utility { let unsigned = json_object.remove("unsigned"); let signatures = json_object.remove("signatures"); - let canonical_json = cjson::to_string(json_object)?; + let canonical_json = serde_json::to_string(json_object)?; if let Some(u) = unsigned { json_object.insert("unsigned".to_string(), u); diff --git a/matrix_sdk_crypto/src/session_manager/sessions.rs b/matrix_sdk_crypto/src/session_manager/sessions.rs index 8e18dfb7..2cf2a2cc 100644 --- a/matrix_sdk_crypto/src/session_manager/sessions.rs +++ b/matrix_sdk_crypto/src/session_manager/sessions.rs @@ -405,10 +405,7 @@ mod test { .or_insert_with(BTreeMap::new) .insert(bob.device_id().into(), one_time); - let response = KeyClaimResponse { - failures: BTreeMap::new(), - one_time_keys, - }; + let response = KeyClaimResponse::new(one_time_keys); manager .receive_keys_claim_response(&response) @@ -476,10 +473,7 @@ mod test { .or_insert_with(BTreeMap::new) .insert(bob.device_id().into(), one_time); - let response = KeyClaimResponse { - failures: BTreeMap::new(), - one_time_keys, - }; + let response = KeyClaimResponse::new(one_time_keys); assert!(manager.outgoing_to_device_requests.is_empty()); diff --git a/matrix_sdk_crypto/src/store/sqlite.rs b/matrix_sdk_crypto/src/store/sqlite.rs index 3df06ab2..ae01352e 100644 --- a/matrix_sdk_crypto/src/store/sqlite.rs +++ b/matrix_sdk_crypto/src/store/sqlite.rs @@ -15,7 +15,7 @@ use std::{ collections::{BTreeMap, HashMap, HashSet}, convert::TryFrom, - path::{Path, PathBuf}, + path::Path, result::Result as StdResult, sync::{Arc, Mutex as SyncMutex}, }; @@ -58,7 +58,7 @@ pub struct SqliteStore { user_id: Arc, device_id: Arc>, account_info: Arc>>, - path: Arc, + path: Arc, sessions: SessionStore, tracked_users: Arc>, @@ -155,7 +155,7 @@ impl SqliteStore { device_id: Arc::new(device_id.into()), account_info: Arc::new(SyncMutex::new(None)), sessions: SessionStore::new(), - path: Arc::new(path), + path: path.into(), connection: Arc::new(Mutex::new(connection)), tracked_users: Arc::new(DashSet::new()), users_for_key_query: Arc::new(DashSet::new()), diff --git a/matrix_sdk_crypto/src/verification/sas/mod.rs b/matrix_sdk_crypto/src/verification/sas/mod.rs index 9ef25bb8..476eadc2 100644 --- a/matrix_sdk_crypto/src/verification/sas/mod.rs +++ b/matrix_sdk_crypto/src/verification/sas/mod.rs @@ -66,7 +66,7 @@ pub struct Sas { private_identity: PrivateCrossSigningIdentity, other_device: ReadOnlyDevice, other_identity: Option, - flow_id: Arc, + flow_id: Arc, } impl Sas { @@ -524,11 +524,11 @@ impl Sas { content } - pub(crate) fn verified_devices(&self) -> Option>> { + pub(crate) fn verified_devices(&self) -> Option> { self.inner.lock().unwrap().verified_devices() } - pub(crate) fn verified_identities(&self) -> Option>> { + pub(crate) fn verified_identities(&self) -> Option> { self.inner.lock().unwrap().verified_identities() } @@ -723,7 +723,7 @@ impl InnerSas { } } - fn verification_flow_id(&self) -> Arc { + fn verification_flow_id(&self) -> Arc { match self { InnerSas::Created(s) => s.verification_flow_id.clone(), InnerSas::Started(s) => s.verification_flow_id.clone(), @@ -752,7 +752,7 @@ impl InnerSas { } } - fn verified_devices(&self) -> Option>> { + fn verified_devices(&self) -> Option> { if let InnerSas::Done(s) = self { Some(s.verified_devices()) } else { @@ -760,7 +760,7 @@ impl InnerSas { } } - fn verified_identities(&self) -> Option>> { + fn verified_identities(&self) -> Option> { if let InnerSas::Done(s) = self { Some(s.verified_identities()) } else { diff --git a/matrix_sdk_crypto/src/verification/sas/sas_state.rs b/matrix_sdk_crypto/src/verification/sas/sas_state.rs index 946e03a4..9c0ba30a 100644 --- a/matrix_sdk_crypto/src/verification/sas/sas_state.rs +++ b/matrix_sdk_crypto/src/verification/sas/sas_state.rs @@ -144,7 +144,7 @@ pub struct SasState { /// /// This will be the transaction id for to-device events and the relates_to /// field for in-room events. - pub verification_flow_id: Arc, + pub verification_flow_id: Arc, /// The SAS state we're in. state: Arc, @@ -209,8 +209,8 @@ pub struct Confirmed { pub struct MacReceived { we_started: bool, their_pubkey: String, - verified_devices: Arc>, - verified_master_keys: Arc>, + verified_devices: Arc<[ReadOnlyDevice]>, + verified_master_keys: Arc<[UserIdentities]>, } /// The SAS state indicating that the verification finished successfully. @@ -219,8 +219,8 @@ pub struct MacReceived { /// the master keys in the verified devices list. #[derive(Clone, Debug)] pub struct Done { - verified_devices: Arc>, - verified_master_keys: Arc>, + verified_devices: Arc<[ReadOnlyDevice]>, + verified_master_keys: Arc<[UserIdentities]>, } #[derive(Clone, Debug)] @@ -269,7 +269,7 @@ impl SasState { } fn check_event(&self, sender: &UserId, flow_id: &str) -> Result<(), CancelCode> { - if flow_id != *self.verification_flow_id { + if *flow_id != *self.verification_flow_id { Err(CancelCode::UnknownTransaction) } else if sender != self.ids.other_device.user_id() { Err(CancelCode::UserMismatch) @@ -303,7 +303,7 @@ impl SasState { other_device, other_identity, }, - verification_flow_id: Arc::new(verification_flow_id), + verification_flow_id: verification_flow_id.into(), creation_time: Arc::new(Instant::now()), last_event_time: Arc::new(Instant::now()), @@ -351,7 +351,7 @@ impl SasState { let accepted_protocols = AcceptedProtocols::try_from(content.clone()).map_err(|c| self.clone().cancel(c))?; - let json_start_content = cjson::to_string(&self.as_content()) + let json_start_content = serde_json::to_string(&self.as_content()) .expect("Can't deserialize start event content"); Ok(SasState { @@ -396,7 +396,8 @@ impl SasState { let sas = OlmSas::new(); let utility = OlmUtility::new(); - let json_content = cjson::to_string(&event.content).expect("Can't serialize content"); + let json_content = + serde_json::to_string(&event.content).expect("Can't serialize content"); let pubkey = sas.public_key(); let commitment = utility.sha256_utf8_msg(&format!("{}{}", pubkey, json_content)); @@ -412,7 +413,7 @@ impl SasState { creation_time: Arc::new(Instant::now()), last_event_time: Arc::new(Instant::now()), - verification_flow_id: Arc::new(event.content.transaction_id.clone()), + verification_flow_id: event.content.transaction_id.as_str().into(), state: Arc::new(Started { protocol_definitions: content.clone(), @@ -451,7 +452,7 @@ impl SasState { other_identity, }, - verification_flow_id: Arc::new(event.content.transaction_id.clone()), + verification_flow_id: event.content.transaction_id.as_str().into(), state: Arc::new(Canceled::new(CancelCode::UnknownMethod)), }) } @@ -656,8 +657,8 @@ impl SasState { state: Arc::new(MacReceived { we_started: self.state.we_started, their_pubkey: self.state.their_pubkey.clone(), - verified_devices: Arc::new(devices), - verified_master_keys: Arc::new(master_keys), + verified_devices: devices.into(), + verified_master_keys: master_keys.into(), }), }) } @@ -711,8 +712,8 @@ impl SasState { ids: self.ids, state: Arc::new(Done { - verified_devices: Arc::new(devices), - verified_master_keys: Arc::new(master_keys), + verified_devices: devices.into(), + verified_master_keys: master_keys.into(), }), }) } @@ -791,12 +792,12 @@ impl SasState { } /// Get the list of verified devices. - pub fn verified_devices(&self) -> Arc> { + pub fn verified_devices(&self) -> Arc<[ReadOnlyDevice]> { self.state.verified_devices.clone() } /// Get the list of verified identities. - pub fn verified_identities(&self) -> Arc> { + pub fn verified_identities(&self) -> Arc<[UserIdentities]> { self.state.verified_master_keys.clone() } } diff --git a/matrix_sdk_test/Cargo.toml b/matrix_sdk_test/Cargo.toml index b6a7bcb9..28f88398 100644 --- a/matrix_sdk_test/Cargo.toml +++ b/matrix_sdk_test/Cargo.toml @@ -16,4 +16,4 @@ http = "0.2.1" matrix-sdk-common = { version = "0.1.0", path = "../matrix_sdk_common" } matrix-sdk-test-macros = { version = "0.1.0", path = "../matrix_sdk_test_macros" } lazy_static = "1.4.0" -serde = "1.0.116" +serde = "1.0.117"