Skip to content

chore(cargo): Update rand to 0.9, and getrandom to 0.3.2 #4885

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 105 additions & 47 deletions Cargo.lock

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand Down
10 changes: 3 additions & 7 deletions bindings/matrix-sdk-crypto-ffi/src/backup_recovery_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -75,11 +75,7 @@ impl BackupRecoveryKey {
#[allow(clippy::new_without_default)]
#[uniffi::constructor]
pub fn new() -> Arc<Self> {
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.
Expand All @@ -97,7 +93,7 @@ impl BackupRecoveryKey {
/// Create a new [`BackupRecoveryKey`] from the given passphrase.
#[uniffi::constructor]
pub fn new_from_passphrase(passphrase: String) -> Arc<Self> {
let mut rng = thread_rng();
let mut rng = rng();
let salt: String = iter::repeat(())
.map(|()| rng.sample(Alphanumeric))
.map(char::from)
Expand Down
6 changes: 1 addition & 5 deletions bindings/matrix-sdk-crypto-ffi/src/dehydrated_devices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<matrix_sdk_crypto::dehydrated_devices::DehydrationError> for DehydrationError {
Expand Down Expand Up @@ -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;

Expand Down
5 changes: 2 additions & 3 deletions bindings/matrix-sdk-crypto-ffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -841,9 +841,8 @@ pub struct DehydratedDeviceKey {

impl DehydratedDeviceKey {
/// Generates a new random pickle key.
pub fn new() -> Result<Self, DehydrationError> {
let inner = InnerDehydratedDeviceKey::new()?;
Ok(inner.into())
pub fn new() -> Self {
InnerDehydratedDeviceKey::new().into()
}

/// Creates a new dehydration pickle key from the given slice.
Expand Down
3 changes: 3 additions & 0 deletions crates/matrix-sdk-base/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
3 changes: 1 addition & 2 deletions crates/matrix-sdk-common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
6 changes: 6 additions & 0 deletions crates/matrix-sdk-crypto/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions crates/matrix-sdk-crypto/src/backups/keys/decryption.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)?;
Expand All @@ -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)?;
Expand Down Expand Up @@ -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;
Expand All @@ -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();

Expand Down
8 changes: 4 additions & 4 deletions crates/matrix-sdk-crypto/src/backups/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());

Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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();
Expand All @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions crates/matrix-sdk-crypto/src/ciphers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion crates/matrix-sdk-crypto/src/dehydrated_devices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
4 changes: 2 additions & 2 deletions crates/matrix-sdk-crypto/src/file_encryption/attachments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions crates/matrix-sdk-crypto/src/file_encryption/key_export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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);

Expand Down
2 changes: 1 addition & 1 deletion crates/matrix-sdk-crypto/src/gossiping/machine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion crates/matrix-sdk-crypto/src/machine/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
8 changes: 4 additions & 4 deletions crates/matrix-sdk-crypto/src/secret_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -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);
Expand All @@ -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::<Hmac<Sha512>>(
Expand Down
6 changes: 3 additions & 3 deletions crates/matrix-sdk-crypto/src/store/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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() };
Expand All @@ -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();
Expand Down
31 changes: 21 additions & 10 deletions crates/matrix-sdk-crypto/src/store/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -739,13 +739,13 @@ impl BackupDecryptionKey {
pub const KEY_SIZE: usize = 32;

/// Create a new random decryption key.
pub fn new() -> Result<Self, rand::Error> {
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.
Expand All @@ -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 {
Expand All @@ -776,13 +782,13 @@ impl DehydratedDeviceKey {
pub const KEY_SIZE: usize = 32;

/// Generates a new random pickle key.
pub fn new() -> Result<Self, rand::Error> {
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.
Expand Down Expand Up @@ -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) }
Expand Down Expand Up @@ -2210,8 +2222,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())
Expand Down
Loading
Loading