From 99ad3d63cb66dad44d014a4c86ee3d8a83dc8ed5 Mon Sep 17 00:00:00 2001 From: Ivan Enderlin Date: Fri, 4 Apr 2025 09:40:40 +0200 Subject: [PATCH 1/5] chore(cargo): Update `rand` to 0.9. This patch updates `rand` to 0.9. It brings several nice advantages: - it is compatible with the new Rust edition 2024, - it simplifies several signatures since `try_fill` is replaced by `fill`, there is no failure. --- Cargo.lock | 86 ++++++++++++++----- Cargo.toml | 2 +- .../src/backup_recovery_key.rs | 10 +-- .../src/dehydrated_devices.rs | 6 +- bindings/matrix-sdk-crypto-ffi/src/lib.rs | 5 +- .../src/backups/keys/decryption.rs | 8 +- crates/matrix-sdk-crypto/src/backups/mod.rs | 8 +- crates/matrix-sdk-crypto/src/ciphers.rs | 4 +- .../src/dehydrated_devices.rs | 2 +- .../src/file_encryption/attachments.rs | 4 +- .../src/file_encryption/key_export.rs | 4 +- .../src/gossiping/machine.rs | 2 +- .../src/machine/tests/mod.rs | 2 +- .../matrix-sdk-crypto/src/secret_storage.rs | 8 +- .../src/store/integration_tests.rs | 6 +- crates/matrix-sdk-crypto/src/store/mod.rs | 19 ++-- .../src/verification/qrcode.rs | 4 +- crates/matrix-sdk-store-encryption/src/lib.rs | 28 +++--- .../matrix-sdk/src/encryption/backups/mod.rs | 5 +- crates/matrix-sdk/src/encryption/mod.rs | 3 +- crates/matrix-sdk/src/utils/local_server.rs | 4 +- examples/oauth_cli/src/main.rs | 4 +- examples/persist_session/src/main.rs | 4 +- .../src/helpers.rs | 2 +- .../src/tests/room_directory_search.rs | 8 +- .../src/tests/sliding_sync/room.rs | 2 +- 26 files changed, 131 insertions(+), 109 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9a9be1ca267..54c9eee987d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -60,7 +60,7 @@ dependencies = [ "getrandom 0.2.15", "once_cell", "version_check", - "zerocopy", + "zerocopy 0.7.35", ] [[package]] @@ -447,7 +447,7 @@ dependencies = [ "getrandom 0.2.15", "instant", "pin-project-lite", - "rand", + "rand 0.8.5", "tokio", ] @@ -1556,7 +1556,7 @@ dependencies = [ "futures-util", "matrix-sdk", "matrix-sdk-ui", - "rand", + "rand 0.9.0", "serde", "serde_json", "tokio", @@ -1571,7 +1571,7 @@ dependencies = [ "anyhow", "dirs 5.0.1", "matrix-sdk", - "rand", + "rand 0.9.0", "serde", "serde_json", "tokio", @@ -2899,7 +2899,7 @@ dependencies = [ "percent-encoding", "pin-project-lite", "proptest", - "rand", + "rand 0.9.0", "reqwest", "ruma", "serde", @@ -3025,7 +3025,7 @@ dependencies = [ "matrix-sdk-test", "pbkdf2", "proptest", - "rand", + "rand 0.9.0", "rmp-serde", "ruma", "serde", @@ -3061,7 +3061,7 @@ dependencies = [ "matrix-sdk-ffi-macros", "matrix-sdk-sqlite", "pbkdf2", - "rand", + "rand 0.9.0", "ruma", "serde", "serde_json", @@ -3139,7 +3139,7 @@ dependencies = [ "matrix-sdk-crypto", "matrix-sdk-store-encryption", "matrix-sdk-test", - "rand", + "rand 0.9.0", "ruma", "serde", "serde-wasm-bindgen", @@ -3176,7 +3176,7 @@ dependencies = [ "matrix-sdk-test", "matrix-sdk-ui", "once_cell", - "rand", + "rand 0.9.0", "reqwest", "serde_json", "similar-asserts", @@ -3239,7 +3239,7 @@ dependencies = [ "getrandom 0.2.15", "hmac", "pbkdf2", - "rand", + "rand 0.9.0", "rmp-serde", "serde", "serde_json", @@ -3527,7 +3527,7 @@ dependencies = [ "chrono", "getrandom 0.2.15", "http", - "rand", + "rand 0.8.5", "reqwest", "serde", "serde_json", @@ -3762,7 +3762,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6" dependencies = [ "phf_shared 0.10.0", - "rand", + "rand 0.8.5", ] [[package]] @@ -3772,7 +3772,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0" dependencies = [ "phf_shared 0.11.2", - "rand", + "rand 0.8.5", ] [[package]] @@ -3988,8 +3988,8 @@ dependencies = [ "bitflags 2.8.0", "lazy_static", "num-traits", - "rand", - "rand_chacha", + "rand 0.8.5", + "rand_chacha 0.3.1", "rand_xorshift", "regex-syntax 0.8.5", "unarray", @@ -4078,7 +4078,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fadfaed2cd7f389d0161bb73eeb07b7b78f8691047a6f3e73caaeae55310a4a6" dependencies = [ "bytes", - "rand", + "rand 0.8.5", "ring", "rustc-hash 2.0.0", "rustls", @@ -4116,10 +4116,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ "libc", - "rand_chacha", + "rand_chacha 0.3.1", "rand_core 0.6.4", ] +[[package]] +name = "rand" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.3", + "zerocopy 0.8.24", +] + [[package]] name = "rand_chacha" version = "0.3.1" @@ -4130,6 +4141,16 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.3", +] + [[package]] name = "rand_core" version = "0.6.4" @@ -4144,6 +4165,9 @@ name = "rand_core" version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" +dependencies = [ + "getrandom 0.3.1", +] [[package]] name = "rand_xorshift" @@ -4466,7 +4490,7 @@ dependencies = [ "js_int", "konst", "percent-encoding", - "rand", + "rand 0.8.5", "regex", "ruma-identifiers-validation", "ruma-macros", @@ -5553,7 +5577,7 @@ version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f294bff79170ed1c5633812aff1e565c35d993a36e757f9bc0accf5eec4e6045" dependencies = [ - "rand", + "rand 0.8.5", "web-time", ] @@ -5873,7 +5897,7 @@ dependencies = [ "hmac", "matrix-pickle", "prost", - "rand", + "rand 0.8.5", "serde", "serde_bytes", "serde_json", @@ -6414,7 +6438,16 @@ version = "0.7.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" dependencies = [ - "zerocopy-derive", + "zerocopy-derive 0.7.35", +] + +[[package]] +name = "zerocopy" +version = "0.8.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2586fea28e186957ef732a5f8b3be2da217d65c5969d4b1e17f973ebbe876879" +dependencies = [ + "zerocopy-derive 0.8.24", ] [[package]] @@ -6428,6 +6461,17 @@ dependencies = [ "syn", ] +[[package]] +name = "zerocopy-derive" +version = "0.8.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a996a8f63c5c4448cd959ac1bab0aaa3306ccfd060472f85943ee0750f0169be" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "zerofrom" version = "0.1.5" diff --git a/Cargo.toml b/Cargo.toml index cf2dc409f78..c49a78a4344 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,7 +55,7 @@ once_cell = "1.20.2" pbkdf2 = { version = "0.12.2" } pin-project-lite = "0.2.16" proptest = { version = "1.6.0", default-features = false, features = ["std"] } -rand = "0.8.5" +rand = "0.9.0" reqwest = { version = "0.12.12", default-features = false } rmp-serde = "1.3.0" # Be careful to use commits from the https://github.com/ruma/ruma/tree/ruma-0.12 diff --git a/bindings/matrix-sdk-crypto-ffi/src/backup_recovery_key.rs b/bindings/matrix-sdk-crypto-ffi/src/backup_recovery_key.rs index 05c17b8aec5..ce9e14ce0b2 100644 --- a/bindings/matrix-sdk-crypto-ffi/src/backup_recovery_key.rs +++ b/bindings/matrix-sdk-crypto-ffi/src/backup_recovery_key.rs @@ -6,7 +6,7 @@ use matrix_sdk_crypto::{ store::{BackupDecryptionKey, CryptoStoreError as InnerStoreError}, }; use pbkdf2::pbkdf2; -use rand::{distributions::Alphanumeric, thread_rng, Rng}; +use rand::{distr::Alphanumeric, rng, Rng}; use sha2::Sha512; use thiserror::Error; use zeroize::Zeroize; @@ -75,11 +75,7 @@ impl BackupRecoveryKey { #[allow(clippy::new_without_default)] #[uniffi::constructor] pub fn new() -> Arc { - Arc::new(Self { - inner: BackupDecryptionKey::new() - .expect("Can't gather enough randomness to create a recovery key"), - passphrase_info: None, - }) + Arc::new(Self { inner: BackupDecryptionKey::new(), passphrase_info: None }) } /// Try to create a [`BackupRecoveryKey`] from a base 64 encoded string. @@ -97,7 +93,7 @@ impl BackupRecoveryKey { /// Create a new [`BackupRecoveryKey`] from the given passphrase. #[uniffi::constructor] pub fn new_from_passphrase(passphrase: String) -> Arc { - let mut rng = thread_rng(); + let mut rng = rng(); let salt: String = iter::repeat(()) .map(|()| rng.sample(Alphanumeric)) .map(char::from) diff --git a/bindings/matrix-sdk-crypto-ffi/src/dehydrated_devices.rs b/bindings/matrix-sdk-crypto-ffi/src/dehydrated_devices.rs index 0fc8af94a3c..87b5f3d6bba 100644 --- a/bindings/matrix-sdk-crypto-ffi/src/dehydrated_devices.rs +++ b/bindings/matrix-sdk-crypto-ffi/src/dehydrated_devices.rs @@ -28,8 +28,6 @@ pub enum DehydrationError { Store(#[from] matrix_sdk_crypto::CryptoStoreError), #[error("The pickle key has an invalid length, expected 32 bytes, got {0}")] PickleKeyLength(usize), - #[error(transparent)] - Rand(#[from] rand::Error), } impl From for DehydrationError { @@ -226,9 +224,7 @@ mod tests { #[test] fn test_creating_dehydrated_key() { - let result = DehydratedDeviceKey::new(); - assert!(result.is_ok()); - let dehydrated_device_key = result.unwrap(); + let dehydrated_device_key = DehydratedDeviceKey::new(); let base_64 = dehydrated_device_key.to_base64(); let inner_bytes = dehydrated_device_key.inner; diff --git a/bindings/matrix-sdk-crypto-ffi/src/lib.rs b/bindings/matrix-sdk-crypto-ffi/src/lib.rs index 9ebd94c2791..2759cdf81e4 100644 --- a/bindings/matrix-sdk-crypto-ffi/src/lib.rs +++ b/bindings/matrix-sdk-crypto-ffi/src/lib.rs @@ -841,9 +841,8 @@ pub struct DehydratedDeviceKey { impl DehydratedDeviceKey { /// Generates a new random pickle key. - pub fn new() -> Result { - let inner = InnerDehydratedDeviceKey::new()?; - Ok(inner.into()) + pub fn new() -> Self { + InnerDehydratedDeviceKey::new().into() } /// Creates a new dehydration pickle key from the given slice. diff --git a/crates/matrix-sdk-crypto/src/backups/keys/decryption.rs b/crates/matrix-sdk-crypto/src/backups/keys/decryption.rs index 28cfa6e02f4..1e241694daa 100644 --- a/crates/matrix-sdk-crypto/src/backups/keys/decryption.rs +++ b/crates/matrix-sdk-crypto/src/backups/keys/decryption.rs @@ -303,7 +303,7 @@ mod tests { #[test] fn base64_decoding() -> Result<(), DecodeError> { - let key = BackupDecryptionKey::new().expect("Can't create a new recovery key"); + let key = BackupDecryptionKey::new(); let base64 = key.to_base64(); let decoded_key = BackupDecryptionKey::from_base64(&base64)?; @@ -316,7 +316,7 @@ mod tests { #[test] fn base58_decoding() -> Result<(), DecodeError> { - let key = BackupDecryptionKey::new().expect("Can't create a new recovery key"); + let key = BackupDecryptionKey::new(); let base64 = key.to_base58(); let decoded_key = BackupDecryptionKey::from_base58(&base64)?; @@ -394,7 +394,7 @@ mod tests { async fn test_encryption_cycle() { let session = InboundGroupSession::from_export(&room_key()).unwrap(); - let decryption_key = BackupDecryptionKey::new().unwrap(); + let decryption_key = BackupDecryptionKey::new(); let encryption_key = decryption_key.megolm_v1_public_key(); let encrypted = encryption_key.encrypt(session).await; @@ -406,7 +406,7 @@ mod tests { #[test] fn key_matches() { - let decryption_key = BackupDecryptionKey::new().unwrap(); + let decryption_key = BackupDecryptionKey::new(); let key_info = decryption_key.to_backup_info(); diff --git a/crates/matrix-sdk-crypto/src/backups/mod.rs b/crates/matrix-sdk-crypto/src/backups/mod.rs index b7433ec37e2..438f571b316 100644 --- a/crates/matrix-sdk-crypto/src/backups/mod.rs +++ b/crates/matrix-sdk-crypto/src/backups/mod.rs @@ -699,7 +699,7 @@ mod tests { assert_eq!(counts.total, 2, "Two room keys need to exist in the store"); assert_eq!(counts.backed_up, 0, "No room keys have been backed up yet"); - let decryption_key = BackupDecryptionKey::new().expect("Can't create new recovery key"); + let decryption_key = BackupDecryptionKey::new(); let backup_key = decryption_key.megolm_v1_public_key(); backup_key.set_version("1".to_owned()); @@ -836,7 +836,7 @@ mod tests { let backup_machine = machine.backup_machine(); // We set up a backup key, so that we can test `backup_machine.backup()` later. - let decryption_key = BackupDecryptionKey::new().expect("Couldn't create new recovery key"); + let decryption_key = BackupDecryptionKey::new(); let backup_key = decryption_key.megolm_v1_public_key(); backup_key.set_version("1".to_owned()); backup_machine.enable_backup_v1(backup_key).await.expect("Couldn't enable backup"); @@ -884,7 +884,7 @@ mod tests { let machine = OlmMachine::new(alice_id(), alice_device_id()).await; let backup_machine = machine.backup_machine(); - let decryption_key = BackupDecryptionKey::new().unwrap(); + let decryption_key = BackupDecryptionKey::new(); let mut backup_info = decryption_key.to_backup_info(); let result = backup_machine.verify_backup(backup_info.to_owned(), false).await.unwrap(); @@ -902,7 +902,7 @@ mod tests { async fn test_fix_backup_key_mismatch() { let store = MemoryStore::new(); - let backup_decryption_key = BackupDecryptionKey::new().unwrap(); + let backup_decryption_key = BackupDecryptionKey::new(); store .save_changes(Changes { diff --git a/crates/matrix-sdk-crypto/src/ciphers.rs b/crates/matrix-sdk-crypto/src/ciphers.rs index 23dcc7dbd85..55684412ea0 100644 --- a/crates/matrix-sdk-crypto/src/ciphers.rs +++ b/crates/matrix-sdk-crypto/src/ciphers.rs @@ -23,7 +23,7 @@ use hmac::{ Hmac, Mac as _, }; use pbkdf2::pbkdf2; -use rand::{thread_rng, RngCore}; +use rand::{rng, RngCore}; use sha2::{Sha256, Sha512}; use zeroize::{Zeroize, ZeroizeOnDrop}; @@ -247,7 +247,7 @@ impl AesHmacSha2Key { /// The initialization vector will be clamped and will be used to encrypt /// the ciphertext. fn generate_iv() -> [u8; IV_SIZE] { - let mut rng = thread_rng(); + let mut rng = rng(); let mut iv = [0u8; IV_SIZE]; rng.fill_bytes(&mut iv); diff --git a/crates/matrix-sdk-crypto/src/dehydrated_devices.rs b/crates/matrix-sdk-crypto/src/dehydrated_devices.rs index 62ea9b08e1d..6e57066fe96 100644 --- a/crates/matrix-sdk-crypto/src/dehydrated_devices.rs +++ b/crates/matrix-sdk-crypto/src/dehydrated_devices.rs @@ -596,7 +596,7 @@ mod tests { let stored_key = dehydrated_manager.get_dehydrated_device_pickle_key().await.unwrap(); assert!(stored_key.is_none()); - let pickle_key = DehydratedDeviceKey::new().unwrap(); + let pickle_key = DehydratedDeviceKey::new(); dehydrated_manager.save_dehydrated_device_pickle_key(&pickle_key).await.unwrap(); diff --git a/crates/matrix-sdk-crypto/src/file_encryption/attachments.rs b/crates/matrix-sdk-crypto/src/file_encryption/attachments.rs index f83216ce43f..52b35d817be 100644 --- a/crates/matrix-sdk-crypto/src/file_encryption/attachments.rs +++ b/crates/matrix-sdk-crypto/src/file_encryption/attachments.rs @@ -21,7 +21,7 @@ use aes::{ cipher::{generic_array::GenericArray, KeyIvInit, StreamCipher}, Aes256, }; -use rand::{thread_rng, RngCore}; +use rand::{rng, RngCore}; use ruma::{ events::room::{EncryptedFile, JsonWebKey, JsonWebKeyInit}, serde::Base64, @@ -228,7 +228,7 @@ impl<'a, R: Read + ?Sized + 'a> AttachmentEncryptor<'a, R> { let mut key = [0u8; KEY_SIZE]; let mut iv = [0u8; IV_SIZE]; - let mut rng = thread_rng(); + let mut rng = rng(); rng.fill_bytes(&mut key); // Only populate the first 8 bytes with randomness, the rest is 0 diff --git a/crates/matrix-sdk-crypto/src/file_encryption/key_export.rs b/crates/matrix-sdk-crypto/src/file_encryption/key_export.rs index 01deb50a336..432a5376b2e 100644 --- a/crates/matrix-sdk-crypto/src/file_encryption/key_export.rs +++ b/crates/matrix-sdk-crypto/src/file_encryption/key_export.rs @@ -15,7 +15,7 @@ use std::io::{Cursor, Read, Seek, SeekFrom}; use byteorder::{BigEndian, ReadBytesExt}; -use rand::{thread_rng, RngCore}; +use rand::{rng, RngCore}; use serde_json::Error as SerdeError; use thiserror::Error; use vodozemac::{base64_decode, base64_encode}; @@ -149,7 +149,7 @@ pub fn encrypt_room_key_export( fn encrypt_helper(plaintext: &[u8], passphrase: &str, rounds: u32) -> String { let mut salt = [0u8; SALT_SIZE]; - let mut rng = thread_rng(); + let mut rng = rng(); rng.fill_bytes(&mut salt); diff --git a/crates/matrix-sdk-crypto/src/gossiping/machine.rs b/crates/matrix-sdk-crypto/src/gossiping/machine.rs index a589bef0d2b..5463a2adf17 100644 --- a/crates/matrix-sdk-crypto/src/gossiping/machine.rs +++ b/crates/matrix-sdk-crypto/src/gossiping/machine.rs @@ -2013,7 +2013,7 @@ mod tests { alice_machine.store().save_device_data(&[bob_device.inner]).await.unwrap(); bob_machine.store().save_device_data(&[alice_device.inner]).await.unwrap(); - let decryption_key = crate::store::BackupDecryptionKey::new().unwrap(); + let decryption_key = crate::store::BackupDecryptionKey::new(); alice_machine .backup_machine() .save_decryption_key(Some(decryption_key), None) diff --git a/crates/matrix-sdk-crypto/src/machine/tests/mod.rs b/crates/matrix-sdk-crypto/src/machine/tests/mod.rs index c464d1f056c..15dfd257a02 100644 --- a/crates/matrix-sdk-crypto/src/machine/tests/mod.rs +++ b/crates/matrix-sdk-crypto/src/machine/tests/mod.rs @@ -1288,7 +1288,7 @@ async fn test_wait_on_key_query_doesnt_block_store() { async fn test_fix_incorrect_usage_of_backup_key_causing_decryption_errors() { let store = MemoryStore::new(); - let backup_decryption_key = BackupDecryptionKey::new().unwrap(); + let backup_decryption_key = BackupDecryptionKey::new(); store .save_changes(Changes { diff --git a/crates/matrix-sdk-crypto/src/secret_storage.rs b/crates/matrix-sdk-crypto/src/secret_storage.rs index 1fbd868153d..6eecfffc6eb 100644 --- a/crates/matrix-sdk-crypto/src/secret_storage.rs +++ b/crates/matrix-sdk-crypto/src/secret_storage.rs @@ -23,8 +23,8 @@ pub use hmac::digest::MacError; use hmac::Hmac; use pbkdf2::pbkdf2; use rand::{ - distributions::{Alphanumeric, DistString}, - thread_rng, RngCore, + distr::{Alphanumeric, SampleString}, + rng, RngCore, }; use ruma::{ events::{ @@ -302,7 +302,7 @@ impl SecretStorageKey { /// Create a new random [`SecretStorageKey`]. pub fn new() -> Self { let mut key = Box::new([0u8; KEY_SIZE]); - let mut rng = thread_rng(); + let mut rng = rng(); rng.fill_bytes(key.as_mut_slice()); let key_id = Alphanumeric.sample_string(&mut rng, Self::DEFAULT_KEY_ID_LEN); @@ -318,7 +318,7 @@ impl SecretStorageKey { /// [spec]: https://spec.matrix.org/v1.8/client-server-api/#deriving-keys-from-passphrases pub fn new_from_passphrase(passphrase: &str) -> Self { let mut key = Box::new([0u8; 32]); - let mut rng = thread_rng(); + let mut rng = rng(); let salt = Alphanumeric.sample_string(&mut rng, Self::DEFAULT_KEY_ID_LEN); pbkdf2::>( diff --git a/crates/matrix-sdk-crypto/src/store/integration_tests.rs b/crates/matrix-sdk-crypto/src/store/integration_tests.rs index 2c0f9baf519..25ae472785f 100644 --- a/crates/matrix-sdk-crypto/src/store/integration_tests.rs +++ b/crates/matrix-sdk-crypto/src/store/integration_tests.rs @@ -1200,7 +1200,7 @@ macro_rules! cryptostore_integration_tests { let restored = store.load_backup_keys().await.unwrap(); assert!(restored.decryption_key.is_none(), "Initially no backup decryption key should be present"); - let backup_decryption_key = Some(BackupDecryptionKey::new().unwrap()); + let backup_decryption_key = Some(BackupDecryptionKey::new()); let changes = Changes { backup_decryption_key, ..Default::default() }; store.save_changes(changes).await.unwrap(); @@ -1224,7 +1224,7 @@ macro_rules! cryptostore_integration_tests { let restored = store.load_dehydrated_device_pickle_key().await.unwrap(); assert!(restored.is_none(), "Initially no pickle key should be present"); - let dehydrated_device_pickle_key = Some(DehydratedDeviceKey::new().unwrap()); + let dehydrated_device_pickle_key = Some(DehydratedDeviceKey::new()); let exported_base64 = dehydrated_device_pickle_key.clone().unwrap().to_base64(); let changes = Changes { dehydrated_device_pickle_key, ..Default::default() }; @@ -1248,7 +1248,7 @@ macro_rules! cryptostore_integration_tests { async fn test_delete_dehydration_pickle_key() { let (_account, store) = get_loaded_store("delete_dehydration_pickle_key").await; - let dehydrated_device_pickle_key = DehydratedDeviceKey::new().unwrap(); + let dehydrated_device_pickle_key = DehydratedDeviceKey::new(); let changes = Changes { dehydrated_device_pickle_key: Some(dehydrated_device_pickle_key), ..Default::default() }; store.save_changes(changes).await.unwrap(); diff --git a/crates/matrix-sdk-crypto/src/store/mod.rs b/crates/matrix-sdk-crypto/src/store/mod.rs index f5dc8c58be7..4305adf5b7a 100644 --- a/crates/matrix-sdk-crypto/src/store/mod.rs +++ b/crates/matrix-sdk-crypto/src/store/mod.rs @@ -739,13 +739,13 @@ impl BackupDecryptionKey { pub const KEY_SIZE: usize = 32; /// Create a new random decryption key. - pub fn new() -> Result { - let mut rng = rand::thread_rng(); + pub fn new() -> Self { + let mut rng = rand::rng(); let mut key = Box::new([0u8; Self::KEY_SIZE]); - rand::Fill::try_fill(key.as_mut_slice(), &mut rng)?; + rand::Fill::fill(key.as_mut_slice(), &mut rng); - Ok(Self { inner: key }) + Self { inner: key } } /// Export the [`BackupDecryptionKey`] as a base64 encoded string. @@ -776,13 +776,13 @@ impl DehydratedDeviceKey { pub const KEY_SIZE: usize = 32; /// Generates a new random pickle key. - pub fn new() -> Result { - let mut rng = rand::thread_rng(); + pub fn new() -> Self { + let mut rng = rand::rng(); let mut key = Box::new([0u8; Self::KEY_SIZE]); - rand::Fill::try_fill(key.as_mut_slice(), &mut rng)?; + rand::Fill::fill(key.as_mut_slice(), &mut rng); - Ok(Self { inner: key }) + Self { inner: key } } /// Creates a new dehydration pickle key from the given slice. @@ -2210,8 +2210,7 @@ mod tests { #[async_test] async fn test_create_dehydrated_device_key() { - let pickle_key = DehydratedDeviceKey::new() - .expect("Should be able to create a random dehydrated device key"); + let pickle_key = DehydratedDeviceKey::new(); let to_vec = pickle_key.inner.to_vec(); let pickle_key_from_slice = DehydratedDeviceKey::from_slice(to_vec.as_slice()) diff --git a/crates/matrix-sdk-crypto/src/verification/qrcode.rs b/crates/matrix-sdk-crypto/src/verification/qrcode.rs index 6907fe27b98..41bfbcde14f 100644 --- a/crates/matrix-sdk-crypto/src/verification/qrcode.rs +++ b/crates/matrix-sdk-crypto/src/verification/qrcode.rs @@ -22,7 +22,7 @@ use matrix_sdk_qrcode::{ qrcode::QrCode, EncodingError, QrVerificationData, SelfVerificationData, SelfVerificationNoMasterKey, VerificationData, }; -use rand::{thread_rng, RngCore}; +use rand::{rng, RngCore}; use ruma::{ api::client::keys::upload_signatures::v3::Request as SignatureUploadRequest, events::{ @@ -495,7 +495,7 @@ impl QrVerification { fn generate_secret() -> Base64 { let mut shared_secret = vec![0u8; SECRET_SIZE]; - let mut rng = thread_rng(); + let mut rng = rng(); rng.fill_bytes(&mut shared_secret); Base64::new(shared_secret) diff --git a/crates/matrix-sdk-store-encryption/src/lib.rs b/crates/matrix-sdk-store-encryption/src/lib.rs index dea7e7e440c..8533b6c0549 100644 --- a/crates/matrix-sdk-store-encryption/src/lib.rs +++ b/crates/matrix-sdk-store-encryption/src/lib.rs @@ -30,7 +30,7 @@ use chacha20poly1305::{ }; use hmac::Hmac; use pbkdf2::pbkdf2; -use rand::{thread_rng, Error as RandomError, Fill}; +use rand::{rng, Fill}; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use sha2::Sha256; use zeroize::{Zeroize, ZeroizeOnDrop}; @@ -63,10 +63,6 @@ pub enum Error { #[error("Error encrypting or decrypting a value: `{0}`")] Encryption(#[from] EncryptionError), - /// Could not generate enough randomness for a cryptographic operation: {0} - #[error("Could not generate enough randomness for a cryptographic operation: `{0}`")] - Random(#[from] RandomError), - /// Unsupported ciphertext version. #[error("Unsupported ciphertext version, expected `{0}`, got `{1}`")] Version(u8, u8), @@ -189,7 +185,7 @@ impl StoreCipher { let key = ChachaKey::from_slice(key.as_ref()); let cipher = XChaCha20Poly1305::new(key); - let nonce = Keys::get_nonce()?; + let nonce = Keys::get_nonce(); let mut keys = [0u8; 64]; @@ -212,10 +208,10 @@ impl StoreCipher { } fn export_kdf(&self, passphrase: &str, kdf_rounds: u32) -> Result, Error> { - let mut rng = thread_rng(); + let mut rng = rng(); let mut salt = [0u8; KDF_SALT_SIZE]; - salt.try_fill(&mut rng)?; + salt.fill(&mut rng); let key = StoreCipher::expand_key(passphrase, &salt, kdf_rounds); @@ -451,7 +447,7 @@ impl StoreCipher { /// # anyhow::Ok(()) }; /// ``` pub fn encrypt_value_data(&self, mut data: Vec) -> Result { - let nonce = Keys::get_nonce()?; + let nonce = Keys::get_nonce(); let cipher = XChaCha20Poly1305::new(self.inner.encryption_key()); let ciphertext = cipher.encrypt(XNonce::from_slice(&nonce), data.as_ref())?; @@ -733,10 +729,10 @@ impl Keys { let mut encryption_key = Box::new([0u8; 32]); let mut mac_key_seed = Box::new([0u8; 32]); - let mut rng = thread_rng(); + let mut rng = rng(); - encryption_key.try_fill(&mut rng)?; - mac_key_seed.try_fill(&mut rng)?; + encryption_key.fill(&mut rng); + mac_key_seed.fill(&mut rng); Ok(Self { encryption_key, mac_key_seed }) } @@ -760,13 +756,13 @@ impl Keys { key } - fn get_nonce() -> Result<[u8; XNONCE_SIZE], RandomError> { + fn get_nonce() -> [u8; XNONCE_SIZE] { let mut nonce = [0u8; XNONCE_SIZE]; - let mut rng = thread_rng(); + let mut rng = rng(); - nonce.try_fill(&mut rng)?; + nonce.fill(&mut rng); - Ok(nonce) + nonce } } diff --git a/crates/matrix-sdk/src/encryption/backups/mod.rs b/crates/matrix-sdk/src/encryption/backups/mod.rs index d48ec2f1f84..6a9b921086b 100644 --- a/crates/matrix-sdk/src/encryption/backups/mod.rs +++ b/crates/matrix-sdk/src/encryption/backups/mod.rs @@ -102,10 +102,7 @@ impl Backups { let olm_machine = olm_machine.as_ref().ok_or(Error::NoOlmMachine)?; // Create a new backup recovery key. - let decryption_key = BackupDecryptionKey::new().expect( - "We should be able to generate enough randomness to create a new backup recovery \ - key", - ); + let decryption_key = BackupDecryptionKey::new(); // Get the info about the new backup key, this needs to be uploaded to the // homeserver[1]. diff --git a/crates/matrix-sdk/src/encryption/mod.rs b/crates/matrix-sdk/src/encryption/mod.rs index 3d4e541f8c7..dce7206f088 100644 --- a/crates/matrix-sdk/src/encryption/mod.rs +++ b/crates/matrix-sdk/src/encryption/mod.rs @@ -1941,8 +1941,7 @@ mod tests { client1.olm_machine().await.clone().expect("must have an olm machine"); // Also enable backup to check that new machine has the same backup keys. - let decryption_key = matrix_sdk_base::crypto::store::BackupDecryptionKey::new() - .expect("Can't create new recovery key"); + let decryption_key = matrix_sdk_base::crypto::store::BackupDecryptionKey::new(); let backup_key = decryption_key.megolm_v1_public_key(); backup_key.set_version("1".to_owned()); initial_olm_machine diff --git a/crates/matrix-sdk/src/utils/local_server.rs b/crates/matrix-sdk/src/utils/local_server.rs index d70d1ba8d52..1d1311acce8 100644 --- a/crates/matrix-sdk/src/utils/local_server.rs +++ b/crates/matrix-sdk/src/utils/local_server.rs @@ -47,7 +47,7 @@ use std::{ use axum::{body::Body, response::IntoResponse, routing::any_service}; use http::{header, HeaderValue, Method, Request, StatusCode}; use matrix_sdk_base::{boxed_into_future, locks::Mutex}; -use rand::{thread_rng, Rng}; +use rand::{rng, Rng}; use tokio::{net::TcpListener, sync::oneshot}; use tower::service_fn; use url::Url; @@ -142,7 +142,7 @@ impl LocalServerBuilder { let mut n = 0u8; loop { - let port = thread_rng().gen_range(port_range.clone()); + let port = rng().random_range(port_range.clone()); let socket_addresses = ip_addresses.iter().map(|ip| SocketAddr::new(*ip, port)).collect::>(); diff --git a/examples/oauth_cli/src/main.rs b/examples/oauth_cli/src/main.rs index be6695f0639..a130d19984b 100644 --- a/examples/oauth_cli/src/main.rs +++ b/examples/oauth_cli/src/main.rs @@ -39,7 +39,7 @@ use matrix_sdk::{ Client, ClientBuildError, Result, RoomState, }; use matrix_sdk_ui::sync_service::SyncService; -use rand::{distributions::Alphanumeric, thread_rng, Rng}; +use rand::{distr::Alphanumeric, rng, Rng}; use serde::{Deserialize, Serialize}; use tokio::{fs, io::AsyncBufReadExt as _}; use url::Url; @@ -579,7 +579,7 @@ async fn build_client(data_dir: &Path) -> anyhow::Result<(Client, ClientSession) let db_path = data_dir.join("db"); // Generate a random passphrase. - let mut rng = thread_rng(); + let mut rng = rng(); let passphrase: String = (&mut rng).sample_iter(Alphanumeric).take(32).map(char::from).collect(); diff --git a/examples/persist_session/src/main.rs b/examples/persist_session/src/main.rs index 248612ccca2..2f275f1e000 100644 --- a/examples/persist_session/src/main.rs +++ b/examples/persist_session/src/main.rs @@ -12,7 +12,7 @@ use matrix_sdk::{ }, Client, Error, LoopCtrl, Room, RoomState, }; -use rand::{distributions::Alphanumeric, thread_rng, Rng}; +use rand::{distr::Alphanumeric, rng, Rng}; use serde::{Deserialize, Serialize}; use tokio::fs; @@ -162,7 +162,7 @@ async fn login(data_dir: &Path, session_file: &Path) -> anyhow::Result { /// Build a new client. async fn build_client(data_dir: &Path) -> anyhow::Result<(Client, ClientSession)> { - let mut rng = thread_rng(); + let mut rng = rng(); // Generating a subfolder for the database is not mandatory, but it is useful if // you allow several clients to run at the same time. Each one must have a diff --git a/testing/matrix-sdk-integration-testing/src/helpers.rs b/testing/matrix-sdk-integration-testing/src/helpers.rs index 18614c6ed4b..cce9b179325 100644 --- a/testing/matrix-sdk-integration-testing/src/helpers.rs +++ b/testing/matrix-sdk-integration-testing/src/helpers.rs @@ -42,7 +42,7 @@ pub struct TestClientBuilder { impl TestClientBuilder { pub fn new(username: impl AsRef) -> Self { - let suffix: u128 = rand::thread_rng().gen(); + let suffix: u128 = rand::rng().random(); let randomized_username = format!("{}{}", username.as_ref(), suffix); Self::with_exact_username(randomized_username) } diff --git a/testing/matrix-sdk-integration-testing/src/tests/room_directory_search.rs b/testing/matrix-sdk-integration-testing/src/tests/room_directory_search.rs index b6c20a665d9..4923bb72ad1 100644 --- a/testing/matrix-sdk-integration-testing/src/tests/room_directory_search.rs +++ b/testing/matrix-sdk-integration-testing/src/tests/room_directory_search.rs @@ -23,7 +23,7 @@ use matrix_sdk::{ room_directory_search::RoomDirectorySearch, ruma::api::client::room::{create_room::v3::Request as CreateRoomRequest, Visibility}, }; -use rand::{thread_rng, Rng}; +use rand::{rng, Rng}; use stream_assert::assert_pending; use tokio::time::sleep; use tracing::warn; @@ -72,9 +72,5 @@ async fn test_room_directory_search_filter() -> Result<()> { } fn random_string(length: usize) -> String { - thread_rng() - .sample_iter(&rand::distributions::Alphanumeric) - .take(length) - .map(char::from) - .collect() + rng().sample_iter(&rand::distr::Alphanumeric).take(length).map(char::from).collect() } diff --git a/testing/matrix-sdk-integration-testing/src/tests/sliding_sync/room.rs b/testing/matrix-sdk-integration-testing/src/tests/sliding_sync/room.rs index 0033edbddd9..211e8e85bdc 100644 --- a/testing/matrix-sdk-integration-testing/src/tests/sliding_sync/room.rs +++ b/testing/matrix-sdk-integration-testing/src/tests/sliding_sync/room.rs @@ -1058,7 +1058,7 @@ async fn test_room_preview() -> Result<()> { .await?; // Alice creates a room in which they're alone, to start with. - let suffix: u128 = rand::thread_rng().gen(); + let suffix: u128 = rand::rng().random(); let room_alias = format!("aliasy_mac_alias{suffix}"); let room = alice From 110b5163fc97509ff47ee0512c6e471d57069f23 Mon Sep 17 00:00:00 2001 From: Ivan Enderlin Date: Fri, 4 Apr 2025 09:48:11 +0200 Subject: [PATCH 2/5] doc(changelog): Add #4885. --- crates/matrix-sdk-crypto/CHANGELOG.md | 6 ++++++ crates/matrix-sdk-store-encryption/CHANGELOG.md | 5 +++++ 2 files changed, 11 insertions(+) diff --git a/crates/matrix-sdk-crypto/CHANGELOG.md b/crates/matrix-sdk-crypto/CHANGELOG.md index c86e561defe..3051ef14fbe 100644 --- a/crates/matrix-sdk-crypto/CHANGELOG.md +++ b/crates/matrix-sdk-crypto/CHANGELOG.md @@ -17,6 +17,12 @@ All notable changes to this project will be documented in this file. `shared_history` field that defaults to `false.` ([#4700](https://github.com/matrix-org/matrix-rust-sdk/pull/4700)) +## Refactor + +- [**breaking**] `BackupDecryptionKey` and `DehydratedDeviceKey` no longer return + a `Result` + ([#4885](https://github.com/matrix-org/matrix-rust-sdk/pull/4885)) + ## [0.10.0] - 2025-02-04 ### Features diff --git a/crates/matrix-sdk-store-encryption/CHANGELOG.md b/crates/matrix-sdk-store-encryption/CHANGELOG.md index 6d5e17c9936..b2757ef86e0 100644 --- a/crates/matrix-sdk-store-encryption/CHANGELOG.md +++ b/crates/matrix-sdk-store-encryption/CHANGELOG.md @@ -6,6 +6,11 @@ All notable changes to this project will be documented in this file. ## [Unreleased] - ReleaseDate +## Refactor + +- [**breaking**] `Error::Random` has been removed + ([#4885](https://github.com/matrix-org/matrix-rust-sdk/pull/4885)) + ## [0.10.0] - 2025-02-04 ### Bug Fixes From af39cbf9cf000c506f4f888ddff1fed9b04b10b7 Mon Sep 17 00:00:00 2001 From: Ivan Enderlin Date: Fri, 4 Apr 2025 09:50:14 +0200 Subject: [PATCH 3/5] feat(crypto): `BackupDecryptionKey` and `DehydratedDeviceKey` implement `Default`. --- crates/matrix-sdk-crypto/src/store/mod.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/crates/matrix-sdk-crypto/src/store/mod.rs b/crates/matrix-sdk-crypto/src/store/mod.rs index 4305adf5b7a..e164e7dcf82 100644 --- a/crates/matrix-sdk-crypto/src/store/mod.rs +++ b/crates/matrix-sdk-crypto/src/store/mod.rs @@ -754,6 +754,12 @@ impl BackupDecryptionKey { } } +impl Default for BackupDecryptionKey { + fn default() -> Self { + Self::new() + } +} + #[cfg(not(tarpaulin_include))] impl Debug for BackupDecryptionKey { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -812,6 +818,12 @@ impl DehydratedDeviceKey { } } +impl Default for DehydratedDeviceKey { + fn default() -> Self { + Self::new() + } +} + impl From<&[u8; 32]> for DehydratedDeviceKey { fn from(value: &[u8; 32]) -> Self { DehydratedDeviceKey { inner: Box::new(*value) } From dae799db31a97273d878ba56a330ef99e1982f5e Mon Sep 17 00:00:00 2001 From: Ivan Enderlin Date: Fri, 4 Apr 2025 09:58:40 +0200 Subject: [PATCH 4/5] chore(cargo): Update `getrandom` to 0.3.2. This patch deduplicates `getrandom` where it was present in 2 versions. It also updates `getrandom` to 0.3.2. --- Cargo.lock | 68 +++++++++++-------- Cargo.toml | 2 +- crates/matrix-sdk-base/Cargo.toml | 3 + crates/matrix-sdk-common/Cargo.toml | 3 +- crates/matrix-sdk-indexeddb/Cargo.toml | 3 +- crates/matrix-sdk-store-encryption/Cargo.toml | 2 +- crates/matrix-sdk-store-encryption/README.md | 4 +- testing/matrix-sdk-test/Cargo.toml | 2 +- 8 files changed, 51 insertions(+), 36 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 54c9eee987d..036b9ff73df 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1914,14 +1914,16 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43a49c392881ce6d5c3b8cb70f98717b7c07aabbdff06687b9030dbfbe2725f8" +checksum = "73fea8450eea4bac3940448fb7ae50d91f034f941199fcd9d909a5a07aa455f0" dependencies = [ "cfg-if", + "js-sys", "libc", - "wasi 0.13.3+wasi-0.2.2", - "windows-targets 0.52.6", + "r-efi", + "wasi 0.14.2+wasi-0.2.4", + "wasm-bindgen", ] [[package]] @@ -2594,10 +2596,11 @@ checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" [[package]] name = "js-sys" -version = "0.3.69" +version = "0.3.77" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d" +checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f" dependencies = [ + "once_cell", "wasm-bindgen", ] @@ -2943,6 +2946,7 @@ dependencies = [ "eyeball-im", "futures-executor", "futures-util", + "getrandom 0.3.2", "growable-bloom-filter", "http", "matrix-sdk-common", @@ -2973,7 +2977,7 @@ dependencies = [ "eyeball-im", "futures-core", "futures-util", - "getrandom 0.2.15", + "getrandom 0.3.2", "gloo-timers", "imbl", "insta", @@ -3128,7 +3132,7 @@ dependencies = [ "assert_matches2", "async-trait", "base64", - "getrandom 0.2.15", + "getrandom 0.3.2", "gloo-utils", "growable-bloom-filter", "hkdf", @@ -3236,7 +3240,7 @@ dependencies = [ "base64", "blake3", "chacha20poly1305", - "getrandom 0.2.15", + "getrandom 0.3.2", "hmac", "pbkdf2", "rand 0.9.0", @@ -3254,7 +3258,7 @@ version = "0.10.0" dependencies = [ "as_variant", "ctor", - "getrandom 0.2.15", + "getrandom 0.3.2", "http", "insta", "matrix-sdk-common", @@ -4109,6 +4113,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5" + [[package]] name = "rand" version = "0.8.5" @@ -4166,7 +4176,7 @@ version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" dependencies = [ - "getrandom 0.3.1", + "getrandom 0.3.2", ] [[package]] @@ -5147,7 +5157,7 @@ checksum = "38c246215d7d24f48ae091a2902398798e05d978b24315d6efbc00ede9a8bb91" dependencies = [ "cfg-if", "fastrand", - "getrandom 0.3.1", + "getrandom 0.3.2", "once_cell", "rustix", "windows-sys 0.59.0", @@ -5935,32 +5945,33 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasi" -version = "0.13.3+wasi-0.2.2" +version = "0.14.2+wasi-0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26816d2e1a4a36a2940b96c5296ce403917633dff8f3440e9b236ed6f6bacad2" +checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3" dependencies = [ "wit-bindgen-rt", ] [[package]] name = "wasm-bindgen" -version = "0.2.92" +version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" +checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5" dependencies = [ "cfg-if", + "once_cell", + "rustversion", "wasm-bindgen-macro", ] [[package]] name = "wasm-bindgen-backend" -version = "0.2.92" +version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" +checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6" dependencies = [ "bumpalo", "log", - "once_cell", "proc-macro2", "quote", "syn", @@ -5981,9 +5992,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.92" +version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" +checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -5991,9 +6002,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.92" +version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" +checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de" dependencies = [ "proc-macro2", "quote", @@ -6004,9 +6015,12 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.92" +version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" +checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d" +dependencies = [ + "unicode-ident", +] [[package]] name = "wasm-bindgen-test" @@ -6343,9 +6357,9 @@ dependencies = [ [[package]] name = "wit-bindgen-rt" -version = "0.33.0" +version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3268f3d866458b787f390cf61f4bbb563b922d091359f9608842999eaee3943c" +checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1" dependencies = [ "bitflags 2.8.0", ] diff --git a/Cargo.toml b/Cargo.toml index c49a78a4344..3517b17b559 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,7 +39,7 @@ eyeball-im-util = "0.9.0" futures-core = "0.3.31" futures-executor = "0.3.31" futures-util = "0.3.31" -getrandom = { version = "0.2.15", default-features = false } +getrandom = { version = "0.3.2", default-features = false } gloo-timers = "0.3.0" growable-bloom-filter = "2.1.1" hkdf = "0.12.4" diff --git a/crates/matrix-sdk-base/Cargo.toml b/crates/matrix-sdk-base/Cargo.toml index 330744efe90..d43d2305d96 100644 --- a/crates/matrix-sdk-base/Cargo.toml +++ b/crates/matrix-sdk-base/Cargo.toml @@ -76,6 +76,9 @@ thiserror = { workspace = true } tracing = { workspace = true } uniffi = { workspace = true, optional = true } +[target.'cfg(target_arch = "wasm32")'.dependencies] +getrandom = { workspace = true, features = ["wasm_js"] } + [dev-dependencies] assert_matches = { workspace = true } assert_matches2 = { workspace = true } diff --git a/crates/matrix-sdk-common/Cargo.toml b/crates/matrix-sdk-common/Cargo.toml index 9d2fbf90b9e..ebbaecd4e2e 100644 --- a/crates/matrix-sdk-common/Cargo.toml +++ b/crates/matrix-sdk-common/Cargo.toml @@ -57,8 +57,7 @@ insta = { workspace = true } tokio = { workspace = true, features = ["rt", "macros"] } [target.'cfg(target_arch = "wasm32")'.dev-dependencies] -# Enable the JS feature for getrandom. -getrandom = { workspace = true, default-features = false, features = ["js"] } +getrandom = { workspace = true, features = ["wasm_js"] } js-sys = { workspace = true } [lints] diff --git a/crates/matrix-sdk-indexeddb/Cargo.toml b/crates/matrix-sdk-indexeddb/Cargo.toml index b5c7a0a3080..10d0eaa9f17 100644 --- a/crates/matrix-sdk-indexeddb/Cargo.toml +++ b/crates/matrix-sdk-indexeddb/Cargo.toml @@ -44,8 +44,7 @@ zeroize = { workspace = true } sha2 = { workspace = true } [target.'cfg(target_arch = "wasm32")'.dependencies] -# for wasm32 we need to activate this -getrandom = { workspace = true, features = ["js"] } +getrandom = { workspace = true, features = ["wasm_js"] } [dev-dependencies] assert_matches = { workspace = true } diff --git a/crates/matrix-sdk-store-encryption/Cargo.toml b/crates/matrix-sdk-store-encryption/Cargo.toml index 8b57e96f0fd..182c9d08adc 100644 --- a/crates/matrix-sdk-store-encryption/Cargo.toml +++ b/crates/matrix-sdk-store-encryption/Cargo.toml @@ -11,7 +11,7 @@ rust-version = { workspace = true } rustdoc-args = ["--cfg", "docsrs"] [features] -js = ["dep:getrandom", "getrandom?/js"] +js = ["dep:getrandom", "getrandom?/wasm_js"] [dependencies] base64 = { workspace = true } diff --git a/crates/matrix-sdk-store-encryption/README.md b/crates/matrix-sdk-store-encryption/README.md index 8a2b0357f4c..5f082a53d3c 100644 --- a/crates/matrix-sdk-store-encryption/README.md +++ b/crates/matrix-sdk-store-encryption/README.md @@ -73,10 +73,10 @@ used for non-Matrix data, users need to ensure: to a DOS attack. 2. The `StoreCipher` is periodically rotated/rekeyed. -# WASM support +# Wasm support This crate relies on the `random` and `getrandom` crates which don't support -WASM automatically. +Wasm automatically. Either turn the `js` feature on directly on this crate or depend on `getrandom` with the `js` feature turned on. More info can be found in the [`getrandom` diff --git a/testing/matrix-sdk-test/Cargo.toml b/testing/matrix-sdk-test/Cargo.toml index 787819e112b..8ef2ea5868f 100644 --- a/testing/matrix-sdk-test/Cargo.toml +++ b/testing/matrix-sdk-test/Cargo.toml @@ -36,7 +36,7 @@ tracing-subscriber = { workspace = true, features = ["env-filter"] } wiremock = { workspace = true } [target.'cfg(target_arch = "wasm32")'.dependencies] -getrandom = { version = "0.2.6", default-features = false, features = ["js"] } +getrandom = { workspace = true, features = ["wasm_js"] } wasm-bindgen-test = "0.3.33" [lints] From d871b9b502983315d857ce6cc56d43b4230fd365 Mon Sep 17 00:00:00 2001 From: Ivan Enderlin Date: Fri, 4 Apr 2025 10:07:19 +0200 Subject: [PATCH 5/5] chore(ci): Add full support for testing `getrandom` in Wasm. --- xtask/src/ci.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/xtask/src/ci.rs b/xtask/src/ci.rs index 5678ec66a02..933b84fdcde 100644 --- a/xtask/src/ci.rs +++ b/xtask/src/ci.rs @@ -10,6 +10,8 @@ use crate::{build_docs, sh, workspace, DenyWarnings, Result, NIGHTLY}; const WASM_TIMEOUT_ENV_KEY: &str = "WASM_BINDGEN_TEST_TIMEOUT"; const WASM_TIMEOUT_VALUE: &str = "120"; +const RUSTFLAGS: &str = "RUSTFLAGS"; +const GETRANDOM_BACKEND: &str = "--cfg getrandom_backend=\"wasm_js\""; #[derive(Args)] pub struct CiArgs { @@ -330,6 +332,7 @@ fn run_wasm_checks(cmd: Option) -> Result<()> { cmd!(sh, "rustup run stable cargo clippy --target wasm32-unknown-unknown") .args(arg_set.split_whitespace()) .args(["--", "-D", "warnings"]) + .env(RUSTFLAGS, GETRANDOM_BACKEND) .env(WASM_TIMEOUT_ENV_KEY, WASM_TIMEOUT_VALUE) .run() }; @@ -394,10 +397,12 @@ fn run_wasm_pack_tests(cmd: Option) -> Result<()> { cmd!(sh, "pwd").env(WASM_TIMEOUT_ENV_KEY, WASM_TIMEOUT_VALUE).run()?; // print dir so we know what might have failed cmd!(sh, "wasm-pack test --node -- ") .args(arg_set.split_whitespace()) + .env(RUSTFLAGS, GETRANDOM_BACKEND) .env(WASM_TIMEOUT_ENV_KEY, WASM_TIMEOUT_VALUE) .run()?; cmd!(sh, "wasm-pack test --firefox --headless --") .args(arg_set.split_whitespace()) + .env(RUSTFLAGS, GETRANDOM_BACKEND) .env(WASM_TIMEOUT_ENV_KEY, WASM_TIMEOUT_VALUE) .run() };