From a26dc3179a6febcf4a04be61eae7509362247db2 Mon Sep 17 00:00:00 2001 From: Amanda Graven Date: Mon, 7 Dec 2020 11:17:26 +0100 Subject: [PATCH 01/27] Add methods for getting and setting display name --- matrix_sdk/src/client.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/matrix_sdk/src/client.rs b/matrix_sdk/src/client.rs index 41ff0cc3..7374b7c7 100644 --- a/matrix_sdk/src/client.rs +++ b/matrix_sdk/src/client.rs @@ -74,6 +74,7 @@ use matrix_sdk_common::{ join_room_by_id, join_room_by_id_or_alias, kick_user, leave_room, Invite3pid, }, message::{get_message_events, send_message_event}, + profile::{get_display_name, set_display_name}, read_marker::set_read_marker, receipt::create_receipt, room::create_room, @@ -429,6 +430,22 @@ impl Client { session.as_ref().cloned().map(|s| s.user_id) } + /// Fetches the display name of the owner of the client. + pub async fn user_display_name(&self) -> Result> { + let user_id = self.user_id().await.ok_or(Error::AuthenticationRequired)?; + let request = get_display_name::Request::new(&user_id); + let response = self.send(request).await?; + Ok(response.displayname) + } + + /// Sets the display name of the owner of the client. + pub async fn set_user_display_name(&self, name: Option<&str>) -> Result<()> { + let user_id = self.user_id().await.ok_or(Error::AuthenticationRequired)?; + let request = set_display_name::Request::new(&user_id, name); + self.send(request).await?; + Ok(()) + } + /// Add `EventEmitter` to `Client`. /// /// The methods of `EventEmitter` are called when the respective `RoomEvents` occur. From 7f503eb71c4c8b71fbeb43b8593980a3efeb77f2 Mon Sep 17 00:00:00 2001 From: Amanda Graven Date: Mon, 7 Dec 2020 12:59:10 +0100 Subject: [PATCH 02/27] Add examples, remove user from method names --- matrix_sdk/src/client.rs | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/matrix_sdk/src/client.rs b/matrix_sdk/src/client.rs index 7374b7c7..392d3448 100644 --- a/matrix_sdk/src/client.rs +++ b/matrix_sdk/src/client.rs @@ -431,7 +431,24 @@ impl Client { } /// Fetches the display name of the owner of the client. - pub async fn user_display_name(&self) -> Result> { + /// + /// # Example + /// ```no_run + /// # use futures::executor::block_on; + /// # use matrix_sdk::Client; + /// # use url::Url; + /// # let homeserver = Url::parse("http://example.com").unwrap(); + /// # block_on(async { + /// let user = "example"; + /// let client = Client::new(homeserver).unwrap(); + /// client.login(user, "password", None, None).await.unwrap(); + /// + /// if let Some(name) = client.display_name().await { + /// println!("Logged in as user '{}' with display name '{}'", user, name); + /// } + /// # }) + /// ``` + pub async fn display_name(&self) -> Result> { let user_id = self.user_id().await.ok_or(Error::AuthenticationRequired)?; let request = get_display_name::Request::new(&user_id); let response = self.send(request).await?; @@ -439,7 +456,22 @@ impl Client { } /// Sets the display name of the owner of the client. - pub async fn set_user_display_name(&self, name: Option<&str>) -> Result<()> { + /// + /// # Example + /// ```no_run + /// # use futures::executor::block_on; + /// # use matrix_sdk::Client; + /// # use url::Url; + /// # let homeserver = Url::parse("http://example.com").unwrap(); + /// # block_on(async { + /// let user = "example"; + /// let client = Client::new(homeserver).unwrap(); + /// client.login(user, "password", None, None).await.unwrap(); + /// + /// client.set_display_name(Some("Alice")).await.expect("Failed setting display name"); + /// # }) + /// ``` + pub async fn set_display_name(&self, name: Option<&str>) -> Result<()> { let user_id = self.user_id().await.ok_or(Error::AuthenticationRequired)?; let request = set_display_name::Request::new(&user_id, name); self.send(request).await?; From bca7f41ca9a14a94a1052c9d5502aecfc8ddf138 Mon Sep 17 00:00:00 2001 From: Amanda Graven Date: Mon, 7 Dec 2020 13:14:23 +0100 Subject: [PATCH 03/27] Fix error in example --- matrix_sdk/src/client.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matrix_sdk/src/client.rs b/matrix_sdk/src/client.rs index 392d3448..195a4a28 100644 --- a/matrix_sdk/src/client.rs +++ b/matrix_sdk/src/client.rs @@ -443,7 +443,7 @@ impl Client { /// let client = Client::new(homeserver).unwrap(); /// client.login(user, "password", None, None).await.unwrap(); /// - /// if let Some(name) = client.display_name().await { + /// if let Some(name) = client.display_name().await.unwrap() { /// println!("Logged in as user '{}' with display name '{}'", user, name); /// } /// # }) From 795900cf39ac2411888b572e12e5fa4d01f53400 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 10:42:05 +0100 Subject: [PATCH 04/27] CI: Add a lint github workflow. --- .github/workflows/lint.yml | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 .github/workflows/lint.yml diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 00000000..3d0ed9d9 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,29 @@ +name: Lint + +on: + push: + pull_request: + branches: [ master ] + +env: + CARGO_TERM_COLOR: always + +jobs: + check: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + toolchain: stable + + - uses: actions-rs/cargo@v1 + with: + command: fmt + args: --all --check + + - uses: actions-rs/cargo@v1 + with: + command: clippy + args: --all-targets -- -D warnings From e24fb8b4714f3ab4907c9ab9cadb3b10b42c20ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 10:44:19 +0100 Subject: [PATCH 05/27] CI: Fix the cargo fmt invocation. --- .github/workflows/lint.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 3d0ed9d9..cb5ece16 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -9,7 +9,7 @@ env: CARGO_TERM_COLOR: always jobs: - check: + lint: runs-on: ubuntu-latest steps: @@ -21,7 +21,7 @@ jobs: - uses: actions-rs/cargo@v1 with: command: fmt - args: --all --check + args: --all -- --check - uses: actions-rs/cargo@v1 with: From 35247fac2abe9e3b50db0c97414800e596412c0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 10:50:58 +0100 Subject: [PATCH 06/27] crypto: Fix a lint issue. --- matrix_sdk_crypto/src/olm/account.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matrix_sdk_crypto/src/olm/account.rs b/matrix_sdk_crypto/src/olm/account.rs index 0557129a..d181aae6 100644 --- a/matrix_sdk_crypto/src/olm/account.rs +++ b/matrix_sdk_crypto/src/olm/account.rs @@ -170,7 +170,7 @@ impl Account { return Err(OlmError::SessionWedged(user_id, sender_key)); } } - Err(e) => return Err(e.into()), + Err(e) => return Err(e), }; debug!("Decrypted a to-device event {:?}", event); From 59917f45e3a2e3e75543b0c017c257f60b74a965 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 11:01:20 +0100 Subject: [PATCH 07/27] matrix-sdk: Fix a clippy lint. --- matrix_sdk/src/client.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matrix_sdk/src/client.rs b/matrix_sdk/src/client.rs index 195a4a28..c0be1097 100644 --- a/matrix_sdk/src/client.rs +++ b/matrix_sdk/src/client.rs @@ -841,7 +841,7 @@ impl Client { since: Option<&str>, server: Option<&ServerName>, ) -> Result { - let limit = limit.map(|n| UInt::from(n)); + let limit = limit.map(UInt::from); let request = assign!(get_public_rooms::Request::new(), { limit, From 1d5ee22dd2990f5019c34f9fc3b944647fb054c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 11:08:41 +0100 Subject: [PATCH 08/27] CI: Name our lint stages. --- .github/workflows/lint.yml | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index cb5ece16..ad5c1e91 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -13,17 +13,21 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - uses: actions-rs/toolchain@v1 + - name: Checkout the repo + uses: actions/checkout@v2 + - name: Install rust + uses: actions-rs/toolchain@v1 with: toolchain: stable - - uses: actions-rs/cargo@v1 + - name: Cargo fmt + uses: actions-rs/cargo@v1 with: command: fmt args: --all -- --check - - uses: actions-rs/cargo@v1 + - name: Clippy + uses: actions-rs/cargo@v1 with: command: clippy args: --all-targets -- -D warnings From 8dc56ec3322bc74ae959618970f6e71e95776577 Mon Sep 17 00:00:00 2001 From: Amanda Graven Date: Mon, 7 Dec 2020 16:34:32 +0100 Subject: [PATCH 09/27] Add methods for setting, getting and uploading avatar --- matrix_sdk/src/client.rs | 65 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 64 insertions(+), 1 deletion(-) diff --git a/matrix_sdk/src/client.rs b/matrix_sdk/src/client.rs index 195a4a28..06bbed1d 100644 --- a/matrix_sdk/src/client.rs +++ b/matrix_sdk/src/client.rs @@ -74,7 +74,7 @@ use matrix_sdk_common::{ join_room_by_id, join_room_by_id_or_alias, kick_user, leave_room, Invite3pid, }, message::{get_message_events, send_message_event}, - profile::{get_display_name, set_display_name}, + profile::{get_avatar_url, get_display_name, set_avatar_url, set_display_name}, read_marker::set_read_marker, receipt::create_receipt, room::create_room, @@ -478,6 +478,69 @@ impl Client { Ok(()) } + /// Gets the mxc avatar url of the owner of the client, if set. + /// + /// # Example + /// ```no_run + /// # use futures::executor::block_on; + /// # use matrix_sdk::Client; + /// # use url::Url; + /// # let homeserver = Url::parse("http://example.com").unwrap(); + /// # block_on(async { + /// # let user = "example"; + /// let client = Client::new(homeserver).unwrap(); + /// client.login(user, "password", None, None).await.unwrap(); + /// + /// if let Some(url) = client.avatar_url().await.unwrap() { + /// println!("Your avatar's mxc url is {}", url); + /// } + /// # }) + /// ``` + pub async fn avatar_url(&self) -> Result> { + let user_id = self.user_id().await.ok_or(Error::AuthenticationRequired)?; + let request = get_avatar_url::Request::new(&user_id); + let response = self.send(request).await?; + Ok(response.avatar_url) + } + + /// Sets the mxc avatar url of the client's owner. The avatar gets unset if `url` is `None`. + pub async fn set_avatar_url(&self, url: Option<&str>) -> Result<()> { + let user_id = self.user_id().await.ok_or(Error::AuthenticationRequired)?; + let request = set_avatar_url::Request::new(&user_id, url); + self.send(request).await?; + Ok(()) + } + + /// Upload and set the owning client's avatar. + /// + /// The will upload the data produced by the reader to the homeserver's content repository, and + /// set the user's avatar to the mxc url for the uploaded file. + /// + /// This is a convenience method for calling [`upload()`](#method.upload), followed by + /// [`set_avatar_url()`](#method.set_avatar_url). + /// + /// # Example + /// ```no_run + /// # use std::{path::Path, fs::File, io::Read}; + /// # use futures::executor::block_on; + /// # use matrix_sdk::Client; + /// # use url::Url; + /// # block_on(async { + /// # let homeserver = Url::parse("http://locahost:8080").unwrap(); + /// # let client = Client::new(homeserver).unwrap(); + /// let path = Path::new("/home/example/selfie.jpg"); + /// let mut image = File::open(&path).unwrap(); + /// + /// client.upload_avatar(&mime::IMAGE_JPEG, &mut image).await.expect("Can't set avatar"); + /// # }) + /// ``` + pub async fn upload_avatar(&self, content_type: &Mime, reader: &mut R) -> Result<()> { + let upload_response = self.upload(content_type, reader).await?; + self.set_avatar_url(Some(&upload_response.content_uri)) + .await?; + Ok(()) + } + /// Add `EventEmitter` to `Client`. /// /// The methods of `EventEmitter` are called when the respective `RoomEvents` occur. From 2cc899338a5fd8a0b47a570bbc891047487ca8fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 11:21:09 +0100 Subject: [PATCH 10/27] CI: Split out the fmt and clippy runs into two jobs. --- .github/workflows/lint.yml | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index ad5c1e91..ffb02400 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -1,4 +1,4 @@ -name: Lint +name: CI on: push: @@ -9,16 +9,21 @@ env: CARGO_TERM_COLOR: always jobs: - lint: + style: + name: Check style runs-on: ubuntu-latest steps: - name: Checkout the repo uses: actions/checkout@v2 + - name: Install rust uses: actions-rs/toolchain@v1 with: toolchain: stable + components: rustfmt + profile: minimal + override: true - name: Cargo fmt uses: actions-rs/cargo@v1 @@ -26,6 +31,23 @@ jobs: command: fmt args: --all -- --check + clippy: + name: Run clippy + needs: [style] + runs-on: ubuntu-latest + + steps: + - name: Checkout the repo + uses: actions/checkout@v2 + + - name: Install rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + components: clippy + profile: minimal + override: true + - name: Clippy uses: actions-rs/cargo@v1 with: From e4779163b8d104f396212561f746db39716817ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 11:36:01 +0100 Subject: [PATCH 11/27] CI: Run the tests on the CI. --- .github/workflows/lint.yml | 48 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index ffb02400..ece8c47c 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -53,3 +53,51 @@ jobs: with: command: clippy args: --all-targets -- -D warnings + + test: + name: ${{ matrix.name }} + needs: [clippy] + + runs-on: ${{ matrix.os || 'ubuntu-latest' }} + strategy: + matrix: + name: + - linux / stable + - linux / beta + - macOS / stable + - windows / stable-x86_64-msvc + + include: + - name: linux / stable + + - name: linux / beta + rust: beta + + - name: macOS / stable + os: macOS-latest + + - name: windows / stable-x86_64-msvc + os: windows-latest + target: x86_64-pc-windows-msvc + + steps: + - name: Checkout + uses: actions/checkout@v1 + + - name: Install rust + uses: actions-rs/toolchain@v1 + with: + toolchain: ${{ matrix.rust || 'stable' }} + target: ${{ matrix.target }} + profile: minimal + override: true + + - name: Build + uses: actions-rs/cargo@v1 + with: + command: build + + - name: Test + uses: actions-rs/cargo@v1 + with: + command: test From 27d9cf04de50fd852cf36df2becbdc2b36c6cbb8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 11:52:21 +0100 Subject: [PATCH 12/27] base: Remove a flaky state store test. The state store is undergoing a rewrite and this test fails more often than i would like making our CI seem flaky. Remove the test since it's going to become obsolete anyways. --- matrix_sdk_base/src/state/json_store.rs | 40 ------------------------- 1 file changed, 40 deletions(-) diff --git a/matrix_sdk_base/src/state/json_store.rs b/matrix_sdk_base/src/state/json_store.rs index 1eea500b..a959418d 100644 --- a/matrix_sdk_base/src/state/json_store.rs +++ b/matrix_sdk_base/src/state/json_store.rs @@ -360,44 +360,4 @@ mod test { // test that we have removed the correct room assert!(invited.is_empty()); } - - #[tokio::test] - async fn test_client_sync_store() { - let dir = tempdir().unwrap(); - let path: &Path = dir.path(); - - let session = Session { - access_token: "1234".to_owned(), - user_id: user_id!("@cheeky_monkey:matrix.org"), - device_id: "DEVICEID".into(), - }; - - // a sync response to populate our JSON store - let store = Box::new(JsonStore::open(path).unwrap()); - let client = - BaseClient::new_with_config(BaseClientConfig::new().state_store(store)).unwrap(); - client.restore_login(session.clone()).await.unwrap(); - - let mut response = sync_response(SyncResponseFile::Default); - - // gather state to save to the db, the first time through loading will be skipped - client.receive_sync_response(&mut response).await.unwrap(); - - // now syncing the client will update from the state store - let store = Box::new(JsonStore::open(path).unwrap()); - let client = - BaseClient::new_with_config(BaseClientConfig::new().state_store(store)).unwrap(); - client.restore_login(session.clone()).await.unwrap(); - - // assert the synced client and the logged in client are equal - assert_eq!(*client.session().read().await, Some(session)); - assert_eq!( - client.sync_token().await, - Some("s526_47314_0_7_1_1_1_11444_1".to_string()) - ); - assert_eq!( - *client.ignored_users.read().await, - vec![user_id!("@someone:example.org")] - ); - } } From a80aa4c2add874a567ddc89b587d20b841c65678 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 12:11:55 +0100 Subject: [PATCH 13/27] base: Fix some lint issues. --- matrix_sdk_base/src/state/json_store.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/matrix_sdk_base/src/state/json_store.rs b/matrix_sdk_base/src/state/json_store.rs index a959418d..19068995 100644 --- a/matrix_sdk_base/src/state/json_store.rs +++ b/matrix_sdk_base/src/state/json_store.rs @@ -224,11 +224,9 @@ mod test { use crate::{ identifiers::{room_id, user_id}, push::Ruleset, - BaseClient, BaseClientConfig, Session, + Session, }; - use matrix_sdk_test::{sync_response, SyncResponseFile}; - #[tokio::test] async fn test_store_client_state() { let dir = tempdir().unwrap(); From b982d363030741437e53d59067d1ccdb41c84b27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 12:34:59 +0100 Subject: [PATCH 14/27] crypto: Run the time sensitive tests only on linux. --- matrix_sdk_crypto/src/olm/group_sessions/mod.rs | 2 +- matrix_sdk_crypto/src/session_manager/sessions.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/matrix_sdk_crypto/src/olm/group_sessions/mod.rs b/matrix_sdk_crypto/src/olm/group_sessions/mod.rs index a78bde53..67ac13d9 100644 --- a/matrix_sdk_crypto/src/olm/group_sessions/mod.rs +++ b/matrix_sdk_crypto/src/olm/group_sessions/mod.rs @@ -138,7 +138,7 @@ mod test { use crate::ReadOnlyAccount; #[tokio::test] - #[cfg(not(target_os = "macos"))] + #[cfg(target_os = "linux")] async fn expiration() { let settings = EncryptionSettings { rotation_period_msgs: 1, diff --git a/matrix_sdk_crypto/src/session_manager/sessions.rs b/matrix_sdk_crypto/src/session_manager/sessions.rs index 2cf2a2cc..51dfcc5e 100644 --- a/matrix_sdk_crypto/src/session_manager/sessions.rs +++ b/matrix_sdk_crypto/src/session_manager/sessions.rs @@ -422,7 +422,7 @@ mod test { // This test doesn't run on macos because we're modifying the session // creation time so we can get around the UNWEDGING_INTERVAL. #[async_test] - #[cfg(not(target_os = "macos"))] + #[cfg(not(target_os = "linux"))] async fn session_unwedging() { let manager = session_manager().await; let bob = bob_account(); From 795c1225dde3e175913e1262780547cd228e1941 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 12:37:39 +0100 Subject: [PATCH 15/27] CI: Use the cargo-clippy workflow. --- .github/workflows/lint.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index ece8c47c..4f2094da 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -49,9 +49,9 @@ jobs: override: true - name: Clippy - uses: actions-rs/cargo@v1 + uses: actions-rs/clippy-check@v1 with: - command: clippy + token: ${{ secrets.GITHUB_TOKEN }} args: --all-targets -- -D warnings test: From 0a76f75c226025a39dcdacd071e969054dda2646 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 12:45:16 +0100 Subject: [PATCH 16/27] Revert "CI: Use the cargo-clippy workflow." This reverts commit 795c1225dde3e175913e1262780547cd228e1941. --- .github/workflows/lint.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 4f2094da..ece8c47c 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -49,9 +49,9 @@ jobs: override: true - name: Clippy - uses: actions-rs/clippy-check@v1 + uses: actions-rs/cargo@v1 with: - token: ${{ secrets.GITHUB_TOKEN }} + command: clippy args: --all-targets -- -D warnings test: From c8dd6bfd26ab2d2c2073b5328d8038d30d6d83fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 12:56:16 +0100 Subject: [PATCH 17/27] crypto: Scope the imports for the unwedging test into the test. --- matrix_sdk_crypto/src/session_manager/sessions.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/matrix_sdk_crypto/src/session_manager/sessions.rs b/matrix_sdk_crypto/src/session_manager/sessions.rs index 51dfcc5e..b074e305 100644 --- a/matrix_sdk_crypto/src/session_manager/sessions.rs +++ b/matrix_sdk_crypto/src/session_manager/sessions.rs @@ -316,8 +316,7 @@ mod test { use matrix_sdk_common::{ api::r0::keys::claim_keys::Response as KeyClaimResponse, - identifiers::{user_id, DeviceIdBox, DeviceKeyAlgorithm, UserId}, - instant::{Duration, Instant}, + identifiers::{user_id, DeviceIdBox, UserId}, }; use matrix_sdk_test::async_test; @@ -424,6 +423,11 @@ mod test { #[async_test] #[cfg(not(target_os = "linux"))] async fn session_unwedging() { + use matrix_sdk_common::{ + identifiers::DeviceKeyAlgorithm, + instant::{Duration, Instant}, + }; + let manager = session_manager().await; let bob = bob_account(); let (_, mut session) = bob.create_session_for(&manager.account).await; From 4ab6ae7f303cb2b46b36df628e437f4def65eb76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 13:15:19 +0100 Subject: [PATCH 18/27] crypto: Fix an os_target definition. --- matrix_sdk_crypto/src/session_manager/sessions.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matrix_sdk_crypto/src/session_manager/sessions.rs b/matrix_sdk_crypto/src/session_manager/sessions.rs index b074e305..95afe118 100644 --- a/matrix_sdk_crypto/src/session_manager/sessions.rs +++ b/matrix_sdk_crypto/src/session_manager/sessions.rs @@ -421,7 +421,7 @@ mod test { // This test doesn't run on macos because we're modifying the session // creation time so we can get around the UNWEDGING_INTERVAL. #[async_test] - #[cfg(not(target_os = "linux"))] + #[cfg(target_os = "linux")] async fn session_unwedging() { use matrix_sdk_common::{ identifiers::DeviceKeyAlgorithm, From 40d13d9b598a4ec244a1c5b641840292dc4c1b87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 13:37:55 +0100 Subject: [PATCH 19/27] cyrpto: Another timing based test that only works on Linux. --- matrix_sdk_crypto/src/verification/machine.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matrix_sdk_crypto/src/verification/machine.rs b/matrix_sdk_crypto/src/verification/machine.rs index c3ba5e88..c81344c3 100644 --- a/matrix_sdk_crypto/src/verification/machine.rs +++ b/matrix_sdk_crypto/src/verification/machine.rs @@ -380,7 +380,7 @@ mod test { assert!(bob.is_done()); } - #[cfg(not(target_os = "macos"))] + #[cfg(target_os = "linux")] #[tokio::test] async fn timing_out() { let (alice_machine, bob) = setup_verification_machine().await; From fdf48d1f30e1c10f5e6a92741b3affb08df673cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 13:58:26 +0100 Subject: [PATCH 20/27] CI: Rename the workflow file. --- .github/workflows/{lint.yml => ci.yml} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/workflows/{lint.yml => ci.yml} (100%) diff --git a/.github/workflows/lint.yml b/.github/workflows/ci.yml similarity index 100% rename from .github/workflows/lint.yml rename to .github/workflows/ci.yml From 9679db6ddc0097bcabfa7951b479439c3219fdbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 14:05:25 +0100 Subject: [PATCH 21/27] CI: Enable code coverage again. --- .github/workflows/coverage.yml | 36 ++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 .github/workflows/coverage.yml diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml new file mode 100644 index 00000000..5b0f562d --- /dev/null +++ b/.github/workflows/coverage.yml @@ -0,0 +1,36 @@ +name: Code coverage + +on: + push: + +env: + CARGO_TERM_COLOR: always + +jobs: + code_coverage: + name: Code Coverage + runs-on: "ubuntu-latest" + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + - name: Install stable toolchain + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + override: true + + - name: Install tarpaulin + uses: actions-rs/cargo@v1 + with: + command: install + args: cargo-tarpaulin -f + + - name: Run tarpaulin + uses: actions-rs/cargo@v1 + with: + command: tarpaulin + args: --ignore-config --exclude-files "matrix_sdk/examples/*,matrix_sdk_common,matrix_sdk_test" --out Xml + + - name: Upload to codecov.io + uses: codecov/codecov-action@v1 From fa3583234c2f997d9ceb9e60294ee47dc100b144 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 14:09:51 +0100 Subject: [PATCH 22/27] CI: Fix the coverage yml. --- .github/workflows/coverage.yml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 5b0f562d..bc3d12a9 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -8,9 +8,10 @@ env: jobs: code_coverage: - name: Code Coverage - runs-on: "ubuntu-latest" - steps: + name: Code Coverage + runs-on: "ubuntu-latest" + + steps: - name: Checkout repository uses: actions/checkout@v2 @@ -18,6 +19,7 @@ jobs: uses: actions-rs/toolchain@v1 with: toolchain: stable + profile: minimal override: true - name: Install tarpaulin From 15b87e9dc1fe6bf1dc488c9790b04a05b6f67378 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 14:30:49 +0100 Subject: [PATCH 23/27] CI: Restrict code coverage to the master branch. --- .github/workflows/coverage.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index bc3d12a9..8b9076e1 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -2,6 +2,7 @@ name: Code coverage on: push: + branches: [ master ] env: CARGO_TERM_COLOR: always From 594e9b9e2d53af88a3678890307c793a104e865a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 14:31:14 +0100 Subject: [PATCH 24/27] README: Swap out the CI badge. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2768c56f..7b5dc261 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -[![Build Status](https://img.shields.io/travis/matrix-org/matrix-rust-sdk.svg?style=flat-square)](https://travis-ci.org/matrix-org/matrix-rust-sdk) +![Build Status](https://img.shields.io/github/workflow/status/matrix-org/matrix-rust-sdk/CI?style=flat-square) [![codecov](https://img.shields.io/codecov/c/github/matrix-org/matrix-rust-sdk/master.svg?style=flat-square)](https://codecov.io/gh/matrix-org/matrix-rust-sdk) [![License](https://img.shields.io/badge/License-Apache%202.0-yellowgreen.svg?style=flat-square)](https://opensource.org/licenses/Apache-2.0) [![#matrix-rust-sdk](https://img.shields.io/badge/matrix-%23matrix--rust--sdk-blue?style=flat-square)](https://matrix.to/#/#matrix-rust-sdk:matrix.org) From fd705b7d5e5efb4535f834b9218e5b08423f8449 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 16:01:42 +0100 Subject: [PATCH 25/27] crypto: Canonicalize the start event content before calculating the commitment This fixes: #117. --- matrix_sdk_common/src/lib.rs | 2 +- .../src/verification/sas/helpers.rs | 59 +++++++++++++++++-- .../src/verification/sas/sas_state.rs | 32 +++++----- 3 files changed, 71 insertions(+), 22 deletions(-) diff --git a/matrix_sdk_common/src/lib.rs b/matrix_sdk_common/src/lib.rs index 92002cfc..13655d0a 100644 --- a/matrix_sdk_common/src/lib.rs +++ b/matrix_sdk_common/src/lib.rs @@ -8,7 +8,7 @@ pub use ruma::{ AuthScheme, EndpointError, OutgoingRequest, }, directory, encryption, events, identifiers, presence, push, - serde::Raw, + serde::{CanonicalJsonValue, Raw}, thirdparty, Outgoing, }; diff --git a/matrix_sdk_crypto/src/verification/sas/helpers.rs b/matrix_sdk_crypto/src/verification/sas/helpers.rs index 106727b8..5a85e958 100644 --- a/matrix_sdk_crypto/src/verification/sas/helpers.rs +++ b/matrix_sdk_crypto/src/verification/sas/helpers.rs @@ -16,16 +16,19 @@ use std::{collections::BTreeMap, convert::TryInto}; use tracing::{trace, warn}; -use olm_rs::sas::OlmSas; +use olm_rs::{sas::OlmSas, utility::OlmUtility}; use matrix_sdk_common::{ api::r0::to_device::DeviceIdOrAllDevices, events::{ - key::verification::{cancel::CancelCode, mac::MacToDeviceEventContent}, + key::verification::{ + cancel::CancelCode, mac::MacToDeviceEventContent, start::StartToDeviceEventContent, + }, AnyToDeviceEventContent, EventType, ToDeviceEvent, }, identifiers::{DeviceId, DeviceKeyAlgorithm, DeviceKeyId, UserId}, uuid::Uuid, + CanonicalJsonValue, }; use crate::{ @@ -40,6 +43,26 @@ pub struct SasIds { pub other_identity: Option, } +/// Calculate the commitment for a accept event from the public key and the +/// start event. +/// +/// # Arguments +/// +/// * `public_key` - Our own ephemeral public key that is used for the +/// interactive verification. +/// +/// * `content` - The `m.key.verification.start` event content that started the +/// interactive verification process. +pub fn calculate_commitment(public_key: &str, content: &StartToDeviceEventContent) -> String { + let json_content: CanonicalJsonValue = serde_json::to_value(content) + .expect("Can't serialize content") + .try_into() + .expect("Can't canonicalize content"); + + let utility = OlmUtility::new(); + utility.sha256_utf8_msg(&format!("{}{}", public_key, json_content)) +} + /// Get a tuple of an emoji and a description of the emoji using a number. /// /// This is taken directly from the [spec] @@ -493,12 +516,38 @@ pub fn content_to_request( #[cfg(test)] mod test { + use matrix_sdk_common::events::key::verification::start::StartToDeviceEventContent; use proptest::prelude::*; + use serde_json::json; - use super::{bytes_to_decimal, bytes_to_emoji, bytes_to_emoji_index, emoji_from_index}; + use super::{ + bytes_to_decimal, bytes_to_emoji, bytes_to_emoji_index, calculate_commitment, + emoji_from_index, + }; #[test] - fn test_emoji_generation() { + fn commitment_calculation() { + let commitment = "CCQmB4JCdB0FW21FdAnHj/Hu8+W9+Nb0vgwPEnZZQ4g"; + + let public_key = "Q/NmNFEUS1fS+YeEmiZkjjblKTitrKOAk7cPEumcMlg"; + let content = json!({ + "from_device":"XOWLHHFSWM", + "transaction_id":"bYxBsirjUJO9osar6ST4i2M2NjrYLA7l", + "method":"m.sas.v1", + "key_agreement_protocols":["curve25519-hkdf-sha256","curve25519"], + "hashes":["sha256"], + "message_authentication_codes":["hkdf-hmac-sha256","hmac-sha256"], + "short_authentication_string":["decimal","emoji"] + }); + + let content: StartToDeviceEventContent = serde_json::from_value(content).unwrap(); + let calculated_commitment = calculate_commitment(public_key, &content); + + assert_eq!(commitment, &calculated_commitment); + } + + #[test] + fn emoji_generation() { let bytes = vec![0, 0, 0, 0, 0, 0]; let index: Vec<(&'static str, &'static str)> = vec![0, 0, 0, 0, 0, 0, 0] .into_iter() @@ -516,7 +565,7 @@ mod test { } #[test] - fn test_decimal_generation() { + fn decimal_generation() { let bytes = vec![0, 0, 0, 0, 0]; let result = bytes_to_decimal(bytes); diff --git a/matrix_sdk_crypto/src/verification/sas/sas_state.rs b/matrix_sdk_crypto/src/verification/sas/sas_state.rs index 90966008..ab136cae 100644 --- a/matrix_sdk_crypto/src/verification/sas/sas_state.rs +++ b/matrix_sdk_crypto/src/verification/sas/sas_state.rs @@ -19,7 +19,7 @@ use std::{ time::{Duration, Instant}, }; -use olm_rs::{sas::OlmSas, utility::OlmUtility}; +use olm_rs::sas::OlmSas; use matrix_sdk_common::{ events::{ @@ -40,8 +40,11 @@ use matrix_sdk_common::{ identifiers::{DeviceId, UserId}, uuid::Uuid, }; +use tracing::error; -use super::helpers::{get_decimal, get_emoji, get_mac_content, receive_mac_event, SasIds}; +use super::helpers::{ + calculate_commitment, get_decimal, get_emoji, get_mac_content, receive_mac_event, SasIds, +}; use crate::{ identities::{ReadOnlyDevice, UserIdentities}, @@ -176,7 +179,7 @@ pub struct Started { #[derive(Clone, Debug)] pub struct Accepted { accepted_protocols: Arc, - json_start_content: String, + start_content: Arc, commitment: String, } @@ -348,8 +351,7 @@ impl SasState { let accepted_protocols = AcceptedProtocols::try_from(content.clone()).map_err(|c| self.clone().cancel(c))?; - let json_start_content = serde_json::to_string(&self.as_content()) - .expect("Can't deserialize start event content"); + let start_content = self.as_content().into(); Ok(SasState { inner: self.inner, @@ -358,9 +360,9 @@ impl SasState { creation_time: self.creation_time, last_event_time: self.last_event_time, state: Arc::new(Accepted { - json_start_content, + start_content, commitment: content.commitment.clone(), - accepted_protocols: Arc::new(accepted_protocols), + accepted_protocols: accepted_protocols.into(), }), }) } else { @@ -391,12 +393,14 @@ impl SasState { ) -> Result, SasState> { if let StartMethod::MSasV1(content) = &event.content.method { let sas = OlmSas::new(); - let utility = OlmUtility::new(); - 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)); + let commitment = calculate_commitment(&pubkey, &event.content); + + error!( + "Calculated commitment for pubkey {} and content {:?} {}", + pubkey, event.content, commitment + ); let sas = SasState { inner: Arc::new(Mutex::new(sas)), @@ -540,11 +544,7 @@ impl SasState { self.check_event(&event.sender, &event.content.transaction_id) .map_err(|c| self.clone().cancel(c))?; - let utility = OlmUtility::new(); - let commitment = utility.sha256_utf8_msg(&format!( - "{}{}", - event.content.key, self.state.json_start_content - )); + let commitment = calculate_commitment(&event.content.key, &self.state.start_content); if self.state.commitment != commitment { Err(self.cancel(CancelCode::InvalidMessage)) From b5c61af47234efe76a5017a8feff87268c6367a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 16:10:46 +0100 Subject: [PATCH 26/27] crypto: Move the base64 helpers into a common module. --- .../src/file_encryption/attachments.rs | 2 +- .../src/file_encryption/key_export.rs | 6 ++-- matrix_sdk_crypto/src/file_encryption/mod.rs | 18 ---------- matrix_sdk_crypto/src/lib.rs | 1 + matrix_sdk_crypto/src/olm/account.rs | 2 +- .../src/olm/signing/pk_signing.rs | 10 +----- matrix_sdk_crypto/src/utilities.rs | 36 +++++++++++++++++++ 7 files changed, 44 insertions(+), 31 deletions(-) create mode 100644 matrix_sdk_crypto/src/utilities.rs diff --git a/matrix_sdk_crypto/src/file_encryption/attachments.rs b/matrix_sdk_crypto/src/file_encryption/attachments.rs index 675e9ed7..b578d71c 100644 --- a/matrix_sdk_crypto/src/file_encryption/attachments.rs +++ b/matrix_sdk_crypto/src/file_encryption/attachments.rs @@ -33,7 +33,7 @@ use aes_ctr::{ use base64::DecodeError; use sha2::{Digest, Sha256}; -use super::{decode, decode_url_safe, encode, encode_url_safe}; +use crate::utilities::{decode, decode_url_safe, encode, encode_url_safe}; const IV_SIZE: usize = 16; const KEY_SIZE: usize = 32; diff --git a/matrix_sdk_crypto/src/file_encryption/key_export.rs b/matrix_sdk_crypto/src/file_encryption/key_export.rs index b881ec64..da394edf 100644 --- a/matrix_sdk_crypto/src/file_encryption/key_export.rs +++ b/matrix_sdk_crypto/src/file_encryption/key_export.rs @@ -27,8 +27,10 @@ use hmac::{Hmac, Mac, NewMac}; use pbkdf2::pbkdf2; use sha2::{Sha256, Sha512}; -use super::{decode, encode, DecodeError}; -use crate::olm::ExportedRoomKey; +use crate::{ + olm::ExportedRoomKey, + utilities::{decode, encode, DecodeError}, +}; const SALT_SIZE: usize = 16; const IV_SIZE: usize = 16; diff --git a/matrix_sdk_crypto/src/file_encryption/mod.rs b/matrix_sdk_crypto/src/file_encryption/mod.rs index 45ccd310..41e0b045 100644 --- a/matrix_sdk_crypto/src/file_encryption/mod.rs +++ b/matrix_sdk_crypto/src/file_encryption/mod.rs @@ -3,21 +3,3 @@ mod key_export; pub use attachments::{AttachmentDecryptor, AttachmentEncryptor, DecryptorError}; pub use key_export::{decrypt_key_export, encrypt_key_export}; - -use base64::{decode_config, encode_config, DecodeError, STANDARD_NO_PAD, URL_SAFE_NO_PAD}; - -fn decode(input: impl AsRef<[u8]>) -> Result, DecodeError> { - decode_config(input, STANDARD_NO_PAD) -} - -fn decode_url_safe(input: impl AsRef<[u8]>) -> Result, DecodeError> { - decode_config(input, URL_SAFE_NO_PAD) -} - -pub fn encode(input: impl AsRef<[u8]>) -> String { - encode_config(input, STANDARD_NO_PAD) -} - -pub fn encode_url_safe(input: impl AsRef<[u8]>) -> String { - encode_config(input, URL_SAFE_NO_PAD) -} diff --git a/matrix_sdk_crypto/src/lib.rs b/matrix_sdk_crypto/src/lib.rs index 0a1f0300..f37cf97e 100644 --- a/matrix_sdk_crypto/src/lib.rs +++ b/matrix_sdk_crypto/src/lib.rs @@ -36,6 +36,7 @@ pub mod olm; mod requests; mod session_manager; pub mod store; +mod utilities; mod verification; pub use error::{MegolmError, OlmError}; diff --git a/matrix_sdk_crypto/src/olm/account.rs b/matrix_sdk_crypto/src/olm/account.rs index a6beb442..9b6551bd 100644 --- a/matrix_sdk_crypto/src/olm/account.rs +++ b/matrix_sdk_crypto/src/olm/account.rs @@ -54,10 +54,10 @@ use olm_rs::{ use crate::{ error::{EventError, OlmResult, SessionCreationError}, - file_encryption::encode, identities::ReadOnlyDevice, requests::UploadSigningKeysRequest, store::{Changes, Store}, + utilities::encode, OlmError, }; diff --git a/matrix_sdk_crypto/src/olm/signing/pk_signing.rs b/matrix_sdk_crypto/src/olm/signing/pk_signing.rs index fb552349..661c7a61 100644 --- a/matrix_sdk_crypto/src/olm/signing/pk_signing.rs +++ b/matrix_sdk_crypto/src/olm/signing/pk_signing.rs @@ -16,7 +16,6 @@ use aes_gcm::{ aead::{generic_array::GenericArray, Aead, NewAead}, Aes256Gcm, }; -use base64::{decode_config, encode_config, DecodeError, URL_SAFE_NO_PAD}; use getrandom::getrandom; use matrix_sdk_common::{ encryption::DeviceKeys, @@ -42,19 +41,12 @@ use matrix_sdk_common::{ use crate::{ error::SignatureError, identities::{MasterPubkey, SelfSigningPubkey, UserSigningPubkey}, + utilities::{decode_url_safe as decode, encode_url_safe as encode, DecodeError}, UserIdentity, }; const NONCE_SIZE: usize = 12; -fn encode>(input: T) -> String { - encode_config(input, URL_SAFE_NO_PAD) -} - -fn decode>(input: T) -> Result, DecodeError> { - decode_config(input, URL_SAFE_NO_PAD) -} - /// Error type reporting failures in the Signign operations. #[derive(Debug, Error)] pub enum SigningError { diff --git a/matrix_sdk_crypto/src/utilities.rs b/matrix_sdk_crypto/src/utilities.rs new file mode 100644 index 00000000..fcf6dc5a --- /dev/null +++ b/matrix_sdk_crypto/src/utilities.rs @@ -0,0 +1,36 @@ +// Copyright 2020 The Matrix.org Foundation C.I.C. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub use base64::DecodeError; +use base64::{decode_config, encode_config, STANDARD_NO_PAD, URL_SAFE_NO_PAD}; + +/// Decode the input as base64 with no padding. +pub fn decode(input: impl AsRef<[u8]>) -> Result, DecodeError> { + decode_config(input, STANDARD_NO_PAD) +} + +/// Decode the input as URL safe base64 with no padding. +pub fn decode_url_safe(input: impl AsRef<[u8]>) -> Result, DecodeError> { + decode_config(input, URL_SAFE_NO_PAD) +} + +/// Encode the input as base64 with no padding. +pub fn encode(input: impl AsRef<[u8]>) -> String { + encode_config(input, STANDARD_NO_PAD) +} + +/// Encode the input as URL safe base64 with no padding. +pub fn encode_url_safe(input: impl AsRef<[u8]>) -> String { + encode_config(input, URL_SAFE_NO_PAD) +} From d9e5a17ab08b0386bbb32c1f0cbdeae876829be9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 8 Dec 2020 16:17:41 +0100 Subject: [PATCH 27/27] crypto: Use a native Rust sha2 implementation to calculate the commitment --- matrix_sdk_crypto/src/verification/sas/helpers.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/matrix_sdk_crypto/src/verification/sas/helpers.rs b/matrix_sdk_crypto/src/verification/sas/helpers.rs index 5a85e958..37974d14 100644 --- a/matrix_sdk_crypto/src/verification/sas/helpers.rs +++ b/matrix_sdk_crypto/src/verification/sas/helpers.rs @@ -14,9 +14,10 @@ use std::{collections::BTreeMap, convert::TryInto}; +use sha2::{Digest, Sha256}; use tracing::{trace, warn}; -use olm_rs::{sas::OlmSas, utility::OlmUtility}; +use olm_rs::sas::OlmSas; use matrix_sdk_common::{ api::r0::to_device::DeviceIdOrAllDevices, @@ -33,6 +34,7 @@ use matrix_sdk_common::{ use crate::{ identities::{ReadOnlyDevice, UserIdentities}, + utilities::encode, ReadOnlyAccount, ToDeviceRequest, }; @@ -59,8 +61,11 @@ pub fn calculate_commitment(public_key: &str, content: &StartToDeviceEventConten .try_into() .expect("Can't canonicalize content"); - let utility = OlmUtility::new(); - utility.sha256_utf8_msg(&format!("{}{}", public_key, json_content)) + encode( + Sha256::new() + .chain(&format!("{}{}", public_key, json_content)) + .finalize(), + ) } /// Get a tuple of an emoji and a description of the emoji using a number.