fix clippy warnings

This commit is contained in:
Bilal Elmoussaoui 2025-02-13 13:28:48 +01:00
parent 36b15e87b2
commit a3b5ae9839
5 changed files with 42 additions and 42 deletions

View file

@ -21,7 +21,7 @@ fn main() {
} }
// Show message if no YubiKey(s) // Show message if no YubiKey(s)
if yubikeys.len() == 0 { if yubikeys.is_empty() {
println!("No yubikeys detected"); println!("No yubikeys detected");
std::process::exit(0); std::process::exit(0);
} }
@ -45,7 +45,7 @@ fn main() {
}; };
// Show message is node codes found // Show message is node codes found
if codes.len() == 0 { if codes.is_empty() {
println!("No credentials on device {}", device_label); println!("No credentials on device {}", device_label);
} }

View file

@ -20,7 +20,7 @@ fn _get_device_id(salt: Vec<u8>) -> String {
let hash_16_bytes = &result[..16]; let hash_16_bytes = &result[..16];
// Base64 encode the result and remove padding ('=') // Base64 encode the result and remove padding ('=')
return general_purpose::URL_SAFE_NO_PAD.encode(hash_16_bytes); general_purpose::URL_SAFE_NO_PAD.encode(hash_16_bytes)
} }
fn _hmac_sha1(key: &[u8], message: &[u8]) -> Vec<u8> { fn _hmac_sha1(key: &[u8], message: &[u8]) -> Vec<u8> {
let mut mac = Hmac::<sha1::Sha1>::new_from_slice(key).expect("Invalid key length"); let mut mac = Hmac::<sha1::Sha1>::new_from_slice(key).expect("Invalid key length");
@ -41,7 +41,7 @@ fn _hmac_shorten_key(key: &[u8], algo: HashAlgo) -> Vec<u8> {
} }
fn _get_challenge(timestamp: u64, period: u64) -> [u8; 8] { fn _get_challenge(timestamp: u64, period: u64) -> [u8; 8] {
return ((timestamp / period) as u64).to_be_bytes(); (timestamp / period).to_be_bytes()
} }
fn time_to_u64(timestamp: SystemTime) -> u64 { fn time_to_u64(timestamp: SystemTime) -> u64 {
@ -58,7 +58,7 @@ pub struct OathSession<'a> {
pub name: String, pub name: String,
} }
fn clone_with_lifetime<'a>(data: &'a [u8]) -> Vec<u8> { fn clone_with_lifetime(data: &[u8]) -> Vec<u8> {
// Clone the slice into a new Vec<u8> // Clone the slice into a new Vec<u8>
data.to_vec() // `to_vec()` will return a Vec<u8> that has its own ownership data.to_vec() // `to_vec()` will return a Vec<u8> that has its own ownership
} }
@ -71,7 +71,7 @@ pub struct RefreshableOathCredential<'a> {
refresh_provider: &'a OathSession<'a>, refresh_provider: &'a OathSession<'a>,
} }
impl<'a> Display for RefreshableOathCredential<'a> { impl Display for RefreshableOathCredential<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(c) = self.code { if let Some(c) = self.code {
f.write_fmt(format_args!("{}: {}", self.cred.id_data, c)) f.write_fmt(format_args!("{}: {}", self.cred.id_data, c))
@ -95,7 +95,7 @@ impl<'a> RefreshableOathCredential<'a> {
pub fn force_update(&mut self, code: Option<OathCodeDisplay>, timestamp: SystemTime) { pub fn force_update(&mut self, code: Option<OathCodeDisplay>, timestamp: SystemTime) {
self.code = code; self.code = code;
(self.valid_from, self.valid_to) = (self.valid_from, self.valid_to) =
RefreshableOathCredential::format_validity_time_frame(&self, timestamp); RefreshableOathCredential::format_validity_time_frame(self, timestamp);
} }
pub fn refresh(&mut self) { pub fn refresh(&mut self) {
@ -111,7 +111,7 @@ impl<'a> RefreshableOathCredential<'a> {
if !self.is_valid() { if !self.is_valid() {
self.refresh(); self.refresh();
} }
return self; self
} }
pub fn is_valid(&self) -> bool { pub fn is_valid(&self) -> bool {
@ -133,7 +133,7 @@ impl<'a> RefreshableOathCredential<'a> {
} }
} }
impl<'a> OathSession<'a> { impl OathSession<'_> {
pub fn new(name: &str) -> Result<Self, Error> { pub fn new(name: &str) -> Result<Self, Error> {
let transaction_context = TransactionContext::from_name(name)?; let transaction_context = TransactionContext::from_name(name)?;
let info_buffer = let info_buffer =
@ -199,7 +199,7 @@ impl<'a> OathSession<'a> {
timestamp_sys: Option<SystemTime>, timestamp_sys: Option<SystemTime>,
) -> Result<OathCodeDisplay, Error> { ) -> Result<OathCodeDisplay, Error> {
if self.name != cred.device_id { if self.name != cred.device_id {
return Err(Error::DeviceMismatchError); return Err(Error::DeviceMismatch);
} }
let timestamp = time_to_u64(timestamp_sys.unwrap_or_else(SystemTime::now)); let timestamp = time_to_u64(timestamp_sys.unwrap_or_else(SystemTime::now));
@ -220,11 +220,11 @@ impl<'a> OathSession<'a> {
Some(&data), Some(&data),
); );
let meta = TlvIter::from_vec(resp?).next().ok_or(Error::ParsingError( let meta = TlvIter::from_vec(resp?).next().ok_or(Error::Parsing(
"No credentials to unpack found in response".to_string(), "No credentials to unpack found in response".to_string(),
))?; ))?;
OathCodeDisplay::from_tlv(meta).ok_or(Error::ParsingError( OathCodeDisplay::from_tlv(meta).ok_or(Error::Parsing(
"error parsing calculation response".to_string(), "error parsing calculation response".to_string(),
)) ))
} }
@ -264,7 +264,7 @@ impl<'a> OathSession<'a> {
key_buffer.push(refreshable_cred); key_buffer.push(refreshable_cred);
} }
return Ok(key_buffer); Ok(key_buffer)
} }
pub fn list_oath_codes(&self) -> Result<Vec<CredentialIDData>, Error> { pub fn list_oath_codes(&self) -> Result<Vec<CredentialIDData>, Error> {
// Request OATH codes from device // Request OATH codes from device
@ -277,12 +277,12 @@ impl<'a> OathSession<'a> {
for cred_id in TlvIter::from_vec(response?) { for cred_id in TlvIter::from_vec(response?) {
let id_data = CredentialIDData::from_bytes( let id_data = CredentialIDData::from_bytes(
&cred_id.value()[1..], &cred_id.value()[1..],
*cred_id.value().get(0).unwrap_or(&0u8) & 0xf0, *cred_id.value().first().unwrap_or(&0u8) & 0xf0,
); );
key_buffer.push(id_data); key_buffer.push(id_data);
} }
return Ok(key_buffer); Ok(key_buffer)
} }
} }

View file

@ -35,13 +35,13 @@ impl PartialOrd for OathCredential {
} }
} }
impl<'a> PartialEq for OathCredential { impl PartialEq for OathCredential {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
self.device_id == other.device_id && self.id_data == other.id_data self.device_id == other.device_id && self.id_data == other.id_data
} }
} }
impl<'a> Hash for OathCredential { impl Hash for OathCredential {
fn hash<H: Hasher>(&self, state: &mut H) { fn hash<H: Hasher>(&self, state: &mut H) {
self.device_id.hash(state); self.device_id.hash(state);
self.id_data.format_cred_id().hash(state); self.id_data.format_cred_id().hash(state);

View file

@ -23,11 +23,11 @@ impl Display for CredentialIDData {
impl CredentialIDData { impl CredentialIDData {
pub fn from_tlv(id_bytes: &[u8], oath_type_tag: iso7816_tlv::simple::Tag) -> Self { pub fn from_tlv(id_bytes: &[u8], oath_type_tag: iso7816_tlv::simple::Tag) -> Self {
return CredentialIDData::from_bytes(id_bytes, Into::<u8>::into(oath_type_tag)); CredentialIDData::from_bytes(id_bytes, Into::<u8>::into(oath_type_tag))
} }
pub fn as_tlv(&self) -> Vec<u8> { pub fn as_tlv(&self) -> Vec<u8> {
return to_tlv(Tag::Name, &self.format_cred_id()); to_tlv(Tag::Name, &self.format_cred_id())
} }
pub fn format_cred_id(&self) -> Vec<u8> { pub fn format_cred_id(&self) -> Vec<u8> {
@ -42,7 +42,7 @@ impl CredentialIDData {
} }
cred_id.push_str(self.name.as_str()); cred_id.push_str(self.name.as_str());
return cred_id.into_bytes(); // Convert the string to bytes cred_id.into_bytes() // Convert the string to bytes
} }
// Function to parse the credential ID // Function to parse the credential ID
@ -55,19 +55,19 @@ impl CredentialIDData {
if oath_type == OathType::Totp { if oath_type == OathType::Totp {
Regex::new(r"^((\d+)/)?(([^:]+):)?(.+)$") Regex::new(r"^((\d+)/)?(([^:]+):)?(.+)$")
.ok() .ok()
.and_then(|r| r.captures(&data)) .and_then(|r| r.captures(data))
.map_or((None, data.to_string(), DEFAULT_PERIOD), |caps| { .map_or((None, data.to_string(), DEFAULT_PERIOD), |caps| {
let period = (&caps.get(2)) let period = caps
.get(2)
.and_then(|s| s.as_str().parse::<u32>().ok()) .and_then(|s| s.as_str().parse::<u32>().ok())
.unwrap_or(DEFAULT_PERIOD); .unwrap_or(DEFAULT_PERIOD);
return (Some(caps[4].to_string()), caps[5].to_string(), period); (Some(caps[4].to_string()), caps[5].to_string(), period)
}) })
} else { } else {
return data data.split_once(':')
.split_once(':')
.map_or((None, data.to_string(), 0), |(i, n)| { .map_or((None, data.to_string(), 0), |(i, n)| {
(Some(i.to_string()), n.to_string(), 0) (Some(i.to_string()), n.to_string(), 0)
}); })
} }
} }
@ -78,11 +78,11 @@ impl CredentialIDData {
OathType::Totp OathType::Totp
}; };
let (issuer, name, period) = CredentialIDData::parse_cred_id(id_bytes, oath_type); let (issuer, name, period) = CredentialIDData::parse_cred_id(id_bytes, oath_type);
return CredentialIDData { CredentialIDData {
issuer, issuer,
name, name,
period, period,
oath_type, oath_type,
}; }
} }
} }

