From c85f4d4f0cd208f82ba3cb1dca0a7bb6ac7d3e8b Mon Sep 17 00:00:00 2001 From: Devin Ragotzy Date: Wed, 12 May 2021 06:56:29 -0400 Subject: [PATCH] Add rustfmt config file and run over workspace --- matrix_sdk/examples/autojoin.rs | 2 +- .../examples/cross_signing_bootstrap.rs | 5 +- matrix_sdk/examples/emoji_verification.rs | 2 +- matrix_sdk/examples/get_profiles.rs | 3 +- matrix_sdk/examples/image_bot.rs | 2 +- matrix_sdk/examples/login.rs | 2 +- matrix_sdk/src/client.rs | 147 ++++++++---------- matrix_sdk/src/error.rs | 8 +- matrix_sdk/src/event_handler/mod.rs | 15 +- matrix_sdk/src/http_client.rs | 11 +- matrix_sdk/src/lib.rs | 3 +- matrix_sdk/src/room/common.rs | 5 +- matrix_sdk/src/room/invited.rs | 3 +- matrix_sdk/src/room/joined.rs | 24 ++- matrix_sdk/src/room/left.rs | 3 +- matrix_sdk/src/room_member.rs | 4 +- matrix_sdk_appservice/src/actix.rs | 3 +- matrix_sdk_appservice/src/lib.rs | 8 +- matrix_sdk_appservice/tests/actix.rs | 6 +- matrix_sdk_base/examples/state_inspector.rs | 17 +- matrix_sdk_base/src/client.rs | 9 +- matrix_sdk_base/src/error.rs | 4 +- matrix_sdk_base/src/lib.rs | 9 +- matrix_sdk_base/src/rooms/mod.rs | 23 ++- matrix_sdk_base/src/rooms/normal.rs | 3 +- matrix_sdk_base/src/session.rs | 3 +- matrix_sdk_base/src/store/ambiguity_map.rs | 4 +- matrix_sdk_base/src/store/memory_store.rs | 4 +- matrix_sdk_base/src/store/mod.rs | 11 +- matrix_sdk_base/src/store/sled_store/mod.rs | 5 +- .../src/store/sled_store/store_key.rs | 6 +- .../src/deserialized_responses.rs | 3 +- matrix_sdk_common/src/executor.rs | 10 +- matrix_sdk_common/src/lib.rs | 1 - matrix_sdk_common/src/locks.rs | 1 - matrix_sdk_crypto/benches/crypto_bench.rs | 1 - .../src/file_encryption/attachments.rs | 20 ++- .../src/file_encryption/key_export.rs | 13 +- matrix_sdk_crypto/src/identities/device.rs | 24 ++- matrix_sdk_crypto/src/identities/manager.rs | 6 +- matrix_sdk_crypto/src/identities/mod.rs | 16 +- matrix_sdk_crypto/src/identities/user.rs | 21 ++- matrix_sdk_crypto/src/key_request.rs | 16 +- matrix_sdk_crypto/src/machine.rs | 20 ++- matrix_sdk_crypto/src/olm/account.rs | 24 ++- .../src/olm/group_sessions/inbound.rs | 24 ++- .../src/olm/group_sessions/mod.rs | 3 +- .../src/olm/group_sessions/outbound.rs | 34 ++-- matrix_sdk_crypto/src/olm/mod.rs | 11 +- matrix_sdk_crypto/src/olm/session.rs | 19 +-- matrix_sdk_crypto/src/olm/signing/mod.rs | 19 ++- .../src/olm/signing/pk_signing.rs | 27 ++-- matrix_sdk_crypto/src/olm/utility.rs | 10 +- matrix_sdk_crypto/src/requests.rs | 1 - .../src/session_manager/group_sessions.rs | 3 +- .../src/session_manager/sessions.rs | 4 +- matrix_sdk_crypto/src/store/caches.rs | 3 +- matrix_sdk_crypto/src/store/memorystore.rs | 3 +- matrix_sdk_crypto/src/store/mod.rs | 16 +- matrix_sdk_crypto/src/store/pickle_key.rs | 3 +- matrix_sdk_crypto/src/store/sled.rs | 38 ++--- matrix_sdk_crypto/src/verification/machine.rs | 5 +- matrix_sdk_crypto/src/verification/mod.rs | 11 +- .../src/verification/requests.rs | 6 +- .../src/verification/sas/helpers.rs | 19 +-- .../src/verification/sas/inner_sas.rs | 12 +- matrix_sdk_crypto/src/verification/sas/mod.rs | 21 +-- .../src/verification/sas/sas_state.rs | 12 +- matrix_sdk_test/src/lib.rs | 4 +- matrix_sdk_test/src/test_json/mod.rs | 3 +- rustfmt.toml | 5 + 71 files changed, 378 insertions(+), 468 deletions(-) create mode 100644 rustfmt.toml diff --git a/matrix_sdk/examples/autojoin.rs b/matrix_sdk/examples/autojoin.rs index f3f2ade2..e5ae48e4 100644 --- a/matrix_sdk/examples/autojoin.rs +++ b/matrix_sdk/examples/autojoin.rs @@ -1,5 +1,4 @@ use std::{env, process::exit}; -use tokio::time::{sleep, Duration}; use matrix_sdk::{ self, async_trait, @@ -7,6 +6,7 @@ use matrix_sdk::{ room::Room, Client, ClientConfig, EventHandler, SyncSettings, }; +use tokio::time::{sleep, Duration}; use url::Url; struct AutoJoinBot { diff --git a/matrix_sdk/examples/cross_signing_bootstrap.rs b/matrix_sdk/examples/cross_signing_bootstrap.rs index 03e771fa..01c992ca 100644 --- a/matrix_sdk/examples/cross_signing_bootstrap.rs +++ b/matrix_sdk/examples/cross_signing_bootstrap.rs @@ -5,12 +5,11 @@ use std::{ sync::atomic::{AtomicBool, Ordering}, }; -use serde_json::json; -use url::Url; - use matrix_sdk::{ self, api::r0::uiaa::AuthData, identifiers::UserId, Client, LoopCtrl, SyncSettings, }; +use serde_json::json; +use url::Url; fn auth_data<'a>(user: &UserId, password: &str, session: Option<&'a str>) -> AuthData<'a> { let mut auth_parameters = BTreeMap::new(); diff --git a/matrix_sdk/examples/emoji_verification.rs b/matrix_sdk/examples/emoji_verification.rs index e3f25136..073decd0 100644 --- a/matrix_sdk/examples/emoji_verification.rs +++ b/matrix_sdk/examples/emoji_verification.rs @@ -6,7 +6,6 @@ use std::{ Arc, }, }; -use url::Url; use matrix_sdk::{ self, @@ -14,6 +13,7 @@ use matrix_sdk::{ identifiers::UserId, Client, LoopCtrl, Sas, SyncSettings, }; +use url::Url; async fn wait_for_confirmation(client: Client, sas: Sas) { println!("Does the emoji match: {:?}", sas.emoji()); diff --git a/matrix_sdk/examples/get_profiles.rs b/matrix_sdk/examples/get_profiles.rs index 042da8b4..e0da6f12 100644 --- a/matrix_sdk/examples/get_profiles.rs +++ b/matrix_sdk/examples/get_profiles.rs @@ -1,13 +1,12 @@ use std::{convert::TryFrom, env, process::exit}; -use url::Url; - use matrix_sdk::{ self, api::r0::profile, identifiers::{MxcUri, UserId}, Client, Result as MatrixResult, }; +use url::Url; #[derive(Debug)] struct UserProfile { diff --git a/matrix_sdk/examples/image_bot.rs b/matrix_sdk/examples/image_bot.rs index 6e2cb34c..6a7baef1 100644 --- a/matrix_sdk/examples/image_bot.rs +++ b/matrix_sdk/examples/image_bot.rs @@ -6,7 +6,6 @@ use std::{ process::exit, sync::Arc, }; -use tokio::sync::Mutex; use matrix_sdk::{ self, async_trait, @@ -17,6 +16,7 @@ use matrix_sdk::{ room::Room, Client, EventHandler, SyncSettings, }; +use tokio::sync::Mutex; use url::Url; struct ImageBot { diff --git a/matrix_sdk/examples/login.rs b/matrix_sdk/examples/login.rs index 2bb10ac4..783cb415 100644 --- a/matrix_sdk/examples/login.rs +++ b/matrix_sdk/examples/login.rs @@ -1,5 +1,4 @@ use std::{env, process::exit}; -use url::Url; use matrix_sdk::{ self, async_trait, @@ -10,6 +9,7 @@ use matrix_sdk::{ room::Room, Client, EventHandler, SyncSettings, }; +use url::Url; struct EventCallback; diff --git a/matrix_sdk/src/client.rs b/matrix_sdk/src/client.rs index cacd998e..1f6cec65 100644 --- a/matrix_sdk/src/client.rs +++ b/matrix_sdk/src/client.rs @@ -35,6 +35,15 @@ use futures_timer::Delay as sleep; use http::HeaderValue; #[cfg(feature = "sso_login")] use http::Response; +#[cfg(feature = "encryption")] +use matrix_sdk_base::crypto::{ + decrypt_key_export, encrypt_key_export, olm::InboundGroupSession, store::CryptoStoreError, + OutgoingRequests, RoomMessageRequest, ToDeviceRequest, +}; +use matrix_sdk_base::{ + deserialized_responses::SyncResponse, events::AnyMessageEventContent, identifiers::MxcUri, + BaseClient, BaseClientConfig, SendAccessToken, Session, Store, +}; use mime::{self, Mime}; #[cfg(feature = "sso_login")] use rand::{thread_rng, Rng}; @@ -43,27 +52,15 @@ use reqwest::header::InvalidHeaderValue; use tokio::{net::TcpListener, sync::oneshot}; #[cfg(feature = "sso_login")] use tokio_stream::wrappers::TcpListenerStream; +#[cfg(feature = "encryption")] +use tracing::{debug, warn}; +use tracing::{error, info, instrument}; use url::Url; #[cfg(feature = "sso_login")] use warp::Filter; #[cfg(feature = "encryption")] use zeroize::Zeroizing; -#[cfg(feature = "encryption")] -use tracing::{debug, warn}; -use tracing::{error, info, instrument}; - -use matrix_sdk_base::{ - deserialized_responses::SyncResponse, events::AnyMessageEventContent, identifiers::MxcUri, - BaseClient, BaseClientConfig, SendAccessToken, Session, Store, -}; - -#[cfg(feature = "encryption")] -use matrix_sdk_base::crypto::{ - decrypt_key_export, encrypt_key_export, olm::InboundGroupSession, store::CryptoStoreError, - OutgoingRequests, RoomMessageRequest, ToDeviceRequest, -}; - /// Enum controlling if a loop running callbacks should continue or abort. /// /// This is mainly used in the [`sync_with_callback`] method, the return value @@ -96,12 +93,11 @@ use matrix_sdk_common::{ assign, identifiers::{DeviceIdBox, RoomId, RoomIdOrAliasId, ServerName, UserId}, instant::{Duration, Instant}, - locks::RwLock, + locks::{Mutex, RwLock}, presence::PresenceState, uuid::Uuid, FromHttpResponseError, UInt, }; - #[cfg(feature = "encryption")] use matrix_sdk_common::{ api::r0::{ @@ -113,15 +109,6 @@ use matrix_sdk_common::{ identifiers::EventId, }; -use matrix_sdk_common::locks::Mutex; - -use crate::{ - error::HttpError, - event_handler::Handler, - http_client::{client_with_config, HttpClient, HttpSend}, - room, Error, EventHandler, OutgoingRequest, Result, -}; - #[cfg(feature = "encryption")] use crate::{ device::{Device, UserDevices}, @@ -129,6 +116,12 @@ use crate::{ sas::Sas, verification_request::VerificationRequest, }; +use crate::{ + error::HttpError, + event_handler::Handler, + http_client::{client_with_config, HttpClient, HttpSend}, + room, Error, EventHandler, OutgoingRequest, Result, +}; const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(10); const DEFAULT_SYNC_TIMEOUT: Duration = Duration::from_secs(30); @@ -374,8 +367,7 @@ impl<'a> SyncSettings<'a> { /// This does nothing if no sync token is set. /// /// # Arguments - /// * `full_state` - A boolean deciding if the server should return the full - /// state or not. + /// * `full_state` - A boolean deciding if the server should return the full state or not. pub fn full_state(mut self, full_state: bool) -> Self { self.full_state = full_state; self @@ -440,8 +432,8 @@ impl RequestConfig { Default::default() } - /// This is a convince method to disable the retries of a request. Setting the `retry_limit` to `0` - /// has the same effect. + /// This is a convince method to disable the retries of a request. Setting the `retry_limit` to + /// `0` has the same effect. pub fn disable_retry(mut self) -> Self { self.retry_limit = Some(0); self @@ -459,7 +451,8 @@ impl RequestConfig { self } - /// Set a timeout for how long a request should be retried. The default is no timeout, meaning requests are retried forever. + /// Set a timeout for how long a request should be retried. The default is no timeout, meaning + /// requests are retried forever. pub fn retry_timeout(mut self, retry_timeout: Duration) -> Self { self.retry_timeout = Some(retry_timeout); self @@ -877,8 +870,7 @@ impl Client { /// /// # Arguments /// - /// * `redirect_url` - The URL that will receive a `loginToken` after a - /// successful SSO login. + /// * `redirect_url` - The URL that will receive a `loginToken` after a successful SSO login. /// /// [`login_with_token`]: #method.login_with_token pub fn get_sso_login_url(&self, redirect_url: &str) -> Result { @@ -908,10 +900,10 @@ impl Client { /// /// * `password` - The password of the user. /// - /// * `device_id` - A unique id that will be associated with this session. If - /// not given the homeserver will create one. Can be an existing - /// device_id from a previous login call. Note that this should be done - /// only if the client also holds the encryption keys for this device. + /// * `device_id` - A unique id that will be associated with this session. If not given the + /// homeserver will create one. Can be an existing device_id from a previous login call. Note + /// that this should be done only if the client also holds the encryption keys for this + /// device. /// /// # Example /// ```no_run @@ -986,27 +978,24 @@ impl Client { /// /// # Arguments /// - /// * `use_sso_login_url` - A callback that will receive the SSO Login URL. It - /// should usually be used to open the SSO URL in a browser and must return - /// `Ok(())` if the URL was successfully opened. If it returns `Err`, the - /// error will be forwarded. + /// * `use_sso_login_url` - A callback that will receive the SSO Login URL. It should usually be + /// used to open the SSO URL in a browser and must return `Ok(())` if the URL was successfully + /// opened. If it returns `Err`, the error will be forwarded. /// - /// * `server_url` - The local URL the server is going to try to bind to, e.g. - /// `http://localhost:3030`. If `None`, the server will try to open a random - /// port on localhost. + /// * `server_url` - The local URL the server is going to try to bind to, e.g. `http://localhost:3030`. + /// If `None`, the server will try to open a random port on localhost. /// - /// * `server_response` - The text that will be shown on the webpage at the end - /// of the login process. This can be an HTML page. If `None`, a default - /// text will be displayed. + /// * `server_response` - The text that will be shown on the webpage at the end of the login + /// process. This can be an HTML page. If `None`, a default text will be displayed. /// - /// * `device_id` - A unique id that will be associated with this session. If - /// not given the homeserver will create one. Can be an existing device_id - /// from a previous login call. Note that this should be provided only - /// if the client also holds the encryption keys for this device. + /// * `device_id` - A unique id that will be associated with this session. If not given the + /// homeserver will create one. Can be an existing device_id from a previous login call. Note + /// that this should be provided only if the client also holds the encryption keys for this + /// device. /// - /// * `initial_device_display_name` - A public display name that will be - /// associated with the device_id. Only necessary the first time you - /// login with this device_id. It can be changed later. + /// * `initial_device_display_name` - A public display name that will be associated with the + /// device_id. Only necessary the first time you login with this device_id. It can be changed + /// later. /// /// # Example /// ```no_run @@ -1172,14 +1161,14 @@ impl Client { /// /// * `token` - A login token. /// - /// * `device_id` - A unique id that will be associated with this session. If - /// not given the homeserver will create one. Can be an existing device_id - /// from a previous login call. Note that this should be provided only - /// if the client also holds the encryption keys for this device. + /// * `device_id` - A unique id that will be associated with this session. If not given the + /// homeserver will create one. Can be an existing device_id from a previous login call. Note + /// that this should be provided only if the client also holds the encryption keys for this + /// device. /// - /// * `initial_device_display_name` - A public display name that will be - /// associated with the device_id. Only necessary the first time you - /// login with this device_id. It can be changed later. + /// * `initial_device_display_name` - A public display name that will be associated with the + /// device_id. Only necessary the first time you login with this device_id. It can be changed + /// later. /// /// # Example /// ```no_run @@ -1853,8 +1842,8 @@ impl Client { /// /// # Arguments /// - /// * `sync_settings` - Settings for the sync call. Note that those settings - /// will be only used for the first sync call. + /// * `sync_settings` - Settings for the sync call. Note that those settings will be only used + /// for the first sync call. /// /// [`sync_with_callback`]: #method.sync_with_callback pub async fn sync(&self, sync_settings: SyncSettings<'_>) { @@ -1866,14 +1855,13 @@ impl Client { /// /// # Arguments /// - /// * `sync_settings` - Settings for the sync call. Note that those settings - /// will be only used for the first sync call. + /// * `sync_settings` - Settings for the sync call. Note that those settings will be only used + /// for the first sync call. /// - /// * `callback` - A callback that will be called every time a successful - /// response has been fetched from the server. The callback must return - /// a boolean which signalizes if the method should stop syncing. If the - /// callback returns `LoopCtrl::Continue` the sync will continue, if the - /// callback returns `LoopCtrl::Break` the sync will be stopped. + /// * `callback` - A callback that will be called every time a successful response has been + /// fetched from the server. The callback must return a boolean which signalizes if the method + /// should stop syncing. If the callback returns `LoopCtrl::Continue` the sync will continue, + /// if the callback returns `LoopCtrl::Break` the sync will be stopped. /// /// # Examples /// @@ -2035,7 +2023,6 @@ impl Client { /// # Arguments /// /// * `users` - The list of user/device pairs that we should claim keys for. - /// #[cfg(feature = "encryption")] #[cfg_attr(feature = "docs", doc(cfg(encryption)))] #[instrument(skip(users))] @@ -2453,12 +2440,8 @@ impl Client { #[cfg(test)] mod test { - use crate::{ClientConfig, HttpError, RequestConfig, RoomMember}; + use std::{collections::BTreeMap, convert::TryInto, io::Cursor, str::FromStr, time::Duration}; - use super::{ - get_public_rooms, get_public_rooms_filtered, register::RegistrationKind, Client, Session, - SyncSettings, Url, - }; use matrix_sdk_base::identifiers::mxc_uri; use matrix_sdk_common::{ api::r0::{ @@ -2476,7 +2459,11 @@ mod test { use mockito::{mock, Matcher}; use serde_json::json; - use std::{collections::BTreeMap, convert::TryInto, io::Cursor, str::FromStr, time::Duration}; + use super::{ + get_public_rooms, get_public_rooms_filtered, register::RegistrationKind, Client, Session, + SyncSettings, Url, + }; + use crate::{ClientConfig, HttpError, RequestConfig, RoomMember}; async fn logged_in_client() -> Client { let session = Session { @@ -2834,7 +2821,8 @@ mod test { let room_id = room_id!("!testroom:example.org"); assert_eq!( - // this is the `join_by_room_id::Response` but since no PartialEq we check the RoomId field + // this is the `join_by_room_id::Response` but since no PartialEq we check the RoomId + // field client.join_room_by_id(&room_id).await.unwrap().room_id, room_id ); @@ -2856,7 +2844,8 @@ mod test { let room_id = room_id!("!testroom:example.org").into(); assert_eq!( - // this is the `join_by_room_id::Response` but since no PartialEq we check the RoomId field + // this is the `join_by_room_id::Response` but since no PartialEq we check the RoomId + // field client .join_room_by_id_or_alias(&room_id, &["server.com".try_into().unwrap()]) .await diff --git a/matrix_sdk/src/error.rs b/matrix_sdk/src/error.rs index 8f647e4d..78434441 100644 --- a/matrix_sdk/src/error.rs +++ b/matrix_sdk/src/error.rs @@ -14,7 +14,11 @@ //! Error conditions. +use std::io::Error as IoError; + use http::StatusCode; +#[cfg(feature = "encryption")] +use matrix_sdk_base::crypto::store::CryptoStoreError; use matrix_sdk_base::{Error as MatrixError, StoreError}; use matrix_sdk_common::{ api::{ @@ -26,12 +30,8 @@ use matrix_sdk_common::{ }; use reqwest::Error as ReqwestError; use serde_json::Error as JsonError; -use std::io::Error as IoError; use thiserror::Error; -#[cfg(feature = "encryption")] -use matrix_sdk_base::crypto::store::CryptoStoreError; - /// Result type of the rust-sdk. pub type Result = std::result::Result; diff --git a/matrix_sdk/src/event_handler/mod.rs b/matrix_sdk/src/event_handler/mod.rs index 69c73418..99840e9d 100644 --- a/matrix_sdk/src/event_handler/mod.rs +++ b/matrix_sdk/src/event_handler/mod.rs @@ -56,7 +56,6 @@ use crate::{ room::Room, Client, }; -use matrix_sdk_common::async_trait; pub(crate) struct Handler { pub(crate) inner: Box, @@ -341,8 +340,8 @@ pub enum CustomEvent<'c> { StrippedState(&'c StrippedStateEvent), } -/// This trait allows any type implementing `EventHandler` to specify event callbacks for each event. -/// The `Client` calls each method when the corresponding event is received. +/// This trait allows any type implementing `EventHandler` to specify event callbacks for each +/// event. The `Client` calls each method when the corresponding event is received. /// /// # Examples /// ``` @@ -539,15 +538,16 @@ pub trait EventHandler: Send + Sync { #[cfg(test)] mod test { - use super::*; + use std::{sync::Arc, time::Duration}; + use matrix_sdk_common::{async_trait, locks::Mutex}; use matrix_sdk_test::{async_test, test_json}; use mockito::{mock, Matcher}; - use std::{sync::Arc, time::Duration}; - #[cfg(target_arch = "wasm32")] pub use wasm_bindgen_test::*; + use super::*; + #[derive(Clone)] pub struct EvHandlerTest(Arc>>); @@ -656,7 +656,8 @@ mod test { async fn on_stripped_state_name(&self, _: Room, _: &StrippedStateEvent) { self.0.lock().await.push("stripped state name".to_string()) } - /// Fires when `Client` receives a `AnyStrippedStateEvent::StrippedRoomCanonicalAlias` event. + /// Fires when `Client` receives a `AnyStrippedStateEvent::StrippedRoomCanonicalAlias` + /// event. async fn on_stripped_state_canonical_alias( &self, _: Room, diff --git a/matrix_sdk/src/http_client.rs b/matrix_sdk/src/http_client.rs index 4f91143a..9a3f310a 100644 --- a/matrix_sdk/src/http_client.rs +++ b/matrix_sdk/src/http_client.rs @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +#[cfg(all(not(target_arch = "wasm32")))] +use std::sync::atomic::{AtomicU64, Ordering}; use std::{convert::TryFrom, fmt::Debug, sync::Arc}; #[cfg(all(not(target_arch = "wasm32")))] @@ -19,16 +21,13 @@ use backoff::{future::retry, Error as RetryError, ExponentialBackoff}; #[cfg(all(not(target_arch = "wasm32")))] use http::StatusCode; use http::{HeaderValue, Response as HttpResponse}; -use reqwest::{Client, Response}; -#[cfg(all(not(target_arch = "wasm32")))] -use std::sync::atomic::{AtomicU64, Ordering}; -use tracing::trace; -use url::Url; - use matrix_sdk_common::{ api::r0::media::create_content, async_trait, locks::RwLock, AsyncTraitDeps, AuthScheme, FromHttpResponseError, IncomingResponse, SendAccessToken, }; +use reqwest::{Client, Response}; +use tracing::trace; +use url::Url; use crate::{ error::HttpError, Bytes, BytesMut, ClientConfig, OutgoingRequest, RequestConfig, Session, diff --git a/matrix_sdk/src/lib.rs b/matrix_sdk/src/lib.rs index 4ebc7ef1..9ee9fb2a 100644 --- a/matrix_sdk/src/lib.rs +++ b/matrix_sdk/src/lib.rs @@ -71,6 +71,7 @@ compile_error!("only one of 'native-tls' or 'rustls-tls' features can be enabled #[cfg(all(feature = "sso_login", target_arch = "wasm32"))] compile_error!("'sso_login' cannot be enabled on 'wasm32' arch"); +pub use bytes::{Bytes, BytesMut}; #[cfg(feature = "encryption")] #[cfg_attr(feature = "docs", doc(cfg(encryption)))] pub use matrix_sdk_base::crypto::{EncryptionInfo, LocalTrust}; @@ -78,8 +79,6 @@ pub use matrix_sdk_base::{ Error as BaseError, Room as BaseRoom, RoomInfo, RoomMember as BaseRoomMember, RoomType, Session, StateChanges, StoreError, }; - -pub use bytes::{Bytes, BytesMut}; pub use matrix_sdk_common::*; pub use reqwest; diff --git a/matrix_sdk/src/room/common.rs b/matrix_sdk/src/room/common.rs index 42857f6b..d02a7244 100644 --- a/matrix_sdk/src/room/common.rs +++ b/matrix_sdk/src/room/common.rs @@ -1,3 +1,5 @@ +use std::{ops::Deref, sync::Arc}; + use matrix_sdk_base::{deserialized_responses::MembersResponse, identifiers::UserId}; use matrix_sdk_common::{ api::r0::{ @@ -8,8 +10,6 @@ use matrix_sdk_common::{ locks::Mutex, }; -use std::{ops::Deref, sync::Arc}; - use crate::{BaseRoom, Client, Result, RoomMember}; /// A struct containing methodes that are common for Joined, Invited and Left Rooms @@ -295,7 +295,6 @@ impl Common { /// /// * `user_id` - The ID of the user that should be fetched out of the /// store. - /// pub async fn get_member_no_sync(&self, user_id: &UserId) -> Result> { Ok(self .inner diff --git a/matrix_sdk/src/room/invited.rs b/matrix_sdk/src/room/invited.rs index 879ce58a..3ac6f3ef 100644 --- a/matrix_sdk/src/room/invited.rs +++ b/matrix_sdk/src/room/invited.rs @@ -1,6 +1,7 @@ -use crate::{room::Common, BaseRoom, Client, Result, RoomType}; use std::ops::Deref; +use crate::{room::Common, BaseRoom, Client, Result, RoomType}; + /// A room in the invited state. /// /// This struct contains all methodes specific to a `Room` with type `RoomType::Invited`. diff --git a/matrix_sdk/src/room/joined.rs b/matrix_sdk/src/room/joined.rs index 098e722d..0c908b7b 100644 --- a/matrix_sdk/src/room/joined.rs +++ b/matrix_sdk/src/room/joined.rs @@ -1,9 +1,11 @@ -use crate::{room::Common, BaseRoom, Client, Result, RoomType}; +#[cfg(feature = "encryption")] +use std::sync::Arc; use std::{io::Read, ops::Deref}; #[cfg(feature = "encryption")] -use std::sync::Arc; - +use matrix_sdk_base::crypto::AttachmentEncryptor; +#[cfg(feature = "encryption")] +use matrix_sdk_common::locks::Mutex; use matrix_sdk_common::{ api::r0::{ membership::{ @@ -34,18 +36,12 @@ use matrix_sdk_common::{ receipt::ReceiptType, uuid::Uuid, }; - use mime::{self, Mime}; - -#[cfg(feature = "encryption")] -use matrix_sdk_common::locks::Mutex; - -#[cfg(feature = "encryption")] -use matrix_sdk_base::crypto::AttachmentEncryptor; - #[cfg(feature = "encryption")] use tracing::instrument; +use crate::{room::Common, BaseRoom, Client, Result, RoomType}; + const TYPING_NOTICE_TIMEOUT: Duration = Duration::from_secs(4); const TYPING_NOTICE_RESEND_TIMEOUT: Duration = Duration::from_secs(3); @@ -149,9 +145,9 @@ impl Joined { /// Activate typing notice for this room. /// /// The typing notice remains active for 4s. It can be deactivate at any point by setting - /// typing to `false`. If this method is called while the typing notice is active nothing will happen. - /// This method can be called on every key stroke, since it will do nothing while typing is - /// active. + /// typing to `false`. If this method is called while the typing notice is active nothing will + /// happen. This method can be called on every key stroke, since it will do nothing while + /// typing is active. /// /// # Arguments /// diff --git a/matrix_sdk/src/room/left.rs b/matrix_sdk/src/room/left.rs index b49940d5..5f2feaa8 100644 --- a/matrix_sdk/src/room/left.rs +++ b/matrix_sdk/src/room/left.rs @@ -1,8 +1,9 @@ -use crate::{room::Common, BaseRoom, Client, Result, RoomType}; use std::ops::Deref; use matrix_sdk_common::api::r0::membership::forget_room; +use crate::{room::Common, BaseRoom, Client, Result, RoomType}; + /// A room in the left state. /// /// This struct contains all methodes specific to a `Room` with type `RoomType::Left`. diff --git a/matrix_sdk/src/room_member.rs b/matrix_sdk/src/room_member.rs index 81c66fce..f8d68b43 100644 --- a/matrix_sdk/src/room_member.rs +++ b/matrix_sdk/src/room_member.rs @@ -1,7 +1,7 @@ -use matrix_sdk_common::api::r0::media::{get_content, get_content_thumbnail}; - use std::ops::Deref; +use matrix_sdk_common::api::r0::media::{get_content, get_content_thumbnail}; + use crate::{BaseRoomMember, Client, Result}; /// The high-level `RoomMember` representation diff --git a/matrix_sdk_appservice/src/actix.rs b/matrix_sdk_appservice/src/actix.rs index e260e822..a55503cf 100644 --- a/matrix_sdk_appservice/src/actix.rs +++ b/matrix_sdk_appservice/src/actix.rs @@ -17,6 +17,7 @@ use std::{ pin::Pin, }; +pub use actix_web::Scope; use actix_web::{ dev::Payload, error::PayloadError, @@ -30,8 +31,6 @@ use futures::Future; use futures_util::{TryFutureExt, TryStreamExt}; use matrix_sdk::api_appservice as api; -pub use actix_web::Scope; - use crate::{error::Error, Appservice}; pub async fn run_server( diff --git a/matrix_sdk_appservice/src/lib.rs b/matrix_sdk_appservice/src/lib.rs index 3f40bacc..330a196a 100644 --- a/matrix_sdk_appservice/src/lib.rs +++ b/matrix_sdk_appservice/src/lib.rs @@ -18,7 +18,8 @@ //! * ship with functionality to configure your webserver crate or simply run the webserver for you //! * receive and validate requests from the homeserver correctly //! * allow calling the homeserver with proper virtual user identity assertion -//! * have the goal to have a consistent room state available by leveraging the stores that the matrix-sdk provides +//! * have the goal to have a consistent room state available by leveraging the stores that the +//! matrix-sdk provides //! //! # Quickstart //! @@ -62,6 +63,8 @@ use std::{ }; use http::Uri; +#[doc(inline)] +pub use matrix_sdk::api_appservice as api; use matrix_sdk::{ api::{ error::ErrorKind, @@ -81,9 +84,6 @@ use regex::Regex; use tracing::error; use tracing::warn; -#[doc(inline)] -pub use matrix_sdk::api_appservice as api; - #[cfg(feature = "actix")] mod actix; mod error; diff --git a/matrix_sdk_appservice/tests/actix.rs b/matrix_sdk_appservice/tests/actix.rs index eab23010..bee418b5 100644 --- a/matrix_sdk_appservice/tests/actix.rs +++ b/matrix_sdk_appservice/tests/actix.rs @@ -1,8 +1,9 @@ #[cfg(feature = "actix")] mod actix { + use std::env; + use actix_web::{test, App}; use matrix_sdk_appservice::*; - use std::env; async fn appservice() -> Appservice { env::set_var( @@ -109,7 +110,8 @@ mod actix { let resp = test::call_service(&app, req).await; - // TODO: this should actually return a 401 but is 500 because something in the extractor fails + // TODO: this should actually return a 401 but is 500 because something in the extractor + // fails assert_eq!(resp.status(), 500); } } diff --git a/matrix_sdk_base/examples/state_inspector.rs b/matrix_sdk_base/examples/state_inspector.rs index 9c358283..f03cb05c 100644 --- a/matrix_sdk_base/examples/state_inspector.rs +++ b/matrix_sdk_base/examples/state_inspector.rs @@ -1,12 +1,15 @@ use std::{convert::TryFrom, fmt::Debug, sync::Arc}; -use futures::executor::block_on; -use serde::Serialize; - #[cfg(not(target_arch = "wasm32"))] use atty::Stream; #[cfg(not(target_arch = "wasm32"))] use clap::{App as Argparse, AppSettings as ArgParseSettings, Arg, ArgMatches, SubCommand}; +use futures::executor::block_on; +use matrix_sdk_base::{ + events::EventType, + identifiers::{RoomId, UserId}, + RoomInfo, Store, +}; #[cfg(not(target_arch = "wasm32"))] use rustyline::{ completion::{Completer, Pair}, @@ -18,7 +21,7 @@ use rustyline::{ }; #[cfg(not(target_arch = "wasm32"))] use rustyline_derive::Helper; - +use serde::Serialize; #[cfg(not(target_arch = "wasm32"))] use syntect::{ dumps::from_binary, @@ -28,12 +31,6 @@ use syntect::{ util::{as_24_bit_terminal_escaped, LinesWithEndings}, }; -use matrix_sdk_base::{ - events::EventType, - identifiers::{RoomId, UserId}, - RoomInfo, Store, -}; - #[derive(Clone)] #[cfg(not(target_arch = "wasm32"))] struct Inspector { diff --git a/matrix_sdk_base/src/client.rs b/matrix_sdk_base/src/client.rs index bc3c382d..a407703e 100644 --- a/matrix_sdk_base/src/client.rs +++ b/matrix_sdk_base/src/client.rs @@ -1223,11 +1223,10 @@ impl BaseClient { /// /// # Arguments /// - /// * `flow_id` - The unique id that identifies a interactive verification - /// flow. For in-room verifications this will be the event id of the - /// *m.key.verification.request* event that started the flow, for the - /// to-device verification flows this will be the transaction id of the - /// *m.key.verification.start* event. + /// * `flow_id` - The unique id that identifies a interactive verification flow. For in-room + /// verifications this will be the event id of the *m.key.verification.request* event that + /// started the flow, for the to-device verification flows this will be the transaction id of + /// the *m.key.verification.start* event. #[cfg(feature = "encryption")] #[cfg_attr(feature = "docs", doc(cfg(encryption)))] pub async fn get_verification(&self, flow_id: &str) -> Option { diff --git a/matrix_sdk_base/src/error.rs b/matrix_sdk_base/src/error.rs index a7946f57..5c944b83 100644 --- a/matrix_sdk_base/src/error.rs +++ b/matrix_sdk_base/src/error.rs @@ -15,12 +15,12 @@ //! Error conditions. -use serde_json::Error as JsonError; use std::io::Error as IoError; -use thiserror::Error; #[cfg(feature = "encryption")] use matrix_sdk_crypto::{CryptoStoreError, MegolmError, OlmError}; +use serde_json::Error as JsonError; +use thiserror::Error; /// Result type of the rust-sdk. pub type Result = std::result::Result; diff --git a/matrix_sdk_base/src/lib.rs b/matrix_sdk_base/src/lib.rs index 7d70a216..358f69ea 100644 --- a/matrix_sdk_base/src/lib.rs +++ b/matrix_sdk_base/src/lib.rs @@ -36,11 +36,12 @@ )] #![cfg_attr(feature = "docs", feature(doc_cfg))] +pub use matrix_sdk_common::*; + pub use crate::{ error::{Error, Result}, session::Session, }; -pub use matrix_sdk_common::*; mod client; mod error; @@ -48,11 +49,9 @@ mod rooms; mod session; mod store; -pub use rooms::{Room, RoomInfo, RoomMember, RoomType}; -pub use store::{StateChanges, StateStore, Store, StoreError}; - pub use client::{BaseClient, BaseClientConfig}; - #[cfg(feature = "encryption")] #[cfg_attr(feature = "docs", doc(cfg(encryption)))] pub use matrix_sdk_crypto as crypto; +pub use rooms::{Room, RoomInfo, RoomMember, RoomType}; +pub use store::{StateChanges, StateStore, Store, StoreError}; diff --git a/matrix_sdk_base/src/rooms/mod.rs b/matrix_sdk_base/src/rooms/mod.rs index c9378444..5b549b03 100644 --- a/matrix_sdk_base/src/rooms/mod.rs +++ b/matrix_sdk_base/src/rooms/mod.rs @@ -1,27 +1,22 @@ mod members; mod normal; -use matrix_sdk_common::{ - events::room::{ - create::CreateEventContent, guest_access::GuestAccess, - history_visibility::HistoryVisibility, join_rules::JoinRule, - }, - identifiers::{MxcUri, UserId}, -}; -pub use normal::{Room, RoomInfo, RoomType}; - -pub use members::RoomMember; - -use serde::{Deserialize, Serialize}; use std::cmp::max; use matrix_sdk_common::{ events::{ - room::{encryption::EncryptionEventContent, tombstone::TombstoneEventContent}, + room::{ + create::CreateEventContent, encryption::EncryptionEventContent, + guest_access::GuestAccess, history_visibility::HistoryVisibility, join_rules::JoinRule, + tombstone::TombstoneEventContent, + }, AnyStateEventContent, }, - identifiers::RoomAliasId, + identifiers::{MxcUri, RoomAliasId, UserId}, }; +pub use members::RoomMember; +pub use normal::{Room, RoomInfo, RoomType}; +use serde::{Deserialize, Serialize}; /// A base room info struct that is the backbone of normal as well as stripped /// rooms. Holds all the state events that are important to present a room to diff --git a/matrix_sdk_base/src/rooms/normal.rs b/matrix_sdk_base/src/rooms/normal.rs index 8929aee6..a5058e22 100644 --- a/matrix_sdk_base/src/rooms/normal.rs +++ b/matrix_sdk_base/src/rooms/normal.rs @@ -37,13 +37,12 @@ use matrix_sdk_common::{ use serde::{Deserialize, Serialize}; use tracing::info; +use super::{BaseRoomInfo, RoomMember}; use crate::{ deserialized_responses::UnreadNotificationsCount, store::{Result as StoreResult, StateStore}, }; -use super::{BaseRoomInfo, RoomMember}; - /// The underlying room data structure collecting state for joined, left and invtied rooms. #[derive(Debug, Clone)] pub struct Room { diff --git a/matrix_sdk_base/src/session.rs b/matrix_sdk_base/src/session.rs index bae61166..33573637 100644 --- a/matrix_sdk_base/src/session.rs +++ b/matrix_sdk_base/src/session.rs @@ -15,9 +15,8 @@ //! User sessions. -use serde::{Deserialize, Serialize}; - use matrix_sdk_common::identifiers::{DeviceId, UserId}; +use serde::{Deserialize, Serialize}; /// A user session, containing an access token and information about the /// associated user account. diff --git a/matrix_sdk_base/src/store/ambiguity_map.rs b/matrix_sdk_base/src/store/ambiguity_map.rs index 3d524d20..bac250ac 100644 --- a/matrix_sdk_base/src/store/ambiguity_map.rs +++ b/matrix_sdk_base/src/store/ambiguity_map.rs @@ -19,12 +19,10 @@ use matrix_sdk_common::{ events::room::member::MembershipState, identifiers::{EventId, RoomId, UserId}, }; - use tracing::trace; -use crate::Store; - use super::{Result, StateChanges}; +use crate::Store; #[derive(Clone, Debug)] pub struct AmbiguityCache { diff --git a/matrix_sdk_base/src/store/memory_store.rs b/matrix_sdk_base/src/store/memory_store.rs index b9346082..b3f2e1b6 100644 --- a/matrix_sdk_base/src/store/memory_store.rs +++ b/matrix_sdk_base/src/store/memory_store.rs @@ -30,12 +30,10 @@ use matrix_sdk_common::{ instant::Instant, Raw, }; - use tracing::info; -use crate::deserialized_responses::{MemberEvent, StrippedMemberEvent}; - use super::{Result, RoomInfo, StateChanges, StateStore}; +use crate::deserialized_responses::{MemberEvent, StrippedMemberEvent}; #[derive(Debug, Clone)] pub struct MemoryStore { diff --git a/matrix_sdk_base/src/store/mod.rs b/matrix_sdk_base/src/store/mod.rs index 62a480b4..18e109e3 100644 --- a/matrix_sdk_base/src/store/mod.rs +++ b/matrix_sdk_base/src/store/mod.rs @@ -12,15 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. +#[cfg(feature = "sled_state_store")] +use std::path::Path; use std::{ collections::{BTreeMap, BTreeSet}, ops::Deref, sync::Arc, }; -#[cfg(feature = "sled_state_store")] -use std::path::Path; - use dashmap::DashMap; use matrix_sdk_common::{ api::r0::push::get_notifications::Notification, @@ -359,7 +358,8 @@ impl Deref for Store { pub struct StateChanges { /// The sync token that relates to this update. pub sync_token: Option, - /// A user session, containing an access token and information about the associated user account. + /// A user session, containing an access token and information about the associated user + /// account. pub session: Option, /// A mapping of event type string to `AnyBasicEvent`. pub account_data: BTreeMap>, @@ -378,7 +378,8 @@ pub struct StateChanges { /// A map of `RoomId` to `RoomInfo`. pub room_infos: BTreeMap, - /// A mapping of `RoomId` to a map of event type to a map of state key to `AnyStrippedStateEvent`. + /// A mapping of `RoomId` to a map of event type to a map of state key to + /// `AnyStrippedStateEvent`. pub stripped_state: BTreeMap>>>, /// A mapping of `RoomId` to a map of users and their `StrippedMemberEvent`. diff --git a/matrix_sdk_base/src/store/sled_store/mod.rs b/matrix_sdk_base/src/store/sled_store/mod.rs index 6f8d0290..c0aab19d 100644 --- a/matrix_sdk_base/src/store/sled_store/mod.rs +++ b/matrix_sdk_base/src/store/sled_store/mod.rs @@ -37,18 +37,15 @@ use matrix_sdk_common::{ Raw, }; use serde::{Deserialize, Serialize}; - use sled::{ transaction::{ConflictableTransactionError, TransactionError}, Config, Db, Transactional, Tree, }; use tracing::info; -use crate::deserialized_responses::MemberEvent; - use self::store_key::{EncryptedEvent, StoreKey}; - use super::{Result, RoomInfo, StateChanges, StateStore, StoreError}; +use crate::deserialized_responses::MemberEvent; #[derive(Debug, Serialize, Deserialize)] pub enum DatabaseType { diff --git a/matrix_sdk_base/src/store/sled_store/store_key.rs b/matrix_sdk_base/src/store/sled_store/store_key.rs index 28d9820b..f1304289 100644 --- a/matrix_sdk_base/src/store/sled_store/store_key.rs +++ b/matrix_sdk_base/src/store/sled_store/store_key.rs @@ -21,11 +21,10 @@ use chacha20poly1305::{ use hmac::Hmac; use pbkdf2::pbkdf2; use rand::{thread_rng, Error as RngError, Fill}; +use serde::{Deserialize, Serialize}; use sha2::Sha256; use zeroize::{Zeroize, Zeroizing}; -use serde::{Deserialize, Serialize}; - use crate::StoreError; const VERSION: u8 = 1; @@ -248,9 +247,10 @@ impl StoreKey { #[cfg(test)] mod test { - use super::StoreKey; use serde_json::{json, Value}; + use super::StoreKey; + #[test] fn generating() { StoreKey::new().unwrap(); diff --git a/matrix_sdk_common/src/deserialized_responses.rs b/matrix_sdk_common/src/deserialized_responses.rs index c8ce70aa..97a897d0 100644 --- a/matrix_sdk_common/src/deserialized_responses.rs +++ b/matrix_sdk_common/src/deserialized_responses.rs @@ -1,3 +1,5 @@ +use std::{collections::BTreeMap, convert::TryFrom, time::SystemTime}; + use ruma::{ api::client::r0::sync::sync_events::{ Ephemeral, InvitedRoom, Presence, RoomAccountData, State, ToDevice, @@ -6,7 +8,6 @@ use ruma::{ DeviceIdBox, }; use serde::{Deserialize, Serialize}; -use std::{collections::BTreeMap, convert::TryFrom, time::SystemTime}; use super::{ api::r0::{ diff --git a/matrix_sdk_common/src/executor.rs b/matrix_sdk_common/src/executor.rs index b8e34f87..6f73a2a7 100644 --- a/matrix_sdk_common/src/executor.rs +++ b/matrix_sdk_common/src/executor.rs @@ -6,14 +6,12 @@ use std::{ task::{Context, Poll}, }; -#[cfg(not(target_arch = "wasm32"))] -pub use tokio::spawn; - -#[cfg(target_arch = "wasm32")] -use wasm_bindgen_futures::spawn_local; - #[cfg(target_arch = "wasm32")] use futures::{future::RemoteHandle, Future, FutureExt}; +#[cfg(not(target_arch = "wasm32"))] +pub use tokio::spawn; +#[cfg(target_arch = "wasm32")] +use wasm_bindgen_futures::spawn_local; #[cfg(target_arch = "wasm32")] pub fn spawn(future: F) -> JoinHandle diff --git a/matrix_sdk_common/src/lib.rs b/matrix_sdk_common/src/lib.rs index 61db16da..5c91e21f 100644 --- a/matrix_sdk_common/src/lib.rs +++ b/matrix_sdk_common/src/lib.rs @@ -17,7 +17,6 @@ pub use ruma::{ serde::{CanonicalJsonValue, Raw}, thirdparty, uint, Int, Outgoing, UInt, }; - pub use uuid; pub mod deserialized_responses; diff --git a/matrix_sdk_common/src/locks.rs b/matrix_sdk_common/src/locks.rs index aebf244b..f3162309 100644 --- a/matrix_sdk_common/src/locks.rs +++ b/matrix_sdk_common/src/locks.rs @@ -4,6 +4,5 @@ #[cfg(target_arch = "wasm32")] pub use futures_locks::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard}; - #[cfg(not(target_arch = "wasm32"))] pub use tokio::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard}; diff --git a/matrix_sdk_crypto/benches/crypto_bench.rs b/matrix_sdk_crypto/benches/crypto_bench.rs index 9fdfab95..6d2193a0 100644 --- a/matrix_sdk_crypto/benches/crypto_bench.rs +++ b/matrix_sdk_crypto/benches/crypto_bench.rs @@ -4,7 +4,6 @@ mod perf; use std::sync::Arc; use criterion::*; - use matrix_sdk_common::{ api::r0::{ keys::{claim_keys, get_keys}, diff --git a/matrix_sdk_crypto/src/file_encryption/attachments.rs b/matrix_sdk_crypto/src/file_encryption/attachments.rs index 1ea0469e..8a53aa4a 100644 --- a/matrix_sdk_crypto/src/file_encryption/attachments.rs +++ b/matrix_sdk_crypto/src/file_encryption/attachments.rs @@ -17,21 +17,17 @@ use std::{ io::{Error as IoError, ErrorKind, Read}, }; -use thiserror::Error; -use zeroize::Zeroizing; - -use serde::{Deserialize, Serialize}; - -use matrix_sdk_common::events::room::JsonWebKey; - -use getrandom::getrandom; - use aes_ctr::{ cipher::{NewStreamCipher, SyncStreamCipher}, Aes256Ctr, }; use base64::DecodeError; +use getrandom::getrandom; +use matrix_sdk_common::events::room::JsonWebKey; +use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; +use thiserror::Error; +use zeroize::Zeroizing; use crate::utilities::{decode, decode_url_safe, encode, encode_url_safe}; @@ -274,10 +270,12 @@ pub struct EncryptionInfo { #[cfg(test)] mod test { - use super::{AttachmentDecryptor, AttachmentEncryptor, EncryptionInfo}; - use serde_json::json; use std::io::{Cursor, Read}; + use serde_json::json; + + use super::{AttachmentDecryptor, AttachmentEncryptor, EncryptionInfo}; + const EXAMPLE_DATA: &[u8] = &[ 179, 154, 118, 127, 186, 127, 110, 33, 203, 33, 33, 134, 67, 100, 173, 46, 235, 27, 215, 172, 36, 26, 75, 47, 33, 160, diff --git a/matrix_sdk_crypto/src/file_encryption/key_export.rs b/matrix_sdk_crypto/src/file_encryption/key_export.rs index c6b2ae70..5257f910 100644 --- a/matrix_sdk_crypto/src/file_encryption/key_export.rs +++ b/matrix_sdk_crypto/src/file_encryption/key_export.rs @@ -12,20 +12,19 @@ // See the License for the specific language governing permissions and // limitations under the License. -use serde_json::Error as SerdeError; use std::io::{Cursor, Read, Seek, SeekFrom}; -use thiserror::Error; - -use byteorder::{BigEndian, ReadBytesExt}; -use getrandom::getrandom; use aes_ctr::{ cipher::{NewStreamCipher, SyncStreamCipher}, Aes256Ctr, }; +use byteorder::{BigEndian, ReadBytesExt}; +use getrandom::getrandom; use hmac::{Hmac, Mac, NewMac}; use pbkdf2::pbkdf2; +use serde_json::Error as SerdeError; use sha2::{Sha256, Sha512}; +use thiserror::Error; use crate::{ olm::ExportedRoomKey, @@ -231,12 +230,12 @@ fn decrypt_helper(ciphertext: &str, passphrase: &str) -> Result DeviceKeys { let device_keys = json!({ diff --git a/matrix_sdk_crypto/src/identities/manager.rs b/matrix_sdk_crypto/src/identities/manager.rs index ed91272e..ada4dae0 100644 --- a/matrix_sdk_crypto/src/identities/manager.rs +++ b/matrix_sdk_crypto/src/identities/manager.rs @@ -12,20 +12,20 @@ // See the License for the specific language governing permissions and // limitations under the License. -use futures::future::join_all; use std::{ collections::{BTreeMap, HashSet}, convert::TryFrom, sync::Arc, }; -use tracing::{trace, warn}; +use futures::future::join_all; use matrix_sdk_common::{ api::r0::keys::get_keys::Response as KeysQueryResponse, encryption::DeviceKeys, executor::spawn, identifiers::{DeviceIdBox, UserId}, }; +use tracing::{trace, warn}; use crate::{ error::OlmResult, @@ -424,9 +424,7 @@ pub(crate) mod test { locks::Mutex, IncomingResponse, }; - use matrix_sdk_test::async_test; - use serde_json::json; use crate::{ diff --git a/matrix_sdk_crypto/src/identities/mod.rs b/matrix_sdk_crypto/src/identities/mod.rs index e9161a0d..6f50a242 100644 --- a/matrix_sdk_crypto/src/identities/mod.rs +++ b/matrix_sdk_crypto/src/identities/mod.rs @@ -44,19 +44,19 @@ pub(crate) mod device; mod manager; pub(crate) mod user; -pub use device::{Device, LocalTrust, ReadOnlyDevice, UserDevices}; -pub(crate) use manager::IdentityManager; -pub use user::{ - MasterPubkey, OwnUserIdentity, SelfSigningPubkey, UserIdentities, UserIdentity, - UserSigningPubkey, -}; - -use serde::{Deserialize, Deserializer, Serializer}; use std::sync::{ atomic::{AtomicBool, Ordering}, Arc, }; +pub use device::{Device, LocalTrust, ReadOnlyDevice, UserDevices}; +pub(crate) use manager::IdentityManager; +use serde::{Deserialize, Deserializer, Serializer}; +pub use user::{ + MasterPubkey, OwnUserIdentity, SelfSigningPubkey, UserIdentities, UserIdentity, + UserSigningPubkey, +}; + // These methods are only here because Serialize and Deserialize don't seem to // be implemented for WASM. fn atomic_bool_serializer(x: &AtomicBool, s: S) -> Result diff --git a/matrix_sdk_crypto/src/identities/user.rs b/matrix_sdk_crypto/src/identities/user.rs index 09beb2dd..eeacc7df 100644 --- a/matrix_sdk_crypto/src/identities/user.rs +++ b/matrix_sdk_crypto/src/identities/user.rs @@ -21,20 +21,18 @@ use std::{ }, }; -use serde::{Deserialize, Serialize}; -use serde_json::to_value; - use matrix_sdk_common::{ api::r0::keys::{CrossSigningKey, KeyUsage}, identifiers::{DeviceKeyId, UserId}, }; +use serde::{Deserialize, Serialize}; +use serde_json::to_value; +use super::{atomic_bool_deserializer, atomic_bool_serializer}; #[cfg(test)] use crate::olm::PrivateCrossSigningIdentity; use crate::{error::SignatureError, olm::Utility, ReadOnlyDevice}; -use super::{atomic_bool_deserializer, atomic_bool_serializer}; - /// Wrapper for a cross signing key marking it as the master key. /// /// Master keys are used to sign other cross signing keys, the self signing and @@ -719,6 +717,12 @@ impl OwnUserIdentity { pub(crate) mod test { use std::{convert::TryFrom, sync::Arc}; + use matrix_sdk_common::{ + api::r0::keys::get_keys::Response as KeyQueryResponse, identifiers::user_id, locks::Mutex, + }; + use matrix_sdk_test::async_test; + + use super::{OwnUserIdentity, UserIdentities, UserIdentity}; use crate::{ identities::{ manager::test::{other_key_query, own_key_query}, @@ -729,13 +733,6 @@ pub(crate) mod test { verification::VerificationMachine, }; - use matrix_sdk_common::{ - api::r0::keys::get_keys::Response as KeyQueryResponse, identifiers::user_id, locks::Mutex, - }; - use matrix_sdk_test::async_test; - - use super::{OwnUserIdentity, UserIdentities, UserIdentity}; - fn device(response: &KeyQueryResponse) -> (ReadOnlyDevice, ReadOnlyDevice) { let mut devices = response.device_keys.values().next().unwrap().values(); let first = ReadOnlyDevice::try_from(devices.next().unwrap()).unwrap(); diff --git a/matrix_sdk_crypto/src/key_request.rs b/matrix_sdk_crypto/src/key_request.rs index 1eec2981..6a12a8d0 100644 --- a/matrix_sdk_crypto/src/key_request.rs +++ b/matrix_sdk_crypto/src/key_request.rs @@ -20,13 +20,9 @@ // If we don't trust the device store an object that remembers the request and // let the users introspect that object. -use dashmap::{mapref::entry::Entry, DashMap, DashSet}; -use serde::{Deserialize, Serialize}; -use serde_json::value::to_raw_value; use std::{collections::BTreeMap, sync::Arc}; -use thiserror::Error; -use tracing::{error, info, trace, warn}; +use dashmap::{mapref::entry::Entry, DashMap, DashSet}; use matrix_sdk_common::{ api::r0::to_device::DeviceIdOrAllDevices, events::{ @@ -37,6 +33,10 @@ use matrix_sdk_common::{ identifiers::{DeviceId, DeviceIdBox, EventEncryptionAlgorithm, RoomId, UserId}, uuid::Uuid, }; +use serde::{Deserialize, Serialize}; +use serde_json::value::to_raw_value; +use thiserror::Error; +use tracing::{error, info, trace, warn}; use crate::{ error::{OlmError, OlmResult}, @@ -817,6 +817,8 @@ impl KeyRequestMachine { #[cfg(test)] mod test { + use std::{convert::TryInto, sync::Arc}; + use dashmap::DashMap; use matrix_sdk_common::{ api::r0::to_device::DeviceIdOrAllDevices, @@ -829,8 +831,8 @@ mod test { locks::Mutex, }; use matrix_sdk_test::async_test; - use std::{convert::TryInto, sync::Arc}; + use super::{KeyRequestMachine, KeyshareDecision}; use crate::{ identities::{LocalTrust, ReadOnlyDevice}, olm::{Account, PrivateCrossSigningIdentity, ReadOnlyAccount}, @@ -839,8 +841,6 @@ mod test { verification::VerificationMachine, }; - use super::{KeyRequestMachine, KeyshareDecision}; - fn alice_id() -> UserId { user_id!("@alice:example.org") } diff --git a/matrix_sdk_crypto/src/machine.rs b/matrix_sdk_crypto/src/machine.rs index be73530d..cdbf4686 100644 --- a/matrix_sdk_crypto/src/machine.rs +++ b/matrix_sdk_crypto/src/machine.rs @@ -17,8 +17,6 @@ use std::path::Path; use std::{collections::BTreeMap, mem, sync::Arc}; use dashmap::DashMap; -use tracing::{debug, error, info, trace, warn}; - use matrix_sdk_common::{ api::r0::{ keys::{ @@ -44,6 +42,7 @@ use matrix_sdk_common::{ uuid::Uuid, UInt, }; +use tracing::{debug, error, info, trace, warn}; #[cfg(feature = "sled_cryptostore")] use crate::store::sled::SledStore; @@ -1276,15 +1275,6 @@ pub(crate) mod test { }; use http::Response; - use serde_json::json; - - use crate::{ - machine::OlmMachine, - olm::Utility, - verification::test::{outgoing_request_to_event, request_to_event}, - EncryptionSettings, ReadOnlyDevice, ToDeviceRequest, - }; - use matrix_sdk_common::{ api::r0::keys::{claim_keys, get_keys, upload_keys, OneTimeKey}, events::{ @@ -1301,6 +1291,14 @@ pub(crate) mod test { IncomingResponse, Raw, }; use matrix_sdk_test::test_json; + use serde_json::json; + + use crate::{ + machine::OlmMachine, + olm::Utility, + verification::test::{outgoing_request_to_event, request_to_event}, + EncryptionSettings, ReadOnlyDevice, ToDeviceRequest, + }; /// These keys need to be periodically uploaded to the server. type OneTimeKeys = BTreeMap; diff --git a/matrix_sdk_crypto/src/olm/account.rs b/matrix_sdk_crypto/src/olm/account.rs index 27f60103..2cdf08cc 100644 --- a/matrix_sdk_crypto/src/olm/account.rs +++ b/matrix_sdk_crypto/src/olm/account.rs @@ -12,10 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -use matrix_sdk_common::events::ToDeviceEvent; -use serde::{Deserialize, Serialize}; -use serde_json::{json, Value}; -use sha2::{Digest, Sha256}; use std::{ collections::BTreeMap, convert::{TryFrom, TryInto}, @@ -26,7 +22,6 @@ use std::{ Arc, }, }; -use tracing::{debug, trace, warn}; #[cfg(test)] use matrix_sdk_common::events::EventType; @@ -37,7 +32,7 @@ use matrix_sdk_common::{ encryption::DeviceKeys, events::{ room::encrypted::{EncryptedEventContent, EncryptedEventScheme}, - AnyToDeviceEvent, + AnyToDeviceEvent, ToDeviceEvent, }, identifiers::{ DeviceId, DeviceIdBox, DeviceKeyAlgorithm, DeviceKeyId, EventEncryptionAlgorithm, RoomId, @@ -53,7 +48,15 @@ use olm_rs::{ session::{OlmMessage, PreKeyMessage}, PicklingMode, }; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use tracing::{debug, trace, warn}; +use super::{ + EncryptionSettings, InboundGroupSession, OutboundGroupSession, PrivateCrossSigningIdentity, + Session, +}; use crate::{ error::{EventError, OlmResult, SessionCreationError}, identities::ReadOnlyDevice, @@ -63,11 +66,6 @@ use crate::{ OlmError, }; -use super::{ - EncryptionSettings, InboundGroupSession, OutboundGroupSession, PrivateCrossSigningIdentity, - Session, -}; - #[derive(Debug, Clone)] pub struct Account { pub(crate) inner: ReadOnlyAccount, @@ -873,8 +871,8 @@ impl ReadOnlyAccount { /// # Arguments /// * `device` - The other account's device. /// - /// * `key_map` - A map from the algorithm and device id to the one-time - /// key that the other account created and shared with us. + /// * `key_map` - A map from the algorithm and device id to the one-time key that the other + /// account created and shared with us. pub(crate) async fn create_outbound_session( &self, device: ReadOnlyDevice, diff --git a/matrix_sdk_crypto/src/olm/group_sessions/inbound.rs b/matrix_sdk_crypto/src/olm/group_sessions/inbound.rs index ee6c1c2c..8120a507 100644 --- a/matrix_sdk_crypto/src/olm/group_sessions/inbound.rs +++ b/matrix_sdk_crypto/src/olm/group_sessions/inbound.rs @@ -19,19 +19,6 @@ use std::{ sync::Arc, }; -use olm_rs::{ - errors::OlmGroupSessionError, inbound_group_session::OlmInboundGroupSession, PicklingMode, -}; -use serde::{Deserialize, Serialize}; -use serde_json::Value; -use zeroize::Zeroizing; - -pub use olm_rs::{ - account::IdentityKeys, - session::{OlmMessage, PreKeyMessage}, - utility::OlmUtility, -}; - use matrix_sdk_common::{ events::{ forwarded_room_key::ForwardedRoomKeyToDeviceEventContent, @@ -45,6 +32,17 @@ use matrix_sdk_common::{ locks::Mutex, Raw, }; +pub use olm_rs::{ + account::IdentityKeys, + session::{OlmMessage, PreKeyMessage}, + utility::OlmUtility, +}; +use olm_rs::{ + errors::OlmGroupSessionError, inbound_group_session::OlmInboundGroupSession, PicklingMode, +}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use zeroize::Zeroizing; use super::{ExportedGroupSessionKey, ExportedRoomKey, GroupSessionKey}; use crate::error::{EventError, MegolmResult}; diff --git a/matrix_sdk_crypto/src/olm/group_sessions/mod.rs b/matrix_sdk_crypto/src/olm/group_sessions/mod.rs index 720ab997..6b9c9839 100644 --- a/matrix_sdk_crypto/src/olm/group_sessions/mod.rs +++ b/matrix_sdk_crypto/src/olm/group_sessions/mod.rs @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::{collections::BTreeMap, convert::TryInto}; + use matrix_sdk_common::{ events::forwarded_room_key::{ ForwardedRoomKeyToDeviceEventContent, ForwardedRoomKeyToDeviceEventContentInit, @@ -19,7 +21,6 @@ use matrix_sdk_common::{ identifiers::{DeviceKeyAlgorithm, EventEncryptionAlgorithm, RoomId}, }; use serde::{Deserialize, Serialize}; -use std::{collections::BTreeMap, convert::TryInto}; use zeroize::Zeroize; mod inbound; diff --git a/matrix_sdk_crypto/src/olm/group_sessions/outbound.rs b/matrix_sdk_crypto/src/olm/group_sessions/outbound.rs index ebff3c95..8ef62baf 100644 --- a/matrix_sdk_crypto/src/olm/group_sessions/outbound.rs +++ b/matrix_sdk_crypto/src/olm/group_sessions/outbound.rs @@ -12,15 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -use dashmap::DashMap; -use matrix_sdk_common::{ - api::r0::to_device::DeviceIdOrAllDevices, - events::room::{ - encrypted::MegolmV1AesSha2ContentInit, history_visibility::HistoryVisibility, - message::Relation, - }, - uuid::Uuid, -}; use std::{ cmp::max, collections::BTreeMap, @@ -31,23 +22,24 @@ use std::{ }, time::Duration, }; -use tracing::{debug, error, trace}; +use dashmap::DashMap; use matrix_sdk_common::{ + api::r0::to_device::DeviceIdOrAllDevices, events::{ room::{ - encrypted::{EncryptedEventContent, EncryptedEventScheme}, + encrypted::{EncryptedEventContent, EncryptedEventScheme, MegolmV1AesSha2ContentInit}, encryption::EncryptionEventContent, + history_visibility::HistoryVisibility, + message::Relation, }, AnyMessageEventContent, EventContent, }, identifiers::{DeviceId, DeviceIdBox, EventEncryptionAlgorithm, RoomId, UserId}, instant::Instant, locks::Mutex, + uuid::Uuid, }; -use serde::{Deserialize, Serialize}; -use serde_json::{json, Value}; - pub use olm_rs::{ account::IdentityKeys, session::{OlmMessage, PreKeyMessage}, @@ -56,13 +48,15 @@ pub use olm_rs::{ use olm_rs::{ errors::OlmGroupSessionError, outbound_group_session::OlmOutboundGroupSession, PicklingMode, }; - -use crate::ToDeviceRequest; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use tracing::{debug, error, trace}; use super::{ super::{deserialize_instant, serialize_instant}, GroupSessionKey, }; +use crate::ToDeviceRequest; const ROTATION_PERIOD: Duration = Duration::from_millis(604800000); const ROTATION_MESSAGES: u64 = 100; @@ -461,11 +455,11 @@ impl OutboundGroupSession { /// /// # Arguments /// - /// * `device_id` - The device id of the device that created this session. - /// Put differently, our own device id. + /// * `device_id` - The device id of the device that created this session. Put differently, our + /// own device id. /// - /// * `identity_keys` - The identity keys of the device that created this - /// session, our own identity keys. + /// * `identity_keys` - The identity keys of the device that created this session, our own + /// identity keys. /// /// * `pickle` - The pickled version of the `OutboundGroupSession`. /// diff --git a/matrix_sdk_crypto/src/olm/mod.rs b/matrix_sdk_crypto/src/olm/mod.rs index 36cd86f6..85ee51d9 100644 --- a/matrix_sdk_crypto/src/olm/mod.rs +++ b/matrix_sdk_crypto/src/olm/mod.rs @@ -30,14 +30,13 @@ pub use group_sessions::{ OutboundGroupSession, PickledInboundGroupSession, PickledOutboundGroupSession, }; pub(crate) use group_sessions::{GroupSessionKey, ShareState}; +use matrix_sdk_common::instant::{Duration, Instant}; pub use olm_rs::{account::IdentityKeys, PicklingMode}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; pub use session::{PickledSession, Session, SessionPickle}; pub use signing::{PickledCrossSigningIdentity, PrivateCrossSigningIdentity}; pub(crate) use utility::Utility; -use matrix_sdk_common::instant::{Duration, Instant}; -use serde::{Deserialize, Deserializer, Serialize, Serializer}; - pub(crate) fn serialize_instant(instant: &Instant, serializer: S) -> Result where S: Serializer, @@ -60,14 +59,16 @@ where #[cfg(test)] pub(crate) mod test { - use crate::olm::{InboundGroupSession, ReadOnlyAccount, Session}; + use std::{collections::BTreeMap, convert::TryInto}; + use matrix_sdk_common::{ api::r0::keys::SignedKey, events::forwarded_room_key::ForwardedRoomKeyToDeviceEventContent, identifiers::{room_id, user_id, DeviceId, UserId}, }; use olm_rs::session::OlmMessage; - use std::{collections::BTreeMap, convert::TryInto}; + + use crate::olm::{InboundGroupSession, ReadOnlyAccount, Session}; fn alice_id() -> UserId { user_id!("@alice:example.org") diff --git a/matrix_sdk_crypto/src/olm/session.rs b/matrix_sdk_crypto/src/olm/session.rs index aa5ed764..3f3c05e9 100644 --- a/matrix_sdk_crypto/src/olm/session.rs +++ b/matrix_sdk_crypto/src/olm/session.rs @@ -27,20 +27,18 @@ use matrix_sdk_common::{ locks::Mutex, }; use olm_rs::{errors::OlmSessionError, session::OlmSession, PicklingMode}; -use serde::{Deserialize, Serialize}; -use serde_json::{json, Value}; - -use crate::{ - error::{EventError, OlmResult, SessionUnpicklingError}, - ReadOnlyDevice, -}; - pub use olm_rs::{ session::{OlmMessage, PreKeyMessage}, utility::OlmUtility, }; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; use super::{deserialize_instant, serialize_instant, IdentityKeys}; +use crate::{ + error::{EventError, OlmResult, SessionUnpicklingError}, + ReadOnlyDevice, +}; /// Cryptographic session that enables secure communication between two /// `Account`s @@ -104,9 +102,8 @@ impl Session { /// /// # Arguments /// - /// * `recipient_device` - The device for which this message is going to be - /// encrypted, this needs to be the device that was used to create this - /// session with. + /// * `recipient_device` - The device for which this message is going to be encrypted, this + /// needs to be the device that was used to create this session with. /// /// * `event_type` - The type of the event. /// diff --git a/matrix_sdk_crypto/src/olm/signing/mod.rs b/matrix_sdk_crypto/src/olm/signing/mod.rs index bf004313..223eb4a2 100644 --- a/matrix_sdk_crypto/src/olm/signing/mod.rs +++ b/matrix_sdk_crypto/src/olm/signing/mod.rs @@ -14,8 +14,6 @@ mod pk_signing; -use serde::{Deserialize, Serialize}; -use serde_json::Error as JsonError; use std::{ collections::BTreeMap, sync::{ @@ -30,14 +28,15 @@ use matrix_sdk_common::{ identifiers::{DeviceKeyAlgorithm, DeviceKeyId, UserId}, locks::Mutex, }; +use pk_signing::{MasterSigning, PickledSignings, SelfSigning, Signing, SigningError, UserSigning}; +use serde::{Deserialize, Serialize}; +use serde_json::Error as JsonError; use crate::{ error::SignatureError, requests::UploadSigningKeysRequest, OwnUserIdentity, ReadOnlyAccount, ReadOnlyDevice, UserIdentity, }; -use pk_signing::{MasterSigning, PickledSignings, SelfSigning, Signing, SigningError, UserSigning}; - /// Private cross signing identity. /// /// This object holds the private and public ed25519 key triplet that is used @@ -424,20 +423,20 @@ impl PrivateCrossSigningIdentity { #[cfg(test)] mod test { - use crate::{ - identities::{ReadOnlyDevice, UserIdentity}, - olm::ReadOnlyAccount, - }; use std::{collections::BTreeMap, sync::Arc}; - use super::{PrivateCrossSigningIdentity, Signing}; - use matrix_sdk_common::{ api::r0::keys::CrossSigningKey, identifiers::{user_id, UserId}, }; use matrix_sdk_test::async_test; + use super::{PrivateCrossSigningIdentity, Signing}; + use crate::{ + identities::{ReadOnlyDevice, UserIdentity}, + olm::ReadOnlyAccount, + }; + fn user_id() -> UserId { user_id!("@example:localhost") } diff --git a/matrix_sdk_crypto/src/olm/signing/pk_signing.rs b/matrix_sdk_crypto/src/olm/signing/pk_signing.rs index 3a7d434b..e38837e1 100644 --- a/matrix_sdk_crypto/src/olm/signing/pk_signing.rs +++ b/matrix_sdk_crypto/src/olm/signing/pk_signing.rs @@ -12,32 +12,27 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::{collections::BTreeMap, convert::TryInto, sync::Arc}; + use aes_gcm::{ aead::{generic_array::GenericArray, Aead, NewAead}, Aes256Gcm, }; use getrandom::getrandom; -use matrix_sdk_common::{ - encryption::DeviceKeys, - identifiers::{DeviceKeyAlgorithm, DeviceKeyId}, -}; -use serde::{Deserialize, Serialize}; -use serde_json::{json, Error as JsonError, Value}; -use std::{collections::BTreeMap, convert::TryInto, sync::Arc}; -use thiserror::Error; -use zeroize::Zeroizing; - -use olm_rs::pk::OlmPkSigning; - -#[cfg(test)] -use olm_rs::{errors::OlmUtilityError, utility::OlmUtility}; - use matrix_sdk_common::{ api::r0::keys::{CrossSigningKey, KeyUsage}, - identifiers::UserId, + encryption::DeviceKeys, + identifiers::{DeviceKeyAlgorithm, DeviceKeyId, UserId}, locks::Mutex, CanonicalJsonValue, }; +use olm_rs::pk::OlmPkSigning; +#[cfg(test)] +use olm_rs::{errors::OlmUtilityError, utility::OlmUtility}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Error as JsonError, Value}; +use thiserror::Error; +use zeroize::Zeroizing; use crate::{ error::SignatureError, diff --git a/matrix_sdk_crypto/src/olm/utility.rs b/matrix_sdk_crypto/src/olm/utility.rs index e398a139..6d8caf48 100644 --- a/matrix_sdk_crypto/src/olm/utility.rs +++ b/matrix_sdk_crypto/src/olm/utility.rs @@ -12,14 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -use olm_rs::utility::OlmUtility; -use serde_json::Value; use std::convert::TryInto; use matrix_sdk_common::{ identifiers::{DeviceKeyAlgorithm, DeviceKeyId, UserId}, CanonicalJsonValue, }; +use olm_rs::utility::OlmUtility; +use serde_json::Value; use crate::error::SignatureError; @@ -48,8 +48,7 @@ impl Utility { /// /// * `key_id` - The id of the key that signed the JSON object. /// - /// * `signing_key` - The public ed25519 key which was used to sign the JSON - /// object. + /// * `signing_key` - The public ed25519 key which was used to sign the JSON object. /// /// * `json` - The JSON object that should be verified. pub(crate) fn verify_json( @@ -108,10 +107,11 @@ impl Utility { #[cfg(test)] mod test { - use super::Utility; use matrix_sdk_common::identifiers::{user_id, DeviceKeyAlgorithm, DeviceKeyId}; use serde_json::json; + use super::Utility; + #[test] fn signature_test() { let mut device_keys = json!({ diff --git a/matrix_sdk_crypto/src/requests.rs b/matrix_sdk_crypto/src/requests.rs index 5d0e841a..5d852196 100644 --- a/matrix_sdk_crypto/src/requests.rs +++ b/matrix_sdk_crypto/src/requests.rs @@ -35,7 +35,6 @@ use matrix_sdk_common::{ identifiers::{DeviceIdBox, RoomId, UserId}, uuid::Uuid, }; - use serde::{Deserialize, Serialize}; use serde_json::value::RawValue as RawJsonValue; diff --git a/matrix_sdk_crypto/src/session_manager/group_sessions.rs b/matrix_sdk_crypto/src/session_manager/group_sessions.rs index c36aac37..d84a0c2d 100644 --- a/matrix_sdk_crypto/src/session_manager/group_sessions.rs +++ b/matrix_sdk_crypto/src/session_manager/group_sessions.rs @@ -17,9 +17,8 @@ use std::{ sync::Arc, }; -use futures::future::join_all; - use dashmap::DashMap; +use futures::future::join_all; use matrix_sdk_common::{ api::r0::to_device::DeviceIdOrAllDevices, events::{ diff --git a/matrix_sdk_crypto/src/session_manager/sessions.rs b/matrix_sdk_crypto/src/session_manager/sessions.rs index 274314a8..e74e2fa4 100644 --- a/matrix_sdk_crypto/src/session_manager/sessions.rs +++ b/matrix_sdk_crypto/src/session_manager/sessions.rs @@ -307,13 +307,13 @@ impl SessionManager { #[cfg(test)] mod test { - use dashmap::DashMap; - use matrix_sdk_common::locks::Mutex; use std::{collections::BTreeMap, sync::Arc}; + use dashmap::DashMap; use matrix_sdk_common::{ api::r0::keys::claim_keys::Response as KeyClaimResponse, identifiers::{user_id, DeviceIdBox, UserId}, + locks::Mutex, }; use matrix_sdk_test::async_test; diff --git a/matrix_sdk_crypto/src/store/caches.rs b/matrix_sdk_crypto/src/store/caches.rs index 523025ca..770d2391 100644 --- a/matrix_sdk_crypto/src/store/caches.rs +++ b/matrix_sdk_crypto/src/store/caches.rs @@ -195,12 +195,13 @@ impl DeviceStore { #[cfg(test)] mod test { + use matrix_sdk_common::identifiers::room_id; + use crate::{ identities::device::test::get_device, olm::{test::get_account_and_session, InboundGroupSession}, store::caches::{DeviceStore, GroupSessionStore, SessionStore}, }; - use matrix_sdk_common::identifiers::room_id; #[tokio::test] async fn test_session_store() { diff --git a/matrix_sdk_crypto/src/store/memorystore.rs b/matrix_sdk_crypto/src/store/memorystore.rs index e9ca5307..d2420cf7 100644 --- a/matrix_sdk_crypto/src/store/memorystore.rs +++ b/matrix_sdk_crypto/src/store/memorystore.rs @@ -291,12 +291,13 @@ impl CryptoStore for MemoryStore { #[cfg(test)] mod test { + use matrix_sdk_common::identifiers::room_id; + use crate::{ identities::device::test::get_device, olm::{test::get_account_and_session, InboundGroupSession, OlmMessageHash}, store::{memorystore::MemoryStore, Changes, CryptoStore}, }; - use matrix_sdk_common::identifiers::room_id; #[tokio::test] async fn test_session_store() { diff --git a/matrix_sdk_crypto/src/store/mod.rs b/matrix_sdk_crypto/src/store/mod.rs index 1982e1cc..4e0e7aa6 100644 --- a/matrix_sdk_crypto/src/store/mod.rs +++ b/matrix_sdk_crypto/src/store/mod.rs @@ -43,11 +43,6 @@ mod pickle_key; #[cfg(feature = "sled_cryptostore")] pub(crate) mod sled; -#[cfg(feature = "sled_cryptostore")] -pub use self::sled::SledStore; -pub use memorystore::MemoryStore; -pub use pickle_key::{EncryptedPickleKey, PickleKey}; - use std::{ collections::{HashMap, HashSet}, fmt::Debug, @@ -56,10 +51,6 @@ use std::{ sync::Arc, }; -use olm_rs::errors::{OlmAccountError, OlmGroupSessionError, OlmSessionError}; -use serde_json::Error as SerdeError; -use thiserror::Error; - use matrix_sdk_common::{ async_trait, events::room_key_request::RequestedKeyInfo, @@ -71,7 +62,14 @@ use matrix_sdk_common::{ uuid::Uuid, AsyncTraitDeps, }; +pub use memorystore::MemoryStore; +use olm_rs::errors::{OlmAccountError, OlmGroupSessionError, OlmSessionError}; +pub use pickle_key::{EncryptedPickleKey, PickleKey}; +use serde_json::Error as SerdeError; +use thiserror::Error; +#[cfg(feature = "sled_cryptostore")] +pub use self::sled::SledStore; use crate::{ error::SessionUnpicklingError, identities::{Device, ReadOnlyDevice, UserDevices, UserIdentities}, diff --git a/matrix_sdk_crypto/src/store/pickle_key.rs b/matrix_sdk_crypto/src/store/pickle_key.rs index 7794e348..09da6fba 100644 --- a/matrix_sdk_crypto/src/store/pickle_key.rs +++ b/matrix_sdk_crypto/src/store/pickle_key.rs @@ -22,11 +22,10 @@ use getrandom::getrandom; use hmac::Hmac; use olm_rs::PicklingMode; use pbkdf2::pbkdf2; +use serde::{Deserialize, Serialize}; use sha2::Sha256; use zeroize::{Zeroize, Zeroizing}; -use serde::{Deserialize, Serialize}; - const KEY_SIZE: usize = 32; const NONCE_SIZE: usize = 12; const KDF_SALT_SIZE: usize = 32; diff --git a/matrix_sdk_crypto/src/store/sled.rs b/matrix_sdk_crypto/src/store/sled.rs index b6928e78..d8e998f9 100644 --- a/matrix_sdk_crypto/src/store/sled.rs +++ b/matrix_sdk_crypto/src/store/sled.rs @@ -20,13 +20,6 @@ use std::{ }; use dashmap::DashSet; -use olm_rs::{account::IdentityKeys, PicklingMode}; -pub use sled::Error; -use sled::{ - transaction::{ConflictableTransactionError, TransactionError}, - Config, Db, Transactional, Tree, -}; - use matrix_sdk_common::{ async_trait, events::room_key_request::RequestedKeyInfo, @@ -34,6 +27,12 @@ use matrix_sdk_common::{ locks::Mutex, uuid, }; +use olm_rs::{account::IdentityKeys, PicklingMode}; +pub use sled::Error; +use sled::{ + transaction::{ConflictableTransactionError, TransactionError}, + Config, Db, Transactional, Tree, +}; use uuid::Uuid; use super::{ @@ -793,6 +792,19 @@ impl CryptoStore for SledStore { #[cfg(test)] mod test { + use std::collections::BTreeMap; + + use matrix_sdk_common::{ + api::r0::keys::SignedKey, + events::room_key_request::RequestedKeyInfo, + identifiers::{room_id, user_id, DeviceId, EventEncryptionAlgorithm, UserId}, + uuid::Uuid, + }; + use matrix_sdk_test::async_test; + use olm_rs::outbound_group_session::OlmOutboundGroupSession; + use tempfile::tempdir; + + use super::{CryptoStore, OutgoingKeyRequest, SledStore}; use crate::{ identities::{ device::test::get_device, @@ -804,18 +816,6 @@ mod test { }, store::{Changes, DeviceChanges, IdentityChanges}, }; - use matrix_sdk_common::{ - api::r0::keys::SignedKey, - events::room_key_request::RequestedKeyInfo, - identifiers::{room_id, user_id, DeviceId, EventEncryptionAlgorithm, UserId}, - uuid::Uuid, - }; - use matrix_sdk_test::async_test; - use olm_rs::outbound_group_session::OlmOutboundGroupSession; - use std::collections::BTreeMap; - use tempfile::tempdir; - - use super::{CryptoStore, OutgoingKeyRequest, SledStore}; fn alice_id() -> UserId { user_id!("@alice:example.org") diff --git a/matrix_sdk_crypto/src/verification/machine.rs b/matrix_sdk_crypto/src/verification/machine.rs index 5934ef15..f3e8c905 100644 --- a/matrix_sdk_crypto/src/verification/machine.rs +++ b/matrix_sdk_crypto/src/verification/machine.rs @@ -15,9 +15,6 @@ use std::{convert::TryFrom, sync::Arc}; use dashmap::DashMap; - -use tracing::{info, trace, warn}; - use matrix_sdk_common::{ events::{ room::message::MessageType, AnyMessageEvent, AnySyncMessageEvent, AnySyncRoomEvent, @@ -27,12 +24,12 @@ use matrix_sdk_common::{ locks::Mutex, uuid::Uuid, }; +use tracing::{info, trace, warn}; use super::{ requests::VerificationRequest, sas::{content_to_request, OutgoingContent, Sas, VerificationResult}, }; - use crate::{ olm::PrivateCrossSigningIdentity, requests::OutgoingRequest, diff --git a/matrix_sdk_crypto/src/verification/mod.rs b/matrix_sdk_crypto/src/verification/mod.rs index c642dd21..9f386b6b 100644 --- a/matrix_sdk_crypto/src/verification/mod.rs +++ b/matrix_sdk_crypto/src/verification/mod.rs @@ -22,18 +22,17 @@ pub use sas::{AcceptSettings, Sas, VerificationResult}; #[cfg(test)] pub(crate) mod test { - use crate::{ - requests::{OutgoingRequest, OutgoingRequests}, - OutgoingVerificationRequest, - }; - use serde_json::Value; - use matrix_sdk_common::{ events::{AnyToDeviceEvent, AnyToDeviceEventContent, EventType, ToDeviceEvent}, identifiers::UserId, }; + use serde_json::Value; use super::sas::OutgoingContent; + use crate::{ + requests::{OutgoingRequest, OutgoingRequests}, + OutgoingVerificationRequest, + }; pub(crate) fn request_to_event( sender: &UserId, diff --git a/matrix_sdk_crypto/src/verification/requests.rs b/matrix_sdk_crypto/src/verification/requests.rs index 18abfac4..da90cad9 100644 --- a/matrix_sdk_crypto/src/verification/requests.rs +++ b/matrix_sdk_crypto/src/verification/requests.rs @@ -28,14 +28,13 @@ use matrix_sdk_common::{ identifiers::{DeviceId, DeviceIdBox, EventId, RoomId, UserId}, }; +use super::sas::{OutgoingContent, StartContent}; use crate::{ olm::{PrivateCrossSigningIdentity, ReadOnlyAccount}, store::CryptoStore, ReadOnlyDevice, Sas, UserIdentities, }; -use super::sas::{OutgoingContent, StartContent}; - const SUPPORTED_METHODS: &[VerificationMethod] = &[VerificationMethod::MSasV1]; #[derive(Clone, Debug)] @@ -453,6 +452,7 @@ mod test { }; use matrix_sdk_test::async_test; + use super::VerificationRequest; use crate::{ olm::{PrivateCrossSigningIdentity, ReadOnlyAccount}, store::{CryptoStore, MemoryStore}, @@ -460,8 +460,6 @@ mod test { ReadOnlyDevice, }; - use super::VerificationRequest; - fn alice_id() -> UserId { UserId::try_from("@alice:example.org").unwrap() } diff --git a/matrix_sdk_crypto/src/verification/sas/helpers.rs b/matrix_sdk_crypto/src/verification/sas/helpers.rs index e505eec1..33325dc4 100644 --- a/matrix_sdk_crypto/src/verification/sas/helpers.rs +++ b/matrix_sdk_crypto/src/verification/sas/helpers.rs @@ -14,11 +14,6 @@ use std::{collections::BTreeMap, convert::TryInto}; -use sha2::{Digest, Sha256}; -use tracing::{trace, warn}; - -use olm_rs::sas::OlmSas; - use matrix_sdk_common::{ api::r0::to_device::DeviceIdOrAllDevices, events::{ @@ -32,17 +27,19 @@ use matrix_sdk_common::{ identifiers::{DeviceId, DeviceKeyAlgorithm, DeviceKeyId, UserId}, uuid::Uuid, }; - -use crate::{ - identities::{ReadOnlyDevice, UserIdentities}, - utilities::encode, - ReadOnlyAccount, ToDeviceRequest, -}; +use olm_rs::sas::OlmSas; +use sha2::{Digest, Sha256}; +use tracing::{trace, warn}; use super::{ event_enums::{MacContent, StartContent}, sas_state::FlowId, }; +use crate::{ + identities::{ReadOnlyDevice, UserIdentities}, + utilities::encode, + ReadOnlyAccount, ToDeviceRequest, +}; #[derive(Clone, Debug)] pub struct SasIds { diff --git a/matrix_sdk_crypto/src/verification/sas/inner_sas.rs b/matrix_sdk_crypto/src/verification/sas/inner_sas.rs index 89080b5b..2ebed311 100644 --- a/matrix_sdk_crypto/src/verification/sas/inner_sas.rs +++ b/matrix_sdk_crypto/src/verification/sas/inner_sas.rs @@ -12,21 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::sync::Arc; #[cfg(test)] use std::time::Instant; -use std::sync::Arc; - use matrix_sdk_common::{ events::{key::verification::cancel::CancelCode, AnyMessageEvent, AnyToDeviceEvent}, identifiers::{EventId, RoomId}, }; -use crate::{ - identities::{ReadOnlyDevice, UserIdentities}, - ReadOnlyAccount, -}; - use super::{ event_enums::{AcceptContent, CancelContent, MacContent, OutgoingContent}, sas_state::{ @@ -35,6 +29,10 @@ use super::{ }, StartContent, }; +use crate::{ + identities::{ReadOnlyDevice, UserIdentities}, + ReadOnlyAccount, +}; #[derive(Clone, Debug)] pub enum InnerSas { diff --git a/matrix_sdk_crypto/src/verification/sas/mod.rs b/matrix_sdk_crypto/src/verification/sas/mod.rs index 6a7c9332..c4bbc783 100644 --- a/matrix_sdk_crypto/src/verification/sas/mod.rs +++ b/matrix_sdk_crypto/src/verification/sas/mod.rs @@ -17,13 +17,14 @@ mod helpers; mod inner_sas; mod sas_state; +use std::sync::{Arc, Mutex}; #[cfg(test)] use std::time::Instant; use event_enums::AcceptContent; -use std::sync::{Arc, Mutex}; -use tracing::{error, info, trace, warn}; - +pub use event_enums::{OutgoingContent, StartContent}; +pub use helpers::content_to_request; +use inner_sas::InnerSas; use matrix_sdk_common::{ api::r0::keys::upload_signatures::Request as SignatureUploadRequest, events::{ @@ -37,7 +38,10 @@ use matrix_sdk_common::{ identifiers::{DeviceId, EventId, RoomId, UserId}, uuid::Uuid, }; +pub use sas_state::FlowId; +use tracing::{error, info, trace, warn}; +use self::event_enums::CancelContent; use crate::{ error::SignatureError, identities::{LocalTrust, ReadOnlyDevice, UserIdentities}, @@ -47,14 +51,6 @@ use crate::{ ReadOnlyAccount, ToDeviceRequest, }; -pub use helpers::content_to_request; -use inner_sas::InnerSas; -pub use sas_state::FlowId; - -pub use event_enums::{OutgoingContent, StartContent}; - -use self::event_enums::CancelContent; - #[derive(Debug)] /// A result of a verification flow. #[allow(clippy::large_enum_variant)] @@ -741,6 +737,7 @@ mod test { use matrix_sdk_common::identifiers::{DeviceId, UserId}; + use super::Sas; use crate::{ olm::PrivateCrossSigningIdentity, store::{CryptoStore, MemoryStore}, @@ -748,8 +745,6 @@ mod test { ReadOnlyAccount, ReadOnlyDevice, }; - use super::Sas; - fn alice_id() -> UserId { UserId::try_from("@alice:example.org").unwrap() } diff --git a/matrix_sdk_crypto/src/verification/sas/sas_state.rs b/matrix_sdk_crypto/src/verification/sas/sas_state.rs index 96bf25f9..c96471e7 100644 --- a/matrix_sdk_crypto/src/verification/sas/sas_state.rs +++ b/matrix_sdk_crypto/src/verification/sas/sas_state.rs @@ -19,8 +19,6 @@ use std::{ time::{Duration, Instant}, }; -use olm_rs::sas::OlmSas; - use matrix_sdk_common::{ events::key::verification::{ accept::{ @@ -40,6 +38,7 @@ use matrix_sdk_common::{ identifiers::{DeviceId, EventId, RoomId, UserId}, uuid::Uuid, }; +use olm_rs::sas::OlmSas; use tracing::info; use super::{ @@ -51,7 +50,6 @@ use super::{ receive_mac_event, SasIds, }, }; - use crate::{ identities::{ReadOnlyDevice, UserIdentities}, ReadOnlyAccount, @@ -1182,10 +1180,6 @@ impl SasState { mod test { use std::convert::TryFrom; - use crate::{ - verification::sas::{event_enums::AcceptContent, StartContent}, - ReadOnlyAccount, ReadOnlyDevice, - }; use matrix_sdk_common::{ events::key::verification::{ accept::{AcceptMethod, CustomContent}, @@ -1195,6 +1189,10 @@ mod test { }; use super::{Accepted, Created, SasState, Started}; + use crate::{ + verification::sas::{event_enums::AcceptContent, StartContent}, + ReadOnlyAccount, ReadOnlyDevice, + }; fn alice_id() -> UserId { UserId::try_from("@alice:example.org").unwrap() diff --git a/matrix_sdk_test/src/lib.rs b/matrix_sdk_test/src/lib.rs index 942c3c10..8604f0a9 100644 --- a/matrix_sdk_test/src/lib.rs +++ b/matrix_sdk_test/src/lib.rs @@ -1,7 +1,6 @@ use std::{collections::HashMap, panic}; use http::Response; - use matrix_sdk_common::{ api::r0::sync::sync_events::Response as SyncResponse, events::{ @@ -11,9 +10,8 @@ use matrix_sdk_common::{ identifiers::{room_id, RoomId}, IncomingResponse, }; -use serde_json::Value as JsonValue; - pub use matrix_sdk_test_macros::async_test; +use serde_json::Value as JsonValue; pub mod test_json; diff --git a/matrix_sdk_test/src/test_json/mod.rs b/matrix_sdk_test/src/test_json/mod.rs index f229949f..fd869473 100644 --- a/matrix_sdk_test/src/test_json/mod.rs +++ b/matrix_sdk_test/src/test_json/mod.rs @@ -17,12 +17,11 @@ pub use events::{ PUBLIC_ROOMS, REACTION, REDACTED, REDACTED_INVALID, REDACTED_STATE, REDACTION, REGISTRATION_RESPONSE_ERR, ROOM_ID, ROOM_MESSAGES, TYPING, }; +pub use members::MEMBERS; pub use sync::{ DEFAULT_SYNC_SUMMARY, INVITE_SYNC, LEAVE_SYNC, LEAVE_SYNC_EVENT, MORE_SYNC, SYNC, VOIP_SYNC, }; -pub use members::MEMBERS; - lazy_static! { pub static ref DEVICES: JsonValue = json!({ "devices": [ diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 00000000..b80d72d8 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,5 @@ +comment_width = 100 +wrap_comments = true +imports_granularity = "Crate" +max_width = 100 +group_imports = "StdExternalCrate"