From 00855d7eaed4683b11129dd69cea7ad997813d16 Mon Sep 17 00:00:00 2001 From: Ionut Mihalcea Date: Fri, 17 Jul 2020 11:02:26 +0100 Subject: [PATCH] Fix clippy errors This commit fixes clippy warnings in the new version of the Rust compiler (1.45.0). Most of the errors refer to misuse of `or_else`, where an error is mapped exclusively to another error. `map_err` should be used instead. The other warnings are around useless type conversions between identical types. Signed-off-by: Ionut Mihalcea --- .../normal_tests/asym_encryption.rs | 10 +++--- src/bin/main.rs | 12 +++---- src/key_info_managers/on_disk_manager/mod.rs | 8 ++--- src/providers/core_provider/mod.rs | 10 +++--- src/providers/mbed_provider/key_management.rs | 2 +- .../pkcs11_provider/key_management.rs | 6 ++-- src/providers/pkcs11_provider/mod.rs | 13 +++---- src/providers/tpm_provider/asym_sign.rs | 4 +-- src/providers/tpm_provider/key_management.rs | 18 +++++----- src/providers/tpm_provider/mod.rs | 35 ++++++------------- src/providers/tpm_provider/utils.rs | 7 ++-- src/utils/service_builder.rs | 9 ++--- 12 files changed, 56 insertions(+), 78 deletions(-) diff --git a/e2e_tests/tests/per_provider/normal_tests/asym_encryption.rs b/e2e_tests/tests/per_provider/normal_tests/asym_encryption.rs index 41f71ffd..939f31d9 100644 --- a/e2e_tests/tests/per_provider/normal_tests/asym_encryption.rs +++ b/e2e_tests/tests/per_provider/normal_tests/asym_encryption.rs @@ -48,7 +48,7 @@ fn simple_asym_encrypt_rsa_pkcs() { .generate_rsa_encryption_keys_rsapkcs1v15crypt(key_name.clone()) .unwrap(); let _ciphertext = client - .asymmetric_encrypt_message_with_rsapkcs1v15(key_name.clone(), PLAINTEXT_MESSAGE.to_vec()) + .asymmetric_encrypt_message_with_rsapkcs1v15(key_name, PLAINTEXT_MESSAGE.to_vec()) .unwrap(); } @@ -95,7 +95,7 @@ fn asym_encrypt_wrong_algorithm() { .generate_rsa_encryption_keys_rsaoaep_sha256(key_name.clone()) .unwrap(); let status = client - .asymmetric_encrypt_message_with_rsapkcs1v15(key_name.clone(), PLAINTEXT_MESSAGE.to_vec()) + .asymmetric_encrypt_message_with_rsapkcs1v15(key_name, PLAINTEXT_MESSAGE.to_vec()) .unwrap_err(); assert_eq!(status, ResponseStatus::PsaErrorNotPermitted); } @@ -142,10 +142,10 @@ fn asym_encrypt_decrypt_rsa_pkcs_different_keys() { .generate_rsa_encryption_keys_rsapkcs1v15crypt(key_name_2.clone()) .unwrap(); let ciphertext = client - .asymmetric_encrypt_message_with_rsapkcs1v15(key_name_1.clone(), PLAINTEXT_MESSAGE.to_vec()) + .asymmetric_encrypt_message_with_rsapkcs1v15(key_name_1, PLAINTEXT_MESSAGE.to_vec()) .unwrap(); let _res = client - .asymmetric_decrypt_message_with_rsapkcs1v15(key_name_2.clone(), ciphertext) + .asymmetric_decrypt_message_with_rsapkcs1v15(key_name_2, ciphertext) .unwrap_err(); } @@ -173,7 +173,7 @@ fn asym_encrypt_verify_decrypt_with_rsa_crate() { .unwrap(); let plaintext = client - .asymmetric_decrypt_message_with_rsapkcs1v15(key_name.clone(), ciphertext) + .asymmetric_decrypt_message_with_rsapkcs1v15(key_name, ciphertext) .unwrap(); assert_eq!(&PLAINTEXT_MESSAGE[..], &plaintext[..]); diff --git a/src/bin/main.rs b/src/bin/main.rs index 46189e8a..9c03ec07 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -72,11 +72,11 @@ fn main() -> Result<()> { let _ = flag::register(SIGHUP, reload_signal.clone())?; let mut config_file = ::std::fs::read_to_string(opts.config.clone())?; - let mut config: ServiceConfig = toml::from_str(&config_file).or_else(|e| { - Err(Error::new( + let mut config: ServiceConfig = toml::from_str(&config_file).map_err(|e| { + Error::new( ErrorKind::InvalidInput, format!("Failed to parse service configuration ({})", e), - )) + ) })?; log_setup(&config); @@ -111,11 +111,11 @@ fn main() -> Result<()> { drop(threadpool); config_file = ::std::fs::read_to_string(opts.config.clone())?; - config = toml::from_str(&config_file).or_else(|e| { - Err(Error::new( + config = toml::from_str(&config_file).map_err(|e| { + Error::new( ErrorKind::InvalidInput, format!("Failed to parse service configuration ({})", e), - )) + ) })?; front_end_handler = Arc::from(ServiceBuilder::build_service(&config)?); listener = ServiceBuilder::start_listener(config.listener)?; diff --git a/src/key_info_managers/on_disk_manager/mod.rs b/src/key_info_managers/on_disk_manager/mod.rs index 1b161263..548f7dbd 100644 --- a/src/key_info_managers/on_disk_manager/mod.rs +++ b/src/key_info_managers/on_disk_manager/mod.rs @@ -190,9 +190,9 @@ impl OnDiskKeyInfoManager { let mut key_info = Vec::new(); let mut key_info_file = File::open(&key_name_file_path)?; let _ = key_info_file.read_to_end(&mut key_info)?; - let key_info = bincode::deserialize(&key_info[..]).or_else(|e| { + let key_info = bincode::deserialize(&key_info[..]).map_err(|e| { format_error!("Error deserializing key info", e); - Err(Error::new(ErrorKind::Other, "error deserializing key info")) + Error::new(ErrorKind::Other, "error deserializing key info") })?; match base64_data_triple_to_key_triple( os_str_to_u8_ref(app_name_dir_path.file_name().expect( @@ -257,9 +257,9 @@ impl OnDiskKeyInfoManager { } let mut mapping_file = fs::File::create(&key_name_file_path)?; - mapping_file.write_all(&bincode::serialize(key_info).or_else(|e| { + mapping_file.write_all(&bincode::serialize(key_info).map_err(|e| { format_error!("Error serializing key info", e); - Err(Error::new(ErrorKind::Other, "error serializing key info")) + Error::new(ErrorKind::Other, "error serializing key info") })?) } diff --git a/src/providers/core_provider/mod.rs b/src/providers/core_provider/mod.rs index 4c2b3f7d..e6cfe1c1 100644 --- a/src/providers/core_provider/mod.rs +++ b/src/providers/core_provider/mod.rs @@ -105,19 +105,19 @@ impl CoreProviderBuilder { } pub fn build(mut self) -> std::io::Result { - let crate_version: Version = Version::from_str(version!()).or_else(|e| { + let crate_version: Version = Version::from_str(version!()).map_err(|e| { format_error!("Error parsing the crate version", e); - Err(Error::new( + Error::new( ErrorKind::InvalidData, "crate version number has invalid format", - )) + ) })?; self.provider_info.push(ProviderInfo { // Assigned UUID for this provider: 47049873-2a43-4845-9d72-831eab668784 - uuid: Uuid::parse_str("47049873-2a43-4845-9d72-831eab668784").or_else(|_| Err(Error::new( + uuid: Uuid::parse_str("47049873-2a43-4845-9d72-831eab668784").map_err(|_| Error::new( ErrorKind::InvalidData, "provider UUID is invalid", - )))?, + ))?, description: String::from("Software provider that implements only administrative (i.e. no cryptographic) operations"), vendor: String::new(), version_maj: crate_version.major, diff --git a/src/providers/mbed_provider/key_management.rs b/src/providers/mbed_provider/key_management.rs index 0bc9685e..266ffeec 100644 --- a/src/providers/mbed_provider/key_management.rs +++ b/src/providers/mbed_provider/key_management.rs @@ -87,7 +87,7 @@ fn remove_key_id(key_triple: &KeyTriple, store_handle: &mut dyn ManageKeyInfo) - pub fn key_info_exists(key_triple: &KeyTriple, store_handle: &dyn ManageKeyInfo) -> Result { store_handle .exists(key_triple) - .or_else(|e| Err(key_info_managers::to_response_status(e))) + .map_err(key_info_managers::to_response_status) } impl MbedProvider { diff --git a/src/providers/pkcs11_provider/key_management.rs b/src/providers/pkcs11_provider/key_management.rs index f1fc6717..3ab8ebac 100644 --- a/src/providers/pkcs11_provider/key_management.rs +++ b/src/providers/pkcs11_provider/key_management.rs @@ -153,7 +153,7 @@ impl Pkcs11Provider { let key_name = op.key_name; let key_attributes = op.attributes; // This should never panic on 32 bits or more machines. - let key_size = std::convert::TryFrom::try_from(op.attributes.bits).unwrap(); + let key_size = op.attributes.bits; let key_triple = KeyTriple::new(app_name, ProviderID::Pkcs11, key_name); let mut store_handle = self @@ -463,9 +463,9 @@ impl Pkcs11Provider { modulus, public_exponent, }; - let data = picky_asn1_der::to_vec(&key).or_else(|err| { + let data = picky_asn1_der::to_vec(&key).map_err(|err| { format_error!("Could not serialise key elements", err); - Err(ResponseStatus::PsaErrorCommunicationFailure) + ResponseStatus::PsaErrorCommunicationFailure })?; Ok(psa_export_public_key::Result { data: data.into() }) } diff --git a/src/providers/pkcs11_provider/mod.rs b/src/providers/pkcs11_provider/mod.rs index 63e503f8..177819a4 100644 --- a/src/providers/pkcs11_provider/mod.rs +++ b/src/providers/pkcs11_provider/mod.rs @@ -319,12 +319,9 @@ impl Pkcs11ProviderBuilder { let slot_number = self .slot_number .ok_or_else(|| Error::new(ErrorKind::InvalidData, "missing slot number"))?; - let mut backend = Ctx::new(library_path).or_else(|e| { + let mut backend = Ctx::new(library_path).map_err(|e| { format_error!("Error creating a PKCS 11 context", e); - Err(Error::new( - ErrorKind::InvalidData, - "error creating PKCS 11 context", - )) + Error::new(ErrorKind::InvalidData, "error creating PKCS 11 context") })?; let mut args = CK_C_INITIALIZE_ARGS::new(); // Allow the PKCS 11 library to use OS native locking mechanism. @@ -334,12 +331,12 @@ impl Pkcs11ProviderBuilder { args.UnlockMutex = None; args.flags = CKF_OS_LOCKING_OK; trace!("Initialize command"); - backend.initialize(Some(args)).or_else(|e| { + backend.initialize(Some(args)).map_err(|e| { format_error!("Error initializing the PKCS 11 backend", e); - Err(Error::new( + Error::new( ErrorKind::InvalidData, "PKCS 11 backend initializing failed", - )) + ) })?; Ok(Pkcs11Provider::new( self.key_info_store diff --git a/src/providers/tpm_provider/asym_sign.rs b/src/providers/tpm_provider/asym_sign.rs index 2d59bd32..607f9f17 100644 --- a/src/providers/tpm_provider/asym_sign.rs +++ b/src/providers/tpm_provider/asym_sign.rs @@ -49,11 +49,11 @@ impl TpmProvider { &password_context.auth_value, &op.hash, ) - .or_else(|e| { + .map_err(|e| { if crate::utils::GlobalConfig::log_error_details() { error!("Error signing: {}.", e); } - Err(utils::to_response_status(e)) + utils::to_response_status(e) })?; Ok(psa_sign_hash::Result { diff --git a/src/providers/tpm_provider/key_management.rs b/src/providers/tpm_provider/key_management.rs index 4cfb0e6c..d2959683 100644 --- a/src/providers/tpm_provider/key_management.rs +++ b/src/providers/tpm_provider/key_management.rs @@ -53,7 +53,7 @@ pub fn get_password_context( ) -> Result<(PasswordContext, Attributes)> { let key_info = store_handle .get(&key_triple) - .or_else(|e| Err(key_info_managers::to_response_status(e)))? + .map_err(key_info_managers::to_response_status)? .ok_or_else(|| { if crate::utils::GlobalConfig::log_error_details() { error!( @@ -89,9 +89,9 @@ impl TpmProvider { let (key_context, auth_value) = esapi_context .create_signing_key(utils::parsec_to_tpm_params(attributes)?, AUTH_VAL_LEN) - .or_else(|e| { + .map_err(|e| { format_error!("Error creating a RSA signing key", e); - Err(utils::to_response_status(e)) + utils::to_response_status(e) })?; insert_password_context( @@ -132,9 +132,9 @@ impl TpmProvider { .expect("ESAPI Context lock poisoned"); let public_key: RSAPublicKey = picky_asn1_der::from_bytes(key_data.expose_secret()) - .or_else(|err| { + .map_err(|err| { format_error!("Could not deserialise key elements", err); - Err(ResponseStatus::PsaErrorInvalidArgument) + ResponseStatus::PsaErrorInvalidArgument })?; if public_key.modulus.is_negative() || public_key.public_exponent.is_negative() { @@ -183,9 +183,9 @@ impl TpmProvider { let pub_key_context = esapi_context .load_external_rsa_public_key(&key_data) - .or_else(|e| { + .map_err(|e| { format_error!("Error creating a RSA signing key", e); - Err(utils::to_response_status(e)) + utils::to_response_status(e) })?; insert_password_context( @@ -219,9 +219,9 @@ impl TpmProvider { let pub_key_data = esapi_context .read_public_key(password_context.context) - .or_else(|e| { + .map_err(|e| { format_error!("Error reading a public key", e); - Err(utils::to_response_status(e)) + utils::to_response_status(e) })?; Ok(psa_export_public_key::Result { diff --git a/src/providers/tpm_provider/mod.rs b/src/providers/tpm_provider/mod.rs index fb8b3e41..847cb5d0 100644 --- a/src/providers/tpm_provider/mod.rs +++ b/src/providers/tpm_provider/mod.rs @@ -201,11 +201,8 @@ impl TpmProviderBuilder { Some(mut auth) if auth.starts_with(AUTH_HEX_PREFIX) => Ok(hex::decode( auth.split_off(AUTH_STRING_PREFIX.len()), ) - .or_else(|_| { - Err(std::io::Error::new( - ErrorKind::InvalidData, - "invalid hex owner hierarchy auth", - )) + .map_err(|_| { + std::io::Error::new(ErrorKind::InvalidData, "invalid hex owner hierarchy auth") })?), Some(auth) => Ok(auth.into()), } @@ -225,19 +222,13 @@ impl TpmProviderBuilder { Tcti::from_str(self.tcti.as_ref().ok_or_else(|| { std::io::Error::new(ErrorKind::InvalidData, "Invalid TCTI configuration string") })?) - .or_else(|_| { - Err(std::io::Error::new( - ErrorKind::InvalidData, - "Invalid TCTI configuration string", - )) + .map_err(|_| { + std::io::Error::new(ErrorKind::InvalidData, "Invalid TCTI configuration string") })?, ) - .or_else(|e| { + .map_err(|e| { format_error!("Error when creating TSS Context", e); - Err(std::io::Error::new( - ErrorKind::InvalidData, - "failed initializing TSS context", - )) + std::io::Error::new(ErrorKind::InvalidData, "failed initializing TSS context") })?; for cipher in ciphers.iter() { if ctx @@ -265,11 +256,8 @@ impl TpmProviderBuilder { let tcti = Tcti::from_str(self.tcti.as_ref().ok_or_else(|| { std::io::Error::new(ErrorKind::InvalidData, "Invalid TCTI configuration string") })?) - .or_else(|_| { - Err(std::io::Error::new( - ErrorKind::InvalidData, - "Invalid TCTI configuration string", - )) + .map_err(|_| { + std::io::Error::new(ErrorKind::InvalidData, "Invalid TCTI configuration string") })?; TpmProvider::new( self.key_info_store.ok_or_else(|| { @@ -286,12 +274,9 @@ impl TpmProviderBuilder { ) .with_default_context_cipher(default_cipher) .build() - .or_else(|e| { + .map_err(|e| { format_error!("Error creating TSS Transient Object Context", e); - Err(std::io::Error::new( - ErrorKind::InvalidData, - "failed initializing TSS context", - )) + std::io::Error::new(ErrorKind::InvalidData, "failed initializing TSS context") })?, ) .ok_or_else(|| { diff --git a/src/providers/tpm_provider/utils.rs b/src/providers/tpm_provider/utils.rs index 93974bdb..1e1fd4fe 100644 --- a/src/providers/tpm_provider/utils.rs +++ b/src/providers/tpm_provider/utils.rs @@ -8,7 +8,6 @@ use parsec_interface::requests::{ResponseStatus, Result}; use picky_asn1::wrapper::IntegerAsn1; use picky_asn1_x509::RSAPublicKey; use serde::{Deserialize, Serialize}; -use std::convert::TryFrom; use std::convert::TryInto; use tss_esapi::abstraction::transient::KeyParams; use tss_esapi::response_code::{Error, Tss2ResponseCodeKind}; @@ -167,7 +166,7 @@ pub fn pub_key_to_bytes(pub_key: PublicKey, key_attributes: Attributes) -> Resul }) .or(Err(ResponseStatus::PsaErrorGenericError)), PublicKey::Ecc { x, y } => { - let p_byte_size = usize::try_from(key_attributes.bits / 8).unwrap(); // should not fail for valid keys + let p_byte_size = key_attributes.bits / 8; // should not fail for valid keys if x.len() != p_byte_size || y.len() != p_byte_size { if crate::utils::GlobalConfig::log_error_details() { error!( @@ -201,7 +200,7 @@ pub fn signature_data_to_bytes(data: SignatureData, key_attributes: Attributes) // ECDSA signature data is represented the concatenation of the two result values, r and s, // in big endian format, as described here: // https://parallaxsecond.github.io/parsec-book/parsec_client/operations/psa_algorithm.html#asymmetricsignature-algorithm - let p_byte_size = usize::try_from(key_attributes.bits / 8).unwrap(); // should not fail for valid keys + let p_byte_size = key_attributes.bits / 8; // should not fail for valid keys if r.len() != p_byte_size || s.len() != p_byte_size { if crate::utils::GlobalConfig::log_error_details() { error!( @@ -244,7 +243,7 @@ fn bytes_to_signature_data( // ECDSA signature data is represented the concatenation of the two result values, r and s, // in big endian format, as described here: // https://parallaxsecond.github.io/parsec-book/parsec_client/operations/psa_algorithm.html#asymmetricsignature-algorithm - let p_size = usize::try_from(key_attributes.bits / 8).unwrap(); + let p_size = key_attributes.bits / 8; if data.len() != p_size * 2 { return Err(ResponseStatus::PsaErrorInvalidArgument); } diff --git a/src/utils/service_builder.rs b/src/utils/service_builder.rs index 195f2ef2..b700d014 100644 --- a/src/utils/service_builder.rs +++ b/src/utils/service_builder.rs @@ -158,12 +158,9 @@ fn build_backend_handlers( .with_wire_protocol_version(WIRE_PROTOCOL_VERSION_MINOR, WIRE_PROTOCOL_VERSION_MAJOR); for (provider_id, provider) in providers.drain(..) { - let (info, opcodes) = provider.describe().or_else(|_| { - Err(Error::new( - ErrorKind::InvalidData, - "error describing provider", - )) - })?; + let (info, opcodes) = provider + .describe() + .map_err(|_| Error::new(ErrorKind::InvalidData, "error describing provider"))?; core_provider_builder = core_provider_builder.with_provider_details(info, opcodes); let backend_handler = BackEndHandlerBuilder::new()