View file

@ -11,9 +11,9 @@ use crate::{ErrorResponse, Instruction, SuccessResponse, Tag};
pub enum Error { pub enum Error {
Unknown(String), Unknown(String),
Protocol(ErrorResponse), Protocol(ErrorResponse),
PcscError(pcsc::Error), Pcsc(pcsc::Error),
ParsingError(String), Parsing(String),
DeviceMismatchError, DeviceMismatch,
} }
impl Error { impl Error {
@ -34,7 +34,7 @@ impl Error {
impl From<pcsc::Error> for Error { impl From<pcsc::Error> for Error {
fn from(value: pcsc::Error) -> Self { fn from(value: pcsc::Error) -> Self {
Self::PcscError(value) Self::Pcsc(value)
} }
} }
@ -43,9 +43,9 @@ impl Display for Error {
match self { match self {
Self::Unknown(msg) => f.write_str(msg), Self::Unknown(msg) => f.write_str(msg),
Self::Protocol(error_response) => f.write_fmt(format_args!("{}", error_response)), Self::Protocol(error_response) => f.write_fmt(format_args!("{}", error_response)),
Self::PcscError(error) => f.write_fmt(format_args!("{}", error)), Self::Pcsc(error) => f.write_fmt(format_args!("{}", error)),
Self::ParsingError(msg) => f.write_str(msg), Self::Parsing(msg) => f.write_str(msg),
Self::DeviceMismatchError => f.write_str("Devices do not match"), Self::DeviceMismatch => f.write_str("Devices do not match"),
} }
} }
} }
@ -183,7 +183,7 @@ pub fn tlv_to_map(data: Vec<u8>) -> HashMap<u8, Vec<u8>> {
for res in TlvIter::from_vec(data) { for res in TlvIter::from_vec(data) {
parsed_manual.insert(res.tag().into(), res.value().to_vec()); parsed_manual.insert(res.tag().into(), res.value().to_vec());
} }
return parsed_manual; parsed_manual
} }
pub struct TlvZipIter<'a> { pub struct TlvZipIter<'a> {
@ -207,10 +207,10 @@ impl<'a> TlvZipIter<'a> {
} }
} }
impl<'a> Iterator for TlvZipIter<'a> { impl Iterator for TlvZipIter<'_> {
type Item = (Tlv, Tlv); type Item = (Tlv, Tlv);
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
return Some((self.iter.next()?, self.iter.next()?)); Some((self.iter.next()?, self.iter.next()?))
} }
} }
@ -228,7 +228,7 @@ impl<'a> TlvIter<'a> {
} }
} }
impl<'a> Iterator for TlvIter<'a> { impl Iterator for TlvIter<'_> {
type Item = Tlv; type Item = Tlv;
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
@ -237,7 +237,7 @@ impl<'a> Iterator for TlvIter<'a> {
} }
let (r, remaining) = Tlv::parse(self.buf); let (r, remaining) = Tlv::parse(self.buf);
self.buf = remaining; self.buf = remaining;
return r.ok(); r.ok()
} }
} }
@ -246,8 +246,8 @@ pub fn tlv_to_lists(data: Vec<u8>) -> HashMap<u8, Vec<Vec<u8>>> {
for res in TlvIter::from_vec(data) { for res in TlvIter::from_vec(data) {
parsed_manual parsed_manual
.entry(res.tag().into()) .entry(res.tag().into())
.or_insert_with(Vec::new) .or_default()
.push(res.value().to_vec()); .push(res.value().to_vec());
} }
return parsed_manual; parsed_manual
} }