Skip to content

Commit

Permalink
Fix some clippy warnings (kanidm#393)
Browse files Browse the repository at this point in the history
* fix unused import warnings
* fix some clippys
* remove base16_decode
  • Loading branch information
micolous authored and kikuomax committed Nov 4, 2024
1 parent ddae312 commit 9ee7920
Show file tree
Hide file tree
Showing 10 changed files with 116 additions and 140 deletions.
12 changes: 7 additions & 5 deletions cable-tunnel-server/frontend/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::{
collections::HashMap, convert::Infallible, error::Error as StdError, net::SocketAddr, sync::Arc,
collections::HashMap, convert::Infallible, error::Error as StdError, fmt::Write,
net::SocketAddr, sync::Arc,
};

use clap::{ArgAction, Parser, ValueHint};
Expand Down Expand Up @@ -98,10 +99,11 @@ async fn handle_request(
Router::Debug => {
return Ok(if state.debug_handler {
let backends_read = state.backends.read().await;
let backends_info: String = backends_read
.iter()
.map(|(k, v)| format!("backends[{}] = {v}\n", hex::encode_upper(k)))
.collect();
let backends_info: String =
backends_read.iter().fold(String::new(), |mut out, (k, v)| {
let _ = writeln!(out, "backends[{}] = {v}", hex::encode_upper(k));
out
});
let debug = format!(
"server_state.strong_count = {}\nbackends.capacity = {}\nbackends.len = {}\n{}",
Arc::strong_count(&state),
Expand Down
16 changes: 12 additions & 4 deletions fido-hid-rs/src/descriptors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//!
//! ## References
//!
//! * [Device Class Definition for Human Interface Devices, version 1.11][0],
//! * [Device Class Definition for Human Interface Devices, v1.11][0],
//! §6.2.2 "Report Descriptor"
//!
//! [0]: https://www.usb.org/sites/default/files/documents/hid1_11.pdf
Expand All @@ -13,6 +13,14 @@ use num_traits::FromPrimitive;
use crate::{FIDO_USAGE_PAGE, FIDO_USAGE_U2FHID};

/// HID descriptor tags; shifted right by 2 bits (removing the `bSize` field).
///
/// ## References
///
/// * [Device Class Definition for Human Interface Devices, v1.11][0],
/// §5.3 "Generic Item Format"
///
/// [0]: https://www.usb.org/sites/default/files/documents/hid1_11.pdf
#[allow(clippy::unusual_byte_groupings)] // groupings are bTag(4), bType(2)
#[derive(FromPrimitive)]
#[repr(u8)]
enum Tag {
Expand Down Expand Up @@ -130,9 +138,9 @@ impl<'a> Iterator for DescriptorIterator<'a> {
/// support simple descriptors. This is should be sufficient for USB FIDO
/// authethicators.
pub fn is_fido_authenticator(descriptor: &[u8]) -> bool {
let mut descriptor = DescriptorIterator { i: descriptor };
let descriptor = DescriptorIterator { i: descriptor };
let mut current_usage_page = 0u16;
while let Some(item) = descriptor.next() {
for item in descriptor {
// trace!("item: {item:?}");
match item.tag {
Some(Tag::UsagePage) => {
Expand Down Expand Up @@ -170,7 +178,7 @@ pub fn is_fido_authenticator(descriptor: &[u8]) -> bool {
_ => continue,
}
}
return false;
false
}

#[cfg(test)]
Expand Down
1 change: 1 addition & 0 deletions fido-hid-rs/src/linux/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ impl USBDeviceManager for USBDeviceManagerImpl {
EventType::Remove => {
if let Some(path) = device.devnode() {
if known_devices.remove(path) {
// We knew this device once, notify watchers
if tx.blocking_send(WatchEvent::Removed(path.into())).is_err() {
// Channel disappeared!
return;
Expand Down
27 changes: 5 additions & 22 deletions fido-key-manager/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ use std::io::{stdin, stdout, Write};
use std::time::Duration;
use tokio_stream::StreamExt;
#[cfg(feature = "solokey")]
use webauthn_authenticator_rs::ctap2::SoloKeyAuthenticator;
#[cfg(feature = "solokey")]
use webauthn_authenticator_rs::prelude::WebauthnCError;
use webauthn_authenticator_rs::{ctap2::SoloKeyAuthenticator, prelude::WebauthnCError};
use webauthn_authenticator_rs::{
ctap2::{
commands::UserCM, select_one_device, select_one_device_predicate,
Expand Down Expand Up @@ -216,21 +214,6 @@ pub struct CliParser {
pub commands: Opt,
}

pub fn base16_encode<T: IntoIterator<Item = u8>>(i: T) -> String {
i.into_iter().map(|c| format!("{c:02X}")).collect()
}

pub fn base16_decode(s: &str) -> Option<Vec<u8>> {
if s.len() % 2 != 0 {
return None;
}
(0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16))
.collect::<Result<Vec<_>, _>>()
.ok()
}

#[tokio::main]
async fn main() {
let opt = CliParser::parse();
Expand Down Expand Up @@ -385,7 +368,7 @@ async fn main() {
.enroll_fingerprint(Duration::from_secs(30), o.friendly_name)
.await
.expect("enrolling fingerprint");
println!("Enrolled fingerpint {}", base16_encode(id));
println!("Enrolled fingerpint {}", hex::encode(id));
}

Opt::ListFingerprints => {
Expand All @@ -405,7 +388,7 @@ async fn main() {
for t in fingerprints {
println!(
"* ID: {}, Name: {:?}",
base16_encode(t.id),
hex::encode(t.id),
t.friendly_name.unwrap_or_default()
);
}
Expand All @@ -420,7 +403,7 @@ async fn main() {
token
.bio()
.unwrap()
.rename_fingerprint(base16_decode(&o.id).expect("decoding ID"), o.friendly_name)
.rename_fingerprint(hex::decode(&o.id).expect("decoding ID"), o.friendly_name)
.await
.expect("renaming fingerprint");
}
Expand All @@ -433,7 +416,7 @@ async fn main() {

let ids: Vec<Vec<u8>> =
o.id.iter()
.map(|i| base16_decode(i).expect("decoding ID"))
.map(|i| hex::decode(i).expect("decoding ID"))
.collect();
token
.bio()
Expand Down
7 changes: 5 additions & 2 deletions webauthn-authenticator-rs/examples/cable_domain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
//! cargo run --example cable_domain --features cable -- --help
//! ```
use clap::{error::ErrorKind, ArgGroup, CommandFactory, Parser, ValueHint};
use std::net::ToSocketAddrs;
use std::{fmt::Write, net::ToSocketAddrs};
use webauthn_authenticator_rs::cable::get_domain;

#[derive(Debug, clap::Parser)]
Expand Down Expand Up @@ -54,7 +54,10 @@ pub struct CliParser {
/// Returns [None] on resolution failure or no results.
fn resolver(hostname: &str) -> Option<String> {
(hostname, 443).to_socket_addrs().ok().and_then(|addrs| {
let mut o: String = addrs.map(|addr| format!("{},", addr.ip())).collect();
let mut o: String = addrs.fold(String::new(), |mut out, addr| {
let _ = write!(out, "{},", addr.ip());
out
});
o.pop();

if o.is_empty() {
Expand Down
106 changes: 41 additions & 65 deletions webauthn-authenticator-rs/src/bluetooth/framing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,19 +266,16 @@ mod test {
len: 17,
data: vec![0xFF; 17],
};
let expected = Ok(vec![
let expected = vec![
0x80, 0x00, 0x11, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
]);
];

assert!(frame.complete());
assert!(frame.is_initial());
assert_eq!(frame.as_vec(20), expected);
assert_eq!(frame.as_vec(512), expected);
assert_eq!(
frame,
BtleFrame::try_from(expected.unwrap().as_slice()).unwrap()
);
assert_eq!(frame.as_vec(20).unwrap(), expected);
assert_eq!(frame.as_vec(512).unwrap(), expected);
assert_eq!(frame, BtleFrame::try_from(expected.as_slice()).unwrap());

// Invalid MTUs
for mtu in (0..=19).chain([513].into_iter()) {
Expand All @@ -297,20 +294,17 @@ mod test {
len: 18,
data: vec![0xFF; 18],
};
let expected = Ok(vec![
let expected = vec![
0x80, 0x00, 0x12, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
]);
];

assert!(frame.complete());
assert!(frame.is_initial());
assert_eq!(frame.as_vec(20), Err(WebauthnCError::MessageTooLarge));
assert_eq!(frame.as_vec(21), expected);
assert_eq!(frame.as_vec(512), expected);
assert_eq!(
frame,
BtleFrame::try_from(expected.unwrap().as_slice()).unwrap()
);
assert_eq!(frame.as_vec(21).unwrap(), expected);
assert_eq!(frame.as_vec(512).unwrap(), expected);
assert_eq!(frame, BtleFrame::try_from(expected.as_slice()).unwrap());
}

#[test]
Expand All @@ -321,16 +315,13 @@ mod test {
len: 1,
data: vec![0xFF; 1],
};
let expected = Ok(vec![0x80, 0x00, 0x01, 0xff]);
let expected = vec![0x80, 0x00, 0x01, 0xff];

assert!(frame.complete());
assert!(frame.is_initial());
assert_eq!(frame.as_vec(20), expected);
assert_eq!(frame.as_vec(512), expected);
assert_eq!(
frame,
BtleFrame::try_from(expected.unwrap().as_slice()).unwrap()
);
assert_eq!(frame.as_vec(20).unwrap(), expected);
assert_eq!(frame.as_vec(512).unwrap(), expected);
assert_eq!(frame, BtleFrame::try_from(expected.as_slice()).unwrap());

// Invalid MTUs
for mtu in (0..=19).chain([513].into_iter()) {
Expand All @@ -352,19 +343,19 @@ mod test {
len: 0,
data: vec![0xFF; 1],
};
let expected = Ok(vec![0x80, 0x00, 0x00, 0xff]);
let expected = vec![0x80, 0x00, 0x00, 0xff];

assert!(frame.complete()); // because ==0
assert!(frame.is_initial());
assert_eq!(frame.as_vec(20), expected);
assert_eq!(frame.as_vec(512), expected);
assert_eq!(frame.as_vec(20).unwrap(), expected);
assert_eq!(frame.as_vec(512).unwrap(), expected);
// Should drop the excess bytes for a zero-length frame...
assert_eq!(
BtleFrame {
data: vec![],
..frame
},
BtleFrame::try_from(expected.unwrap().as_slice()).unwrap()
BtleFrame::try_from(expected.as_slice()).unwrap()
);

// Technically invalid...
Expand All @@ -373,17 +364,14 @@ mod test {
len: 2,
data: vec![0xFF; 1],
};
let expected = Ok(vec![0x80, 0x00, 0x02, 0xff]);
let expected = vec![0x80, 0x00, 0x02, 0xff];

assert!(!frame.complete()); // because !=0 and !=len
assert!(frame.is_initial());
assert_eq!(frame.as_vec(20), expected);
assert_eq!(frame.as_vec(512), expected);
assert_eq!(frame.as_vec(20).unwrap(), expected);
assert_eq!(frame.as_vec(512).unwrap(), expected);
// Keep the partial bytes
assert_eq!(
frame,
BtleFrame::try_from(expected.unwrap().as_slice()).unwrap()
);
assert_eq!(frame, BtleFrame::try_from(expected.as_slice()).unwrap());
}

#[test]
Expand All @@ -394,19 +382,16 @@ mod test {
len: 0,
data: vec![0xFF; 19],
};
let expected = Ok(vec![
let expected = vec![
0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
]);
];

assert!(!frame.complete());
assert!(!frame.is_initial());
assert_eq!(frame.as_vec(20), expected);
assert_eq!(frame.as_vec(512), expected);
assert_eq!(
frame,
BtleFrame::try_from(expected.unwrap().as_slice()).unwrap()
);
assert_eq!(frame.as_vec(20).unwrap(), expected);
assert_eq!(frame.as_vec(512).unwrap(), expected);
assert_eq!(frame, BtleFrame::try_from(expected.as_slice()).unwrap());

// Invalid MTUs
for mtu in (0..=19).chain([513].into_iter()) {
Expand All @@ -427,20 +412,17 @@ mod test {
len: 0,
data: vec![0xFF; 20],
};
let expected = Ok(vec![
let expected = vec![
0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
]);
];

assert!(!frame.complete());
assert!(!frame.is_initial());
assert_eq!(frame.as_vec(20), Err(WebauthnCError::MessageTooLarge));
assert_eq!(frame.as_vec(21), expected);
assert_eq!(frame.as_vec(512), expected);
assert_eq!(
frame,
BtleFrame::try_from(expected.unwrap().as_slice()).unwrap()
);
assert_eq!(frame.as_vec(21).unwrap(), expected);
assert_eq!(frame.as_vec(512).unwrap(), expected);
assert_eq!(frame, BtleFrame::try_from(expected.as_slice()).unwrap());
}

#[test]
Expand All @@ -451,16 +433,13 @@ mod test {
len: 0,
data: vec![0xFF; 1],
};
let expected = Ok(vec![0x01, 0xff]);
let expected = vec![0x01, 0xff];

assert!(!frame.complete());
assert!(!frame.is_initial());
assert_eq!(frame.as_vec(20), expected);
assert_eq!(frame.as_vec(512), expected);
assert_eq!(
frame,
BtleFrame::try_from(expected.unwrap().as_slice()).unwrap()
);
assert_eq!(frame.as_vec(20).unwrap(), expected);
assert_eq!(frame.as_vec(512).unwrap(), expected);
assert_eq!(frame, BtleFrame::try_from(expected.as_slice()).unwrap());

// Invalid MTUs
for mtu in (0..=19).chain([513].into_iter()) {
Expand All @@ -479,19 +458,16 @@ mod test {
len: 512,
data: vec![0xFF; 17],
};
let expected = Ok(vec![
let expected = vec![
0x80, 0x02, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
]);
];

assert!(!frame.complete());
assert!(frame.is_initial());
assert_eq!(frame.as_vec(20), expected);
assert_eq!(frame.as_vec(512), expected);
assert_eq!(
frame,
BtleFrame::try_from(expected.unwrap().as_slice()).unwrap()
);
assert_eq!(frame.as_vec(20).unwrap(), expected);
assert_eq!(frame.as_vec(512).unwrap(), expected);
assert_eq!(frame, BtleFrame::try_from(expected.as_slice()).unwrap());
}

#[test]
Expand Down
Loading

0 comments on commit 9ee7920

Please sign in to comment.