Skip to content

Commit

Permalink
Merge pull request parallaxsecond#206 from ionut-arm/fix-clippy
Browse files Browse the repository at this point in the history
Fix clippy errors
  • Loading branch information
ionut-arm authored Jul 17, 2020
2 parents 9e622c7 + 00855d7 commit adaf587
Show file tree
Hide file tree
Showing 12 changed files with 56 additions and 78 deletions.
10 changes: 5 additions & 5 deletions e2e_tests/tests/per_provider/normal_tests/asym_encryption.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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();
}

Expand Down Expand Up @@ -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[..]);
Expand Down
12 changes: 6 additions & 6 deletions src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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)?;
Expand Down
8 changes: 4 additions & 4 deletions src/key_info_managers/on_disk_manager/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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")
})?)
}

Expand Down
10 changes: 5 additions & 5 deletions src/providers/core_provider/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,19 +105,19 @@ impl CoreProviderBuilder {
}

pub fn build(mut self) -> std::io::Result<CoreProvider> {
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,
Expand Down
2 changes: 1 addition & 1 deletion src/providers/mbed_provider/key_management.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<bool> {
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 {
Expand Down
6 changes: 3 additions & 3 deletions src/providers/pkcs11_provider/key_management.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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() })
}
Expand Down
13 changes: 5 additions & 8 deletions src/providers/pkcs11_provider/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
4 changes: 2 additions & 2 deletions src/providers/tpm_provider/asym_sign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
18 changes: 9 additions & 9 deletions src/providers/tpm_provider/key_management.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!(
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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 {
Expand Down
35 changes: 10 additions & 25 deletions src/providers/tpm_provider/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
}
Expand All @@ -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
Expand Down Expand Up @@ -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(|| {
Expand All @@ -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(|| {
Expand Down
7 changes: 3 additions & 4 deletions src/providers/tpm_provider/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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!(
Expand Down Expand Up @@ -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!(
Expand Down Expand Up @@ -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);
}
Expand Down
9 changes: 3 additions & 6 deletions src/utils/service_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit adaf587

Please sign in to comment.