diff --git a/.rustfmt.toml b/.rustfmt.toml index 7763ce72e5..f3a280c402 100644 --- a/.rustfmt.toml +++ b/.rustfmt.toml @@ -1,6 +1,8 @@ use_try_shorthand = true use_field_init_shorthand = true max_width = 120 +comment_width = 120 +wrap_comments = true newline_style = "Unix" merge_derives = true condense_wildcard_suffixes = true diff --git a/crypto-ffi/src/core_crypto_context/mls.rs b/crypto-ffi/src/core_crypto_context/mls.rs index f95a0aace1..0566bf7849 100644 --- a/crypto-ffi/src/core_crypto_context/mls.rs +++ b/crypto-ffi/src/core_crypto_context/mls.rs @@ -379,7 +379,8 @@ impl CoreCryptoContext { /// Get all credentials from this client which match the provided parameters. /// - /// Parameters which are unset or `None` match anything. Those with a particular value find only credentials matching that value. + /// Parameters which are unset or `None` match anything. Those with a particular value find only credentials + /// matching that value. pub async fn find_credentials( &self, client_id: Option, diff --git a/crypto-ffi/src/core_crypto_context/proteus.rs b/crypto-ffi/src/core_crypto_context/proteus.rs index 60d966bf29..16abb51419 100644 --- a/crypto-ffi/src/core_crypto_context/proteus.rs +++ b/crypto-ffi/src/core_crypto_context/proteus.rs @@ -105,7 +105,8 @@ impl CoreCryptoContext { proteus_impl!({ self.inner.proteus_new_prekey(prekey_id).await.map_err(Into::into) }) } - /// Creates a new Proteus prekey with an automatically incremented ID and returns the CBOR-serialized version of the prekey bundle + /// Creates a new Proteus prekey with an automatically incremented ID and returns the CBOR-serialized version of the + /// prekey bundle /// /// Warning: The Proteus client **MUST** be initialized with `proteus_init` first or an error will be returned /// diff --git a/crypto-ffi/src/credential.rs b/crypto-ffi/src/credential.rs index 1f89c2dc6b..cb504b1a5d 100644 --- a/crypto-ffi/src/credential.rs +++ b/crypto-ffi/src/credential.rs @@ -10,7 +10,8 @@ use crate::{Ciphersuite, CoreCryptoResult, CredentialType, client_id::ClientIdMa /// This is tied to a particular client via either its client id or certificate bundle, /// depending on its credential type, but is independent of any client instance or storage. /// -/// To attach to a particular client instance and store, see [`CoreCryptoContext::add_credential`][crate::CoreCryptoContext::add_credential]. +/// To attach to a particular client instance and store, see +/// [`CoreCryptoContext::add_credential`][crate::CoreCryptoContext::add_credential]. #[derive(Debug, Clone, derive_more::From, derive_more::Into, uniffi::Object)] pub struct Credential(pub(crate) CryptoCredential); diff --git a/crypto-ffi/src/decrypted_message.rs b/crypto-ffi/src/decrypted_message.rs index 4745fc8716..9e82a590d7 100644 --- a/crypto-ffi/src/decrypted_message.rs +++ b/crypto-ffi/src/decrypted_message.rs @@ -18,7 +18,8 @@ pub struct DecryptedMessage { /// Commit delay in seconds. /// /// When set, clients must delay this long before processing a commit. - /// This reduces load on the backend, which otherwise would receive epoch change notifications from all clients simultaneously. + /// This reduces load on the backend, which otherwise would receive epoch change notifications from all clients + /// simultaneously. pub commit_delay: Option, /// [ClientId] of the sender of the message being decrypted. Only present for application messages. pub sender_client_id: Option, @@ -76,7 +77,8 @@ pub struct BufferedDecryptedMessage { /// Commit delay in seconds. /// /// When set, clients must delay this long before processing a commit. - /// This reduces load on the backend, which otherwise would receive epoch change notifications from all clients simultaneously. + /// This reduces load on the backend, which otherwise would receive epoch change notifications from all clients + /// simultaneously. pub commit_delay: Option, /// [ClientId] of the sender of the message being decrypted. Only present for application messages. pub sender_client_id: Option, diff --git a/crypto-ffi/src/e2ei/acme_challenge.rs b/crypto-ffi/src/e2ei/acme_challenge.rs index 35a252f2cf..949cc42a82 100644 --- a/crypto-ffi/src/e2ei/acme_challenge.rs +++ b/crypto-ffi/src/e2ei/acme_challenge.rs @@ -4,12 +4,14 @@ /// - See [core_crypto::e2e_identity::types::E2eiAcmeChallenge] #[derive(Debug, Clone, uniffi::Record)] pub struct AcmeChallenge { - /// Contains raw JSON data of this challenge. This is parsed by the underlying Rust library hence should not be accessed + /// Contains raw JSON data of this challenge. This is parsed by the underlying Rust library hence should not be + /// accessed pub delegate: Vec, /// URL of this challenge pub url: String, /// Non-standard, Wire specific claim. Indicates the consumer from where it should get the challenge proof. - /// Either from wire-server "/access-token" endpoint in case of a DPoP challenge, or from an OAuth token endpoint for an OIDC challenge + /// Either from wire-server "/access-token" endpoint in case of a DPoP challenge, or from an OAuth token endpoint + /// for an OIDC challenge pub target: String, } diff --git a/crypto-ffi/src/e2ei/mod.rs b/crypto-ffi/src/e2ei/mod.rs index e149b75a9a..ecd234a6d2 100644 --- a/crypto-ffi/src/e2ei/mod.rs +++ b/crypto-ffi/src/e2ei/mod.rs @@ -15,7 +15,8 @@ pub enum E2eiConversationState { Verified = 1, /// Some clients are either still Basic or their certificate is expired NotVerified, - /// All clients are still Basic. If all client have expired certificates, [E2eiConversationState::NotVerified] is returned. + /// All clients are still Basic. If all client have expired certificates, [E2eiConversationState::NotVerified] is + /// returned. NotEnabled, } diff --git a/crypto-ffi/src/error/mls.rs b/crypto-ffi/src/error/mls.rs index 5926d92c67..ea59d65e8c 100644 --- a/crypto-ffi/src/error/mls.rs +++ b/crypto-ffi/src/error/mls.rs @@ -33,8 +33,8 @@ pub enum MlsError { #[error("The received commit is deemed stale and is from an older epoch.")] StaleCommit, /// This happens when the DS cannot flag KeyPackages as claimed or not. In this scenario, a client - /// requests their old KeyPackages to be deleted but one has already been claimed by another client to create a Welcome. - /// In that case the only solution is that the client receiving such a Welcome tries to join the group + /// requests their old KeyPackages to be deleted but one has already been claimed by another client to create a + /// Welcome. In that case the only solution is that the client receiving such a Welcome tries to join the group /// with an External Commit instead #[error( "Although this Welcome seems valid, the local KeyPackage it references has already been deleted locally. Join this group with an external commit" diff --git a/crypto-ffi/src/identity/x509.rs b/crypto-ffi/src/identity/x509.rs index 97a9130d00..a493ca32ae 100644 --- a/crypto-ffi/src/identity/x509.rs +++ b/crypto-ffi/src/identity/x509.rs @@ -1,6 +1,7 @@ use std::time::{Duration, SystemTime}; -/// Represents the parts of [WireIdentity][crate::WireIdentity] that are specific to a X509 certificate (and not a Basic one). +/// Represents the parts of [WireIdentity][crate::WireIdentity] that are specific to a X509 certificate (and not a Basic +/// one). /// /// We don't use an enum here since the sole purpose of this is to be exposed through the FFI (and /// union types are impossible to carry over the FFI boundary) diff --git a/crypto/benches/commit.rs b/crypto/benches/commit.rs index 0554ee5dfe..39749e76fd 100644 --- a/crypto/benches/commit.rs +++ b/crypto/benches/commit.rs @@ -71,7 +71,8 @@ fn commit_add_n_clients_bench(c: &mut Criterion) { } /// Benchmark to measure the impact of group size on the runtime of creating and merging a remove commit. -/// Number of removed clients is equal to group size (→ all clients except the initial client from [setup_mls] are removed). +/// Number of removed clients is equal to group size (→ all clients except the initial client from [setup_mls] are +/// removed). fn commit_remove_bench(c: &mut Criterion) { let mut group = c.benchmark_group("Commit remove f(group size)"); for (case, ciphersuite, credential, in_memory) in MlsTestCase::values() { diff --git a/crypto/benches/utils/mls.rs b/crypto/benches/utils/mls.rs index fbe660c681..c93f26b718 100644 --- a/crypto/benches/utils/mls.rs +++ b/crypto/benches/utils/mls.rs @@ -153,7 +153,8 @@ pub async fn setup_mls( pub async fn new_central( ciphersuite: Ciphersuite, - // TODO: always None for the moment. Need to update the benches with some realistic certificates. Tracking issue: WPB-9589 + // TODO: always None for the moment. Need to update the benches with some realistic certificates. Tracking issue: + // WPB-9589 _credential: Option<&CertificateBundle>, in_memory: bool, with_basic_credential: bool, diff --git a/crypto/src/e2e_identity/enrollment/mod.rs b/crypto/src/e2e_identity/enrollment/mod.rs index 498bb23212..724bb4243c 100644 --- a/crypto/src/e2e_identity/enrollment/mod.rs +++ b/crypto/src/e2e_identity/enrollment/mod.rs @@ -183,8 +183,8 @@ impl E2eiEnrollment { /// # Parameters /// * `url` - one of the URL in new order's authorizations (from [Self::new_order_response]) /// * `account` - you got from [Self::new_account_response] - /// * `previous_nonce` - `replay-nonce` response header from `POST /acme/{provisioner-name}/new-order` - /// (or from the previous to this method if you are creating the second authorization) + /// * `previous_nonce` - `replay-nonce` response header from `POST /acme/{provisioner-name}/new-order` (or from the + /// previous to this method if you are creating the second authorization) pub fn new_authz_request(&self, url: String, previous_nonce: String) -> Result { let account = self.account.as_ref().ok_or(Error::OutOfOrderEnrollment( "You must first call 'newAccountResponse()'", @@ -220,8 +220,7 @@ impl E2eiEnrollment { /// /// # Parameters /// * `expiry_secs` - of the client Dpop JWT. This should be equal to the grace period set in Team Management - /// * `backend_nonce` - you get by calling `GET /clients/token/nonce` on wire-server. - /// See endpoint [definition](https://staging-nginz-https.zinfra.io/api/swagger-ui/#/default/get_clients__client__nonce) + /// * `backend_nonce` - you get by calling `GET /clients/token/nonce` on wire-server. See endpoint [definition](https://staging-nginz-https.zinfra.io/api/swagger-ui/#/default/get_clients__client__nonce) /// * `expiry` - token expiry #[allow(clippy::too_many_arguments)] pub fn create_dpop_token(&self, expiry_secs: u32, backend_nonce: String) -> Result { @@ -337,7 +336,8 @@ impl E2eiEnrollment { /// # Parameters /// * `order_url` - `location` header from http response you got from [Self::new_order_response] /// * `account` - you got from [Self::new_account_response] - /// * `previous_nonce` - `replay-nonce` response header from `POST /acme/{provisioner-name}/challenge/{challenge-id}` + /// * `previous_nonce` - `replay-nonce` response header from `POST + /// /acme/{provisioner-name}/challenge/{challenge-id}` pub fn check_order_request(&self, order_url: String, previous_nonce: String) -> Result { let account = self.account.as_ref().ok_or(Error::OutOfOrderEnrollment( "You must first call 'newAccountResponse()'", @@ -409,7 +409,8 @@ impl E2eiEnrollment { /// # Parameters /// * `finalize` - you got from [Self::finalize_response] /// * `account` - you got from [Self::new_account_response] - /// * `previous_nonce` - `replay-nonce` response header from `POST /acme/{provisioner-name}/order/{order-id}/finalize` + /// * `previous_nonce` - `replay-nonce` response header from `POST + /// /acme/{provisioner-name}/order/{order-id}/finalize` pub fn certificate_request(&mut self, previous_nonce: String) -> Result { let account = self.account.take().ok_or(Error::OutOfOrderEnrollment( "You must first call 'newAccountResponse()'", diff --git a/crypto/src/ephemeral.rs b/crypto/src/ephemeral.rs index 0dc4782e1c..26292316a5 100644 --- a/crypto/src/ephemeral.rs +++ b/crypto/src/ephemeral.rs @@ -118,7 +118,8 @@ pub(crate) async fn generate_history_secret(ciphersuite: Ciphersuite) -> Result< .await .map_err(MlsError::wrap("encapsulating key package"))?; - // we don't need to finish the transaction here--the point of the ephemeral CC was that no mutations would be saved there + // we don't need to finish the transaction here--the point of the ephemeral CC was that no mutations would be saved + // there Ok(HistorySecret { client_id, key_package }) } diff --git a/crypto/src/error/mod.rs b/crypto/src/error/mod.rs index a515a01d96..5f8f301a7b 100644 --- a/crypto/src/error/mod.rs +++ b/crypto/src/error/mod.rs @@ -17,7 +17,8 @@ pub type Result = core::result::Result; /// Errors produced by the root module group #[derive(Debug, thiserror::Error)] pub enum Error { - /// Invalid [crate::transaction_context::TransactionContext]. This context has been finished and can no longer be used. + /// Invalid [crate::transaction_context::TransactionContext]. This context has been finished and can no longer be + /// used. #[error("This transaction context has already been finished and can no longer be used.")] InvalidTransactionContext, /// The proteus client has been called but has not been initialized yet diff --git a/crypto/src/lib.rs b/crypto/src/lib.rs index 9a77cf5642..d0c9bbd1df 100644 --- a/crypto/src/lib.rs +++ b/crypto/src/lib.rs @@ -118,7 +118,8 @@ pub trait MlsTransport: std::fmt::Debug + Send + Sync { /// Wrapper superstruct for both [mls::session::Session] and [proteus::ProteusCentral] /// -/// As [std::ops::Deref] is implemented, this struct is automatically dereferred to [mls::session::Session] apart from `proteus_*` calls +/// As [std::ops::Deref] is implemented, this struct is automatically dereferred to [mls::session::Session] apart from +/// `proteus_*` calls /// /// This is cheap to clone as all internal members have `Arc` wrappers or are `Copy`. #[derive(Debug, Clone)] diff --git a/crypto/src/mls/conversation/commit_delay.rs b/crypto/src/mls/conversation/commit_delay.rs index 57502c6b36..637d1e52db 100644 --- a/crypto/src/mls/conversation/commit_delay.rs +++ b/crypto/src/mls/conversation/commit_delay.rs @@ -50,7 +50,8 @@ impl MlsConversation { let epoch = self.group.epoch().as_u64(); let mut own_index = self.group.own_leaf_index().u32() as u64; - // Look for members that were removed at the left of our tree in order to shift our own leaf index (post-commit tree visualization) + // Look for members that were removed at the left of our tree in order to shift our own leaf index (post-commit + // tree visualization) let left_tree_diff = self .group .members() @@ -66,7 +67,8 @@ impl MlsConversation { // Post-commit visualization of the number of members after remove proposals let nb_members = (self.group.members().count() as u64).saturating_sub(removed_index.len() as u64); - // This shifts our own leaf index to the left (tree-wise) from as many as there was removed members that have a smaller leaf index than us (older members) + // This shifts our own leaf index to the left (tree-wise) from as many as there was removed members that have a + // smaller leaf index than us (older members) own_index = own_index.saturating_sub(left_tree_diff as u64); Some(Self::calculate_delay(own_index, epoch, nb_members)) diff --git a/crypto/src/mls/conversation/config.rs b/crypto/src/mls/conversation/config.rs index c3f28a2db9..fa9a83b442 100644 --- a/crypto/src/mls/conversation/config.rs +++ b/crypto/src/mls/conversation/config.rs @@ -22,8 +22,8 @@ use crate::{Ciphersuite, MlsError, RecursiveError}; /// Sets the config in OpenMls for the oldest possible epoch(past current) that a message can be decrypted pub(crate) const MAX_PAST_EPOCHS: usize = 3; -/// Window for which decryption secrets are kept within an epoch. Use this with caution since this affects forward secrecy within an epoch. -/// Use this when the Delivery Service cannot guarantee application messages order +/// Window for which decryption secrets are kept within an epoch. Use this with caution since this affects forward +/// secrecy within an epoch. Use this when the Delivery Service cannot guarantee application messages order pub(crate) const OUT_OF_ORDER_TOLERANCE: u32 = 2; /// How many application messages can be skipped. Use this when the Delivery Service can drop application messages diff --git a/crypto/src/mls/conversation/conversation_guard/commit.rs b/crypto/src/mls/conversation/conversation_guard/commit.rs index 55265b09ef..8ef30fb479 100644 --- a/crypto/src/mls/conversation/conversation_guard/commit.rs +++ b/crypto/src/mls/conversation/conversation_guard/commit.rs @@ -115,7 +115,8 @@ impl ConversationGuard { let signer = credential.signature_key(); let mut conversation = self.conversation_mut().await; - // No need to also check pending proposals since they should already have been scanned while decrypting the proposal message + // No need to also check pending proposals since they should already have been scanned while decrypting the + // proposal message let crl_dps = extract_crl_uris_from_credentials(key_packages.iter().filter_map(|kp| { let mls_credential = kp.credential().mls_credential(); matches!(mls_credential, openmls::prelude::MlsCredentialType::X509(_)).then_some(mls_credential) diff --git a/crypto/src/mls/conversation/conversation_guard/decrypt/buffer_messages.rs b/crypto/src/mls/conversation/conversation_guard/decrypt/buffer_messages.rs index dc87ef40d2..9f667f0573 100644 --- a/crypto/src/mls/conversation/conversation_guard/decrypt/buffer_messages.rs +++ b/crypto/src/mls/conversation/conversation_guard/decrypt/buffer_messages.rs @@ -154,7 +154,8 @@ mod tests { Box::pin(async move { let conversation = case.create_conversation([&alice, &bob]).await; - // Bob creates a commit but won't merge it immediately (e.g, because his app crashes before he receives the success response from the ds) + // Bob creates a commit but won't merge it immediately (e.g, because his app crashes before he receives the + // success response from the ds) let unmerged_commit_guard = conversation.acting_as(&bob).await.update_unmerged().await; let unmerged_commit = unmerged_commit_guard.message(); diff --git a/crypto/src/mls/conversation/conversation_guard/decrypt/mod.rs b/crypto/src/mls/conversation/conversation_guard/decrypt/mod.rs index 9f8e254ccb..5dfb97b22b 100644 --- a/crypto/src/mls/conversation/conversation_guard/decrypt/mod.rs +++ b/crypto/src/mls/conversation/conversation_guard/decrypt/mod.rs @@ -48,8 +48,8 @@ use crate::{ pub struct MlsConversationDecryptMessage { /// Decrypted text message pub app_msg: Option>, - /// Only when decrypted message is a commit, CoreCrypto will renew local proposal which could not make it in the commit. - /// This will contain either: + /// Only when decrypted message is a commit, CoreCrypto will renew local proposal which could not make it in the + /// commit. This will contain either: /// * local pending proposal not in the accepted commit /// * If there is a pending commit, its proposals which are not in the accepted commit pub proposals: Vec, @@ -569,7 +569,8 @@ impl ConversationGuard { ) .await; if state != E2eiConversationState::Verified { - // FIXME: Uncomment when PKI env can be seeded - the computation is still done to assess performance and impact of the validations. Tracking issue: WPB-9665 + // FIXME: Uncomment when PKI env can be seeded - the computation is still done to assess performance and + // impact of the validations. Tracking issue: WPB-9665 // return Err(Error::InvalidCertificateChain); } } diff --git a/crypto/src/mls/conversation/conversation_guard/history_sharing.rs b/crypto/src/mls/conversation/conversation_guard/history_sharing.rs index 84a2931715..eee36b7a28 100644 --- a/crypto/src/mls/conversation/conversation_guard/history_sharing.rs +++ b/crypto/src/mls/conversation/conversation_guard/history_sharing.rs @@ -80,10 +80,10 @@ impl ConversationGuard { /// Disable history sharing by removing history clients from the conversation. pub async fn disable_history_sharing(&mut self) -> Result<()> { let mut history_client_ids = self.get_client_ids().await; - // We're facing a trade-off situation here: do we want to avoid unnecessary iteration and assume that there is always - // at most one history client in a conversation? - // Then we could use something like `into_iter().find_map()` to lazily evaluate client ids, but this way we're making sure to - // remove any history client, and not just the first one we find. + // We're facing a trade-off situation here: do we want to avoid unnecessary iteration and assume that there is + // always at most one history client in a conversation? + // Then we could use something like `into_iter().find_map()` to lazily evaluate client ids, but this way we're + // making sure to remove any history client, and not just the first one we find. history_client_ids.retain(|client_id| crate::ephemeral::is_history_client(client_id)); if history_client_ids.is_empty() { @@ -310,8 +310,8 @@ mod tests { } #[apply(all_cred_cipher)] - /// In this test, we're testing our mls library. However, our current mls fork doesn't have this test, and we require this behavior - /// for history sharing, that's why this test lives here, for now. + /// In this test, we're testing our mls library. However, our current mls fork doesn't have this test, and we + /// require this behavior for history sharing, that's why this test lives here, for now. async fn can_remove_two_and_add_one_member_in_commit(case: TestContext) { // This many members are initially in the conversation. const INITIAL_MEMBERS_COUNT: usize = 6; diff --git a/crypto/src/mls/conversation/conversation_guard/merge.rs b/crypto/src/mls/conversation/conversation_guard/merge.rs index 6ddebb8090..1093e45e29 100644 --- a/crypto/src/mls/conversation/conversation_guard/merge.rs +++ b/crypto/src/mls/conversation/conversation_guard/merge.rs @@ -28,8 +28,8 @@ impl ConversationGuard { /// /// # Arguments /// * `conversation_id` - the group/conversation id - /// * `proposal_ref` - unique proposal identifier which is present in [crate::MlsProposalBundle] - /// and returned from all operation creating a proposal + /// * `proposal_ref` - unique proposal identifier which is present in [crate::MlsProposalBundle] and returned from + /// all operation creating a proposal /// /// # Errors /// When the conversation is not found or the proposal reference does not identify a proposal diff --git a/crypto/src/mls/conversation/error.rs b/crypto/src/mls/conversation/error.rs index a74a52d8df..60a511e944 100644 --- a/crypto/src/mls/conversation/error.rs +++ b/crypto/src/mls/conversation/error.rs @@ -75,8 +75,8 @@ pub enum Error { #[error("caller error: {0}")] CallerError(&'static str), /// This happens when the DS cannot flag KeyPackages as claimed or not. In this scenario, a client - /// requests their old KeyPackages to be deleted but one has already been claimed by another client to create a Welcome. - /// In that case the only solution is that the client receiving such a Welcome tries to join the group + /// requests their old KeyPackages to be deleted but one has already been claimed by another client to create a + /// Welcome. In that case the only solution is that the client receiving such a Welcome tries to join the group /// with an External Commit instead #[error( "Although this Welcome seems valid, the local KeyPackage it references has already been deleted locally. Join this group with an external commit" diff --git a/crypto/src/mls/conversation/merge.rs b/crypto/src/mls/conversation/merge.rs index a86cc1162c..e912c3b349 100644 --- a/crypto/src/mls/conversation/merge.rs +++ b/crypto/src/mls/conversation/merge.rs @@ -9,7 +9,6 @@ //! |-------------------|----------------|----------------| //! | 0 pend. Proposal | ❌ | ✅ | //! | 1+ pend. Proposal | ❌ | ✅ | -//! use core_crypto_keystore::entities::StoredEncryptionKeyPair; use mls_crypto_provider::MlsCryptoProvider; diff --git a/crypto/src/mls/conversation/mod.rs b/crypto/src/mls/conversation/mod.rs index 3cf5870085..e34aaf4e07 100644 --- a/crypto/src/mls/conversation/mod.rs +++ b/crypto/src/mls/conversation/mod.rs @@ -67,7 +67,8 @@ use crate::{ #[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))] #[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)] pub(crate) trait ConversationWithMls<'a> { - /// [`Session`] and [`TransactionContext`][crate::transaction_context::TransactionContext] both implement [`HasSessionAndCrypto`]. + /// [`Session`] and [`TransactionContext`][crate::transaction_context::TransactionContext] both implement + /// [`HasSessionAndCrypto`]. type Context: HasSessionAndCrypto; type Conversation: Deref + Send; @@ -116,8 +117,8 @@ pub trait Conversation<'a>: ConversationWithMls<'a> { /// Derives a new key from the one in the group, to be used elsewhere. /// /// # Arguments - /// * `key_length` - the length of the key to be derived. If the value is higher than the - /// bounds of `u16` or the context hash * 255, an error will be returned + /// * `key_length` - the length of the key to be derived. If the value is higher than the bounds of `u16` or the + /// context hash * 255, an error will be returned /// /// # Errors /// OpenMls secret generation error diff --git a/crypto/src/mls/conversation/own_commit.rs b/crypto/src/mls/conversation/own_commit.rs index 47dbfc0d19..f7cb8f95b6 100644 --- a/crypto/src/mls/conversation/own_commit.rs +++ b/crypto/src/mls/conversation/own_commit.rs @@ -80,7 +80,8 @@ impl MlsConversation { } /// When the incoming commit is sent by ourselves and it's the same as the local pending commit. - /// This adapts [Self::commit_accepted] to return the same as [crate::mls::conversation::ConversationGuard::decrypt_message] + /// This adapts [Self::commit_accepted] to return the same as + /// [crate::mls::conversation::ConversationGuard::decrypt_message] pub(crate) async fn merge_pending_commit( &mut self, client: &Session, @@ -221,7 +222,8 @@ mod tests { .await } - // if there’s no pending commit & and the incoming commit originates from self: succeed by ignoring the incoming commit + // if there’s no pending commit & and the incoming commit originates from self: succeed by ignoring the incoming + // commit #[apply(all_cred_cipher)] pub async fn should_ignore_self_incoming_commit_when_no_pending_commit(case: TestContext) { if case.is_pure_ciphertext() { diff --git a/crypto/src/mls/conversation/pending_conversation.rs b/crypto/src/mls/conversation/pending_conversation.rs index c16c9523f8..eeb40506c6 100644 --- a/crypto/src/mls/conversation/pending_conversation.rs +++ b/crypto/src/mls/conversation/pending_conversation.rs @@ -118,7 +118,8 @@ impl PendingConversation { &mut self, message: impl AsRef<[u8]>, ) -> Result { - // If the confirmation tag of the pending group and this incoming message are identical, we can merge the pending group. + // If the confirmation tag of the pending group and this incoming message are identical, we can merge the + // pending group. if self.incoming_message_is_own_join_commit(message.as_ref()).await? { return self.merge_and_restore_messages().await; } diff --git a/crypto/src/mls/conversation/persistence.rs b/crypto/src/mls/conversation/persistence.rs index 532fadb629..9f7c53aac7 100644 --- a/crypto/src/mls/conversation/persistence.rs +++ b/crypto/src/mls/conversation/persistence.rs @@ -56,8 +56,9 @@ impl MlsConversation { groups .into_iter() .map(|group| { - // we can't just destructure the fields straight out of the group, because we derive `Zeroize`, which zeroizes on drop, - // which means we are forced to clone all the group's fields, because otherwise the drop impl couldn't run. + // we can't just destructure the fields straight out of the group, because we derive `Zeroize`, which + // zeroizes on drop, which means we are forced to clone all the group's fields, because + // otherwise the drop impl couldn't run. let conversation = Self::from_serialized_state(group.state.clone(), group.parent_id.clone().map(Into::into))?; Ok((group.id.clone().into(), conversation)) diff --git a/crypto/src/mls/conversation/welcome.rs b/crypto/src/mls/conversation/welcome.rs index 29258ebd07..72742b90e4 100644 --- a/crypto/src/mls/conversation/welcome.rs +++ b/crypto/src/mls/conversation/welcome.rs @@ -19,7 +19,8 @@ pub struct WelcomeBundle { } impl MlsConversation { - // ? Do we need to provide the ratchet_tree to the MlsGroup? Does everything crumble down if we can't actually get it? + // ? Do we need to provide the ratchet_tree to the MlsGroup? Does everything crumble down if we can't actually get + // it? /// Create the MLS conversation from an MLS Welcome message /// /// # Arguments diff --git a/crypto/src/mls/credential/credential_ref/persistence.rs b/crypto/src/mls/credential/credential_ref/persistence.rs index 132f0f65dc..98ec607347 100644 --- a/crypto/src/mls/credential/credential_ref/persistence.rs +++ b/crypto/src/mls/credential/credential_ref/persistence.rs @@ -32,8 +32,8 @@ impl CredentialRef { /// /// Note that this does not attach the credential to any Session; it just does the data manipulation. /// - /// The database schema currently permits multiple credentials to exist simultaneously which match a given credential ref. - /// Therefore, this function returns all of them, ordered by `earliest_validity`. + /// The database schema currently permits multiple credentials to exist simultaneously which match a given + /// credential ref. Therefore, this function returns all of them, ordered by `earliest_validity`. /// /// Due to database limitations we currently cannot efficiently retrieve only those keypairs of interest; /// if you are going to be loading several references in a row, it is more efficient to first fetch all diff --git a/crypto/src/mls/credential/persistence.rs b/crypto/src/mls/credential/persistence.rs index 4e37618aff..6fad40fdad 100644 --- a/crypto/src/mls/credential/persistence.rs +++ b/crypto/src/mls/credential/persistence.rs @@ -8,7 +8,8 @@ use crate::{Credential, CredentialRef, KeystoreError}; impl Credential { /// Update all the fields that were updated by the DB during the save. /// - /// [`::pre_save`][core_crypto_keystore::entities::EntityTransactionExt::pre_save]. + /// [`::pre_save`][core_crypto_keystore::entities::EntityTransactionExt::pre_save]. fn update_from(&mut self, stored: StoredCredential) { self.earliest_validity = stored.created_at; } diff --git a/crypto/src/mls/session/credential.rs b/crypto/src/mls/session/credential.rs index 7c2b8755a6..73a7bedf64 100644 --- a/crypto/src/mls/session/credential.rs +++ b/crypto/src/mls/session/credential.rs @@ -51,7 +51,8 @@ impl Session { self.add_credential_without_clientid_check(credential).await } - /// Add a credential to the identities of this session without validating that its client ID matches the session client id. + /// Add a credential to the identities of this session without validating that its client ID matches the session + /// client id. /// /// This is rarely useful and should only be used when absolutely necessary. You'll know it if you need it. /// @@ -68,7 +69,8 @@ impl Session { let guard = self.inner.upgradable_read().await; let inner = guard.as_ref().ok_or(Error::MlsNotInitialized)?; - // failfast before loading the cache if we know already that this credential ref can't be added to the identity set + // failfast before loading the cache if we know already that this credential ref can't be added to the identity + // set let distinct_result = inner.identities.ensure_distinct( credential_ref.signature_scheme(), credential_ref.r#type(), diff --git a/crypto/src/mls/session/error.rs b/crypto/src/mls/session/error.rs index 011c87a67c..78727f2e95 100644 --- a/crypto/src/mls/session/error.rs +++ b/crypto/src/mls/session/error.rs @@ -23,7 +23,8 @@ pub enum Error { CredentialNotFound(crate::CredentialType, SignatureScheme), #[error("supplied signature scheme was not valid")] InvalidSignatureScheme, - /// The keystore has no knowledge of such client; this shouldn't happen as Client::init is failsafe (find-else-create) + /// The keystore has no knowledge of such client; this shouldn't happen as Client::init is failsafe + /// (find-else-create) #[error("The provided client signature has not been found in the keystore")] ClientSignatureNotFound, /// Client was unexpectedly ready. diff --git a/crypto/src/mls/session/identities.rs b/crypto/src/mls/session/identities.rs index 2438fa997f..7aa6b78cbe 100644 --- a/crypto/src/mls/session/identities.rs +++ b/crypto/src/mls/session/identities.rs @@ -14,8 +14,8 @@ use crate::{ /// We use this data structure to make that easy. The outer map filters by signature scheme. The inner set lets us /// quickly find the most recent. /// -/// This depends on the fact that in `Credential`'s `Ord` impl, the first comparison is by the credential's `earliest_validity`. -/// However, by structuring things like this, we do not need to care about insertion order. +/// This depends on the fact that in `Credential`'s `Ord` impl, the first comparison is by the credential's +/// `earliest_validity`. However, by structuring things like this, we do not need to care about insertion order. /// /// We keep each credential inside an arc to avoid cloning them, as X509 credentials can get quite large. #[derive(Debug, Clone)] @@ -150,8 +150,9 @@ impl Identities { "can't binary search if credentials are not sorted by validity" ); // if binary search returns ok, it was not distinct by earliest validity, therefore we have a conflict - // normally we expect that the new credential has the most recent earliest_validity therefore adding the credential is - // as cheap as pushing to the end of the vector, but just in case of random insertion order, do the right thing + // normally we expect that the new credential has the most recent earliest_validity therefore adding the + // credential is as cheap as pushing to the end of the vector, but just in case of random insertion + // order, do the right thing let Err(insertion_point) = credentials.binary_search_by_key(&credential.earliest_validity, |credential| credential.earliest_validity) else { diff --git a/crypto/src/mls/session/key_package.rs b/crypto/src/mls/session/key_package.rs index 954c4efe5c..86a24632c4 100644 --- a/crypto/src/mls/session/key_package.rs +++ b/crypto/src/mls/session/key_package.rs @@ -180,8 +180,9 @@ impl Session { /// Prune the provided KeyPackageRefs from the keystore /// /// Warning: Despite this API being public, the caller should know what they're doing. - /// Provided KeypackageRefs **will** be purged regardless of their expiration state, so please be wary of what you are doing if you directly call this API. - /// This could result in still valid, uploaded keypackages being pruned from the system and thus being impossible to find when referenced in a future Welcome message. + /// Provided KeypackageRefs **will** be purged regardless of their expiration state, so please be wary of what you + /// are doing if you directly call this API. This could result in still valid, uploaded keypackages being pruned + /// from the system and thus being impossible to find when referenced in a future Welcome message. pub async fn prune_keypackages( &self, backend: &MlsCryptoProvider, @@ -460,7 +461,8 @@ mod tests { assert_eq!(init.credential, 1); // since 'delete_keypackages' will evict all Credentials unlinked to a KeyPackage, each iteration - // generates 1 extra KeyPackage in order for this Credential no to be evicted and next iteration sto succeed. + // generates 1 extra KeyPackage in order for this Credential no to be evicted and next iteration sto + // succeed. let transactional_provider = cc.transaction.mls_provider().await.unwrap(); let crypto_provider = transactional_provider.crypto(); let mut pinned_kp = None; @@ -550,7 +552,8 @@ mod tests { .await .unwrap(); - // Generate `UNEXPIRED_COUNT` kpbs that are with default 3 months expiration. We *should* keep them for the duration of the test + // Generate `UNEXPIRED_COUNT` kpbs that are with default 3 months expiration. We *should* keep them for the + // duration of the test let unexpired_kpbs = session .request_key_packages(UNEXPIRED_COUNT, case.ciphersuite(), case.credential_type, &backend) .await diff --git a/crypto/src/proteus.rs b/crypto/src/proteus.rs index 5ac2799449..2877154bf7 100644 --- a/crypto/src/proteus.rs +++ b/crypto/src/proteus.rs @@ -167,7 +167,8 @@ impl CoreCrypto { /// Proteus counterpart of [crate::mls::session::Session] /// /// The big difference is that [ProteusCentral] doesn't *own* its own keystore but must borrow it from the outside. -/// Whether it's exclusively for this struct's purposes or it's shared with our main struct, [crate::mls::session::Session] +/// Whether it's exclusively for this struct's purposes or it's shared with our main struct, +/// [crate::mls::session::Session] #[derive(Debug)] pub struct ProteusCentral { proteus_identity: Arc, @@ -193,7 +194,8 @@ impl ProteusCentral { } /// This function will try to load a proteus Identity from our keystore; If it cannot, it will create a new one - /// This means this function doesn't fail except in cases of deeper errors (such as in the Keystore and other crypto errors) + /// This means this function doesn't fail except in cases of deeper errors (such as in the Keystore and other crypto + /// errors) async fn load_or_create_identity(keystore: &CryptoKeystore) -> Result { let Some(identity) = keystore .find::(ProteusIdentity::ID) @@ -280,15 +282,14 @@ impl ProteusCentral { // // We can derive two general rules about error-handling in Rust from this example: // - // 1. It's better to make smaller error types where possible, encapsulating fallible operations - // with their own error variants, and then wrapping those errors where required, as opposed to - // creating giant catch-all errors. Doing so also has knock-on benefits with regard to tracing - // the precise origin of the error. - // 2. One should never make an error wrapper parametric. If you need to wrap an unknown error, - // it's always better to wrap a `Box` than to make your error type parametric. - // The allocation cost of creating the `Box` is utterly trivial in an error-handling path, and - // it avoids parametric virality. (`init_from_prekey` is itself only generic because it returns - // this error type with a type-parametric variant, which the function never returns.) + // 1. It's better to make smaller error types where possible, encapsulating fallible operations with their own + // error variants, and then wrapping those errors where required, as opposed to creating giant catch-all + // errors. Doing so also has knock-on benefits with regard to tracing the precise origin of the error. + // 2. One should never make an error wrapper parametric. If you need to wrap an unknown error, it's always + // better to wrap a `Box` than to make your error type parametric. The allocation cost + // of creating the `Box` is utterly trivial in an error-handling path, and it avoids parametric virality. + // (`init_from_prekey` is itself only generic because it returns this error type with a type-parametric + // variant, which the function never returns.) // // In this case, we have the out of band knowledge that `ProteusErrorKind` has a `#[from]` implementation // for `proteus_wasm::session::Error` and for no other kinds @@ -345,7 +346,8 @@ impl ProteusCentral { /// Persists a session in store /// - /// **Note**: This isn't usually needed as persisting sessions happens automatically when decrypting/encrypting messages and initializing Sessions + /// **Note**: This isn't usually needed as persisting sessions happens automatically when decrypting/encrypting + /// messages and initializing Sessions pub(crate) async fn session_save(&mut self, keystore: &CryptoKeystore, session_id: &str) -> Result<()> { if let Some(session) = self .proteus_sessions @@ -462,7 +464,8 @@ impl ProteusCentral { Ok(acc) } - /// Generates a new Proteus PreKey, stores it in the keystore and returns a serialized PreKeyBundle to be consumed externally + /// Generates a new Proteus PreKey, stores it in the keystore and returns a serialized PreKeyBundle to be consumed + /// externally pub(crate) async fn new_prekey(&self, id: u16, keystore: &CryptoKeystore) -> Result> { use proteus_wasm::keys::{PreKey, PreKeyId}; diff --git a/crypto/src/test_utils/context.rs b/crypto/src/test_utils/context.rs index c0ce157ef5..817c462a83 100644 --- a/crypto/src/test_utils/context.rs +++ b/crypto/src/test_utils/context.rs @@ -143,8 +143,8 @@ impl SessionContext { }; // in the x509 case, `CertificateBundle::rand` just completely invents a new client id in the format that e2ei - // apparently prefers. We still need to add that credential even so, because this test util code is (meant to be) part of setup, - // not part of the code under test. + // apparently prefers. We still need to add that credential even so, because this test util code is (meant to + // be) part of setup, not part of the code under test. self.session .add_credential_without_clientid_check(credential) .await diff --git a/crypto/src/test_utils/test_conversation/commit.rs b/crypto/src/test_utils/test_conversation/commit.rs index 89cc1168f4..92fa51ee64 100644 --- a/crypto/src/test_utils/test_conversation/commit.rs +++ b/crypto/src/test_utils/test_conversation/commit.rs @@ -117,7 +117,8 @@ impl<'a> TestConversation<'a> { OperationGuard::new(TestOperation::Update, commit, self, []) } - /// Like [Self::e2ei_rotate_notify], but also when notifying other members, call [SessionContext::verify_sender_identity]. + /// Like [Self::e2ei_rotate_notify], but also when notifying other members, call + /// [SessionContext::verify_sender_identity]. pub async fn e2ei_rotate_notify_and_verify_sender(self, credential: Option<&Credential>) -> TestConversation<'a> { self.e2ei_rotate(credential) .await @@ -249,7 +250,8 @@ impl<'a> TestConversation<'a> { ) } - /// Like [Self::external_join_notify], but with "unmerged" state on the joiners session. To merge, call [PendingConversation::merge]. + /// Like [Self::external_join_notify], but with "unmerged" state on the joiners session. To merge, call + /// [PendingConversation::merge]. pub async fn external_join_unmerged_notify( self, joiner: &'a SessionContext, @@ -259,7 +261,8 @@ impl<'a> TestConversation<'a> { (commit_guard.notify_members().await, pending_conversation) } - /// Like [Self::external_join], but with "unmerged" state on the joiners session. To merge, call [PendingConversation::merge]. + /// Like [Self::external_join], but with "unmerged" state on the joiners session. To merge, call + /// [PendingConversation::merge]. pub async fn external_join_unmerged( self, joiner: &'a SessionContext, diff --git a/crypto/src/test_utils/test_conversation/mod.rs b/crypto/src/test_utils/test_conversation/mod.rs index 15e9dc6189..862fb5231e 100644 --- a/crypto/src/test_utils/test_conversation/mod.rs +++ b/crypto/src/test_utils/test_conversation/mod.rs @@ -57,7 +57,8 @@ impl<'a> TestConversation<'a> { } } - /// Use this if you have created a conversation before and want to create a `TestConversation` instance of that conversation. + /// Use this if you have created a conversation before and want to create a `TestConversation` instance of that + /// conversation. pub async fn new_from_existing( case: &'a TestContext, id: ConversationId, diff --git a/crypto/src/test_utils/test_conversation/proposal.rs b/crypto/src/test_utils/test_conversation/proposal.rs index f6d8466b20..0d85955ef0 100644 --- a/crypto/src/test_utils/test_conversation/proposal.rs +++ b/crypto/src/test_utils/test_conversation/proposal.rs @@ -99,7 +99,8 @@ impl<'a> TestConversation<'a> { ) } - /// Like [Self::remove_proposal_notify], but by an external actor, the so-called external sender. We're using the sender index 0. + /// Like [Self::remove_proposal_notify], but by an external actor, the so-called external sender. We're using the + /// sender index 0. pub async fn external_remove_proposal_notify( self, external_actor: &'a SessionContext, @@ -111,7 +112,8 @@ impl<'a> TestConversation<'a> { .await } - /// Like [Self::remove_proposal], but by an external actor, the so-called external sender. We're using the sender index 0. + /// Like [Self::remove_proposal], but by an external actor, the so-called external sender. We're using the sender + /// index 0. pub async fn external_remove_proposal( self, external_actor: &'a SessionContext, diff --git a/crypto/src/test_utils/x509.rs b/crypto/src/test_utils/x509.rs index eda3403e26..db7b106297 100644 --- a/crypto/src/test_utils/x509.rs +++ b/crypto/src/test_utils/x509.rs @@ -22,7 +22,8 @@ pub struct CertificateParams { pub cert_keypair: Option, /// When the certificate becomes valid - UNIX timestamp pub validity_start: Option, - /// Expiration of the certificate; It is relative to either now (when `validity_start` is not provided) or `validity_start` + /// Expiration of the certificate; It is relative to either now (when `validity_start` is not provided) or + /// `validity_start` pub expiration: Duration, } diff --git a/crypto/src/transaction_context/conversation/external_commit.rs b/crypto/src/transaction_context/conversation/external_commit.rs index e8455a7e4c..723794a602 100644 --- a/crypto/src/transaction_context/conversation/external_commit.rs +++ b/crypto/src/transaction_context/conversation/external_commit.rs @@ -25,12 +25,13 @@ impl TransactionContext { /// calling [Self::join_by_external_commit] again. /// /// # Arguments - /// * `group_info` - a GroupInfo wrapped in a MLS message. it can be obtained by deserializing a TLS serialized `GroupInfo` object + /// * `group_info` - a GroupInfo wrapped in a MLS message. it can be obtained by deserializing a TLS serialized + /// `GroupInfo` object /// * `custom_cfg` - configuration of the MLS conversation fetched from the Delivery Service - /// * `credential_type` - kind of [openmls::prelude::Credential] to use for joining this group. - /// If [CredentialType::Basic] is chosen and no Credential has been created yet for it, - /// a new one will be generated. When [CredentialType::X509] is chosen, it fails when no - /// [openmls::prelude::Credential] has been created for the given Ciphersuite. + /// * `credential_type` - kind of [openmls::prelude::Credential] to use for joining this group. If + /// [CredentialType::Basic] is chosen and no Credential has been created yet for it, a new one will be generated. + /// When [CredentialType::X509] is chosen, it fails when no [openmls::prelude::Credential] has been created for + /// the given Ciphersuite. /// /// # Returns [WelcomeBundle] /// diff --git a/crypto/src/transaction_context/conversation/external_proposal.rs b/crypto/src/transaction_context/conversation/external_proposal.rs index cc9d1c0fdd..3d8796bc75 100644 --- a/crypto/src/transaction_context/conversation/external_proposal.rs +++ b/crypto/src/transaction_context/conversation/external_proposal.rs @@ -214,8 +214,8 @@ mod tests { // Charlie joins through a Welcome and should get external_senders from Welcome // message and not from configuration - // charlie can only get it from there, because the `MlsCustomgConfiguration` that they receive when processing - // the welcome, doesn't contain any info about an external sender. + // charlie can only get it from there, because the `MlsCustomgConfiguration` that they receive when + // processing the welcome, doesn't contain any info about an external sender. let conversation = conversation.invite_notify([&charlie]).await; assert_eq!(conversation.member_count().await, 3); assert!(conversation.is_functional_and_contains([&alice, &bob, &charlie]).await); diff --git a/crypto/src/transaction_context/conversation/mod.rs b/crypto/src/transaction_context/conversation/mod.rs index 542b2cdf6f..b34355a8e5 100644 --- a/crypto/src/transaction_context/conversation/mod.rs +++ b/crypto/src/transaction_context/conversation/mod.rs @@ -51,8 +51,7 @@ impl TransactionContext { /// Create a new empty conversation /// /// # Arguments - /// * `id` - identifier of the group/conversation (must be unique otherwise the existing group - /// will be overridden) + /// * `id` - identifier of the group/conversation (must be unique otherwise the existing group will be overridden) /// * `creator_credential_type` - kind of credential the creator wants to create the group with /// * `config` - configuration of the group/conversation /// diff --git a/crypto/src/transaction_context/conversation/proposal.rs b/crypto/src/transaction_context/conversation/proposal.rs index 208e04edef..37d2e60655 100644 --- a/crypto/src/transaction_context/conversation/proposal.rs +++ b/crypto/src/transaction_context/conversation/proposal.rs @@ -31,7 +31,8 @@ impl TransactionContext { /// * `proposal` - the proposal do be added in the group /// /// # Return type - /// A [MlsProposalBundle] with the proposal in a Mls message and a reference to that proposal in order to rollback it if required + /// A [MlsProposalBundle] with the proposal in a Mls message and a reference to that proposal in order to rollback + /// it if required /// /// # Errors /// If the conversation is not found, an error will be returned. Errors from OpenMls can be diff --git a/crypto/src/transaction_context/conversation/welcome.rs b/crypto/src/transaction_context/conversation/welcome.rs index 027dda358b..e4ce52ba7e 100644 --- a/crypto/src/transaction_context/conversation/welcome.rs +++ b/crypto/src/transaction_context/conversation/welcome.rs @@ -12,7 +12,8 @@ use crate::{ }; impl TransactionContext { - /// Create a conversation from a TLS serialized MLS Welcome message. The `MlsConversationConfiguration` used in this function will be the default implementation. + /// Create a conversation from a TLS serialized MLS Welcome message. The `MlsConversationConfiguration` used in this + /// function will be the default implementation. /// /// # Arguments /// * `welcome` - a TLS serialized welcome message @@ -115,7 +116,8 @@ mod tests { // Bob accepts the welcome message, and as such, it should prune the used keypackage from the store commit_guard.notify_members().await; - // Ensure we're left with 1 less keypackage bundle in the store, because it was consumed with the OpenMLS Welcome message + // Ensure we're left with 1 less keypackage bundle in the store, because it was consumed with the OpenMLS + // Welcome message let next_count = bob.transaction.count_entities().await; assert_eq!(next_count.key_package, prev_count.key_package - 1); assert_eq!(next_count.hpke_private_key, prev_count.hpke_private_key - 1); diff --git a/crypto/src/transaction_context/e2e_identity/conversation_state.rs b/crypto/src/transaction_context/e2e_identity/conversation_state.rs index 38d801d6f5..ee53864b49 100644 --- a/crypto/src/transaction_context/e2e_identity/conversation_state.rs +++ b/crypto/src/transaction_context/e2e_identity/conversation_state.rs @@ -15,7 +15,8 @@ pub enum E2eiConversationState { Verified = 1, /// Some clients are either still Basic or their certificate is expired NotVerified, - /// All clients are still Basic. If all client have expired certificates, [E2eiConversationState::NotVerified] is returned. + /// All clients are still Basic. If all client have expired certificates, [E2eiConversationState::NotVerified] is + /// returned. NotEnabled, } diff --git a/crypto/src/transaction_context/e2e_identity/mod.rs b/crypto/src/transaction_context/e2e_identity/mod.rs index f4bab17d2f..f150115f5f 100644 --- a/crypto/src/transaction_context/e2e_identity/mod.rs +++ b/crypto/src/transaction_context/e2e_identity/mod.rs @@ -116,12 +116,13 @@ impl TransactionContext { Ok(crl_new_distribution_points) } - /// When x509 new credentials are registered this extracts the new CRL Distribution Point from the end entity certificate - /// and all the intermediates + /// When x509 new credentials are registered this extracts the new CRL Distribution Point from the end entity + /// certificate and all the intermediates async fn extract_dp_on_init(&self, certificate_chain: &[Vec]) -> Result { use x509_cert::der::Decode as _; - // Own intermediates are not provided by smallstep in the /federation endpoint so we got to intercept them here, at issuance + // Own intermediates are not provided by smallstep in the /federation endpoint so we got to intercept them here, + // at issuance let size = certificate_chain.len(); let mut crl_new_distribution_points = HashSet::new(); if size > 1 { diff --git a/crypto/src/transaction_context/e2e_identity/rotate.rs b/crypto/src/transaction_context/e2e_identity/rotate.rs index da65f88cd2..830809acaf 100644 --- a/crypto/src/transaction_context/e2e_identity/rotate.rs +++ b/crypto/src/transaction_context/e2e_identity/rotate.rs @@ -64,7 +64,8 @@ impl TransactionContext { /// having to change/rotate their credential, either because the former one is expired or it /// has been revoked. As a consequence, this method does not support changing neither ClientId which /// should remain the same as the previous one. It lets you change the DisplayName or the handle - /// if you need to. Once the enrollment is finished, use the instance in [TransactionContext::save_x509_credential] to do the rotation. + /// if you need to. Once the enrollment is finished, use the instance in [TransactionContext::save_x509_credential] + /// to do the rotation. pub async fn e2ei_new_rotate_enrollment( &self, display_name: Option, @@ -110,7 +111,8 @@ impl TransactionContext { &mls_provider, ciphersuite, sign_keypair, - true, // Since we are renewing an e2ei certificate we MUST have already generated one hence we MUST already have done an OIDC authn and gotten a refresh token from it + true, /* Since we are renewing an e2ei certificate we MUST have already generated one hence we MUST + * already have done an OIDC authn and gotten a refresh token from it */ ) .map_err(RecursiveError::e2e_identity("creating new enrollment")) .map_err(Into::into) @@ -125,8 +127,7 @@ impl TransactionContext { /// 2. Generate new key packages with [crate::mls::session::Session::request_key_packages] /// 3. Use these to replace the stale ones the in the backend /// 4. Delete the stale ones locally using [Self::delete_stale_key_packages] - /// * This is the last step because you might still need the old key packages to avoid - /// an orphan welcome message + /// * This is the last step because you might still need the old key packages to avoid an orphan welcome message pub async fn save_x509_credential( &self, enrollment: &mut E2eiEnrollment, @@ -816,11 +817,12 @@ mod tests { let final_count = alice.transaction.count_entities().await; assert_eq!(init_count.encryption_keypair, final_count.encryption_keypair); - // TODO: there is no efficient way to clean a credential when alice merges her pending commit. Tracking issue: WPB-9594 - // One option would be to fetch all conversations and see if Alice is never represented with the said Credential - // but let's be honest this is not very efficient. - // The other option would be to get rid of having an implicit KeyPackage for the creator of a conversation - // assert_eq!(init_count.credential, final_count.credential); + // TODO: there is no efficient way to clean a credential when alice merges her pending commit. Tracking + // issue: WPB-9594 One option would be to fetch all conversations and see if Alice is + // never represented with the said Credential but let's be honest this is not very + // efficient. The other option would be to get rid of having an implicit KeyPackage for + // the creator of a conversation assert_eq!(init_count.credential, + // final_count.credential); }) .await } diff --git a/crypto/src/transaction_context/key_package.rs b/crypto/src/transaction_context/key_package.rs index 081fa76837..284d5f680b 100644 --- a/crypto/src/transaction_context/key_package.rs +++ b/crypto/src/transaction_context/key_package.rs @@ -38,7 +38,8 @@ impl TransactionContext { .map_err(Into::into) } - /// Returns the count of valid, non-expired, unclaimed keypackages in store for the given [Ciphersuite] and [CredentialType] + /// Returns the count of valid, non-expired, unclaimed keypackages in store for the given [Ciphersuite] and + /// [CredentialType] pub async fn client_valid_key_packages_count( &self, ciphersuite: Ciphersuite, diff --git a/crypto/src/transaction_context/proteus.rs b/crypto/src/transaction_context/proteus.rs index 4cedeac5f4..77a7b7b2a6 100644 --- a/crypto/src/transaction_context/proteus.rs +++ b/crypto/src/transaction_context/proteus.rs @@ -29,7 +29,8 @@ impl TransactionContext { /// Reloads the sessions from the key store /// - /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or it will do nothing + /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or it will do + /// nothing pub async fn proteus_reload_sessions(&self) -> Result<()> { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -44,7 +45,8 @@ impl TransactionContext { /// Creates a proteus session from a prekey /// - /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error + /// will be returned pub async fn proteus_session_from_prekey( &self, session_id: &str, @@ -67,7 +69,8 @@ impl TransactionContext { /// Creates a proteus session from a Proteus message envelope /// - /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error + /// will be returned pub async fn proteus_session_from_message( &self, session_id: &str, @@ -90,7 +93,8 @@ impl TransactionContext { /// Saves a proteus session in the keystore /// - /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error + /// will be returned pub async fn proteus_session_save(&self, session_id: &str) -> Result<()> { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -105,7 +109,8 @@ impl TransactionContext { /// Deletes a proteus session from the keystore /// - /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error + /// will be returned pub async fn proteus_session_delete(&self, session_id: &str) -> Result<()> { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -120,7 +125,8 @@ impl TransactionContext { /// Proteus session accessor /// - /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error + /// will be returned pub async fn proteus_session( &self, session_id: &str, @@ -138,7 +144,8 @@ impl TransactionContext { /// Proteus session exists /// - /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error + /// will be returned pub async fn proteus_session_exists(&self, session_id: &str) -> Result { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -149,7 +156,8 @@ impl TransactionContext { /// Decrypts a proteus message envelope /// - /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error + /// will be returned pub async fn proteus_decrypt(&self, session_id: &str, ciphertext: &[u8]) -> Result> { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -164,7 +172,8 @@ impl TransactionContext { /// Encrypts proteus message for a given session ID /// - /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error + /// will be returned pub async fn proteus_encrypt(&self, session_id: &str, plaintext: &[u8]) -> Result> { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -177,10 +186,11 @@ impl TransactionContext { .map_err(Into::into) } - /// Encrypts a proteus message for several sessions ID. This is more efficient than other methods as the calls are batched. - /// This also reduces the rountrips when crossing over the FFI + /// Encrypts a proteus message for several sessions ID. This is more efficient than other methods as the calls are + /// batched. This also reduces the rountrips when crossing over the FFI /// - /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error + /// will be returned pub async fn proteus_encrypt_batched( &self, sessions: &[impl AsRef], @@ -199,7 +209,8 @@ impl TransactionContext { /// Creates a new Proteus prekey and returns the CBOR-serialized version of the prekey bundle /// - /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error + /// will be returned pub async fn proteus_new_prekey(&self, prekey_id: u16) -> Result> { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -212,9 +223,11 @@ impl TransactionContext { .map_err(Into::into) } - /// Creates a new Proteus prekey with an automatically incremented ID and returns the CBOR-serialized version of the prekey bundle + /// Creates a new Proteus prekey with an automatically incremented ID and returns the CBOR-serialized version of the + /// prekey bundle /// - /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error + /// will be returned pub async fn proteus_new_prekey_auto(&self) -> Result<(u16, Vec)> { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -248,7 +261,8 @@ impl TransactionContext { /// Returns the proteus identity's public key fingerprint /// - /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error + /// will be returned pub async fn proteus_fingerprint(&self) -> Result { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -258,7 +272,8 @@ impl TransactionContext { /// Returns the proteus identity's public key fingerprint /// - /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error + /// will be returned pub async fn proteus_fingerprint_local(&self, session_id: &str) -> Result { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -273,7 +288,8 @@ impl TransactionContext { /// Returns the proteus identity's public key fingerprint /// - /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [TransactionContext::proteus_init] first or an error + /// will be returned pub async fn proteus_fingerprint_remote(&self, session_id: &str) -> Result { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; diff --git a/keystore/src/connection/mod.rs b/keystore/src/connection/mod.rs index 7c2408de0c..d3c5417b0d 100644 --- a/keystore/src/connection/mod.rs +++ b/keystore/src/connection/mod.rs @@ -32,7 +32,8 @@ use crate::{ /// Limit on the length of a blob to be stored in the database. /// /// This limit applies to both SQLCipher-backed stores and WASM. -/// This limit is conservative on purpose when targeting WASM, as the lower bound that exists is Safari with a limit of 1GB per origin. +/// This limit is conservative on purpose when targeting WASM, as the lower bound that exists is Safari with a limit of +/// 1GB per origin. /// /// See: [SQLite limits](https://www.sqlite.org/limits.html) /// See: [IndexedDB limits](https://stackoverflow.com/a/63019999/1934177) @@ -42,7 +43,8 @@ pub const MAX_BLOB_LEN: usize = 1_000_000_000; // ? Because of UniFFI async requirements, we need our keystore to be Send as well now pub trait DatabaseConnectionRequirements: Sized + Send {} #[cfg(target_family = "wasm")] -// ? On the other hand, things cannot be Send on WASM because of platform restrictions (all things are copied across the FFI) +// ? On the other hand, things cannot be Send on WASM because of platform restrictions (all things are copied across the +// FFI) pub trait DatabaseConnectionRequirements: Sized {} /// The key used to encrypt the database. diff --git a/keystore/src/connection/platform/generic/meta_migrations/v16.rs b/keystore/src/connection/platform/generic/meta_migrations/v16.rs index 872cbf1b8f..026b77c2e2 100644 --- a/keystore/src/connection/platform/generic/meta_migrations/v16.rs +++ b/keystore/src/connection/platform/generic/meta_migrations/v16.rs @@ -43,7 +43,8 @@ pub(crate) fn meta_migration(conn: &mut rusqlite::Connection) -> CryptoKeystoreR credential_id: row.get("credential_id")?, }; - // Insert the new credential into temporary mls_credentials_new table, that will be renamed in the next migration + // Insert the new credential into temporary mls_credentials_new table, that will be renamed in the next + // migration if let Some(c) = migrate_to_new_credential(&v5, &kp)? { tx.execute( "INSERT INTO mls_credentials_new ( diff --git a/keystore/src/entities/mls.rs b/keystore/src/entities/mls.rs index 68974ce442..0a7ab5917e 100644 --- a/keystore/src/entities/mls.rs +++ b/keystore/src/entities/mls.rs @@ -418,7 +418,8 @@ pub struct E2eiAcmeCA { )] #[zeroize(drop)] pub struct E2eiIntermediateCert { - // key to identify the CA cert; Using a combination of SKI & AKI extensions concatenated like so is suitable: `SKI[+AKI]` + // key to identify the CA cert; Using a combination of SKI & AKI extensions concatenated like so is suitable: + // `SKI[+AKI]` #[id] pub ski_aki_pair: String, pub content: Vec, diff --git a/keystore/src/entities/platform/generic/mls/credential.rs b/keystore/src/entities/platform/generic/mls/credential.rs index 00726e6c30..28e55cee71 100644 --- a/keystore/src/entities/platform/generic/mls/credential.rs +++ b/keystore/src/entities/platform/generic/mls/credential.rs @@ -208,7 +208,8 @@ impl MlsCredentialExt for StoredCredential { transaction: &TransactionWrapper<'_>, credential: Vec, ) -> CryptoKeystoreResult<()> { - // we do not have an index on this since we'll never have more than a handful of credentials in the sotre (~40 max) + // we do not have an index on this since we'll never have more than a handful of credentials in the sotre (~40 + // max) transaction.execute("DELETE FROM mls_credentials WHERE credential = ?", [&credential[..]])?; Ok(()) } diff --git a/keystore/src/transaction/mod.rs b/keystore/src/transaction/mod.rs index 60d9789e43..e35f2333dc 100644 --- a/keystore/src/transaction/mod.rs +++ b/keystore/src/transaction/mod.rs @@ -252,7 +252,8 @@ impl KeystoreTransaction { /// Build a single list of unique records from two potentially overlapping lists. /// In case of overlap, records in `records_a` are prioritized. - /// Identity from the perspective of this function is determined by the output of [crate::entities::Entity::merge_key]. + /// Identity from the perspective of this function is determined by the output of + /// [crate::entities::Entity::merge_key]. /// /// Further, the output list of records is built with respect to the provided [EntityFindParams] /// and the deleted records cached in this [Self] instance. @@ -331,7 +332,7 @@ impl KeystoreTransaction { /// (identifier_05, ProteusSession) /// ] /// ); -///``` +/// ``` macro_rules! commit_transaction { ($keystore_transaction:expr_2021, $db:expr_2021, [ $( ($records:ident, $entity:ty) ),*], proteus_types: [ $( ($conditional_records:ident, $conditional_entity:ty) ),*]) => { #[cfg(feature = "proteus-keystore")] diff --git a/mls-provider/src/pki.rs b/mls-provider/src/pki.rs index de785218ec..3d8c5ffc17 100644 --- a/mls-provider/src/pki.rs +++ b/mls-provider/src/pki.rs @@ -80,8 +80,9 @@ impl openmls_traits::authentication_service::AuthenticationServiceDelegate for P let binding = self.0.read().await; let Some(pki_env) = binding.as_ref() else { - // This implies that we have a Basic client without a PKI environment setup. Hence they cannot validate X509 credentials they see. - // So we consider it as always valid as we have no way to assert the validity + // This implies that we have a Basic client without a PKI environment setup. Hence they cannot + // validate X509 credentials they see. So we consider it as always valid as we + // have no way to assert the validity return CredentialAuthenticationStatus::Valid; };