making 📎 slightly happier (#551)

This commit is contained in:
James Hodgkinson 2021-08-02 10:54:55 +10:00 committed by GitHub
parent b4f99c8e7a
commit 8737a7ad78
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 59 additions and 52 deletions

View file

@ -165,6 +165,7 @@ impl KanidmClientBuilder {
}) })
} }
#[allow(clippy::result_unit_err)]
pub fn read_options_from_optional_config<P: AsRef<Path> + std::fmt::Debug>( pub fn read_options_from_optional_config<P: AsRef<Path> + std::fmt::Debug>(
self, self,
config_path: P, config_path: P,
@ -268,6 +269,7 @@ impl KanidmClientBuilder {
} }
} }
#[allow(clippy::result_unit_err)]
pub fn add_root_certificate_filepath(self, ca_path: &str) -> Result<Self, ()> { pub fn add_root_certificate_filepath(self, ca_path: &str) -> Result<Self, ()> {
//Okay we have a ca to add. Let's read it in and setup. //Okay we have a ca to add. Let's read it in and setup.
let ca = Self::parse_certificate(ca_path)?; let ca = Self::parse_certificate(ca_path)?;

View file

@ -200,14 +200,14 @@ impl AccountOpt {
let mut totp_input = String::new(); let mut totp_input = String::new();
let input_result = io::stdin().read_line(&mut totp_input); let input_result = io::stdin().read_line(&mut totp_input);
// Finish the line? // Finish the line?
eprintln!(""); eprintln!();
if let Err(e) = input_result { if let Err(e) = input_result {
eprintln!("Failed to read from stdin -> {:?}", e); eprintln!("Failed to read from stdin -> {:?}", e);
break; break;
}; };
// Convert to a u32. // Convert to a u32.
let totp = match u32::from_str_radix(totp_input.trim(), 10) { let totp = match totp_input.trim().parse::<u32>() {
Ok(v) => v, Ok(v) => v,
Err(e) => { Err(e) => {
eprintln!("Invalid TOTP -> {:?}", e); eprintln!("Invalid TOTP -> {:?}", e);
@ -227,17 +227,14 @@ impl AccountOpt {
} }
Err(ClientError::TotpInvalidSha1(session)) => { Err(ClientError::TotpInvalidSha1(session)) => {
eprintln!("⚠️ WARNING - It appears your authenticator app may be broken ⚠️ "); eprintln!("⚠️ WARNING - It appears your authenticator app may be broken ⚠️ ");
eprintln!(" The TOTP authenticator you are using is forcing the use of SHA1"); eprintln!(" The TOTP authenticator you are using is forcing the use of SHA1\n");
eprintln!("");
eprintln!(" -- If you accept this risk, and wish to proceed, type 'I am sure' "); eprintln!(" -- If you accept this risk, and wish to proceed, type 'I am sure' ");
eprintln!(" -- Otherwise press ENTER to cancel this operation"); eprintln!(" -- Otherwise press ENTER to cancel this operation\n");
eprintln!("");
eprint!("Are you sure: "); eprint!("Are you sure: ");
let mut confirm_input = String::new(); let mut confirm_input = String::new();
if let Err(e) = io::stdin().read_line(&mut confirm_input) { if let Err(e) = io::stdin().read_line(&mut confirm_input) {
eprintln!("Failed to read from stdin -> {:?}", e); eprintln!("Failed to read from stdin -> {:?}", e);
break;
}; };
if confirm_input.to_lowercase().trim() == "i am sure" { if confirm_input.to_lowercase().trim() == "i am sure" {
@ -252,11 +249,10 @@ impl AccountOpt {
eprintln!("Error Completing -> {:?}", e); eprintln!("Error Completing -> {:?}", e);
} }
}; };
break;
} else { } else {
eprintln!("Cancelling TOTP registration"); eprintln!("Cancelling TOTP registration");
break;
} }
break;
} }
Err(ClientError::TotpVerifyFailed(_, _)) => { Err(ClientError::TotpVerifyFailed(_, _)) => {
eprintln!("Incorrect TOTP code - try again"); eprintln!("Incorrect TOTP code - try again");

View file

@ -84,12 +84,18 @@ impl CommonOpt {
for option in tokens.iter() { for option in tokens.iter() {
options.push(String::from(option.0)); options.push(String::from(option.0));
} }
let selection = Select::with_theme(&ColorfulTheme::default()) let user_select = Select::with_theme(&ColorfulTheme::default())
.with_prompt("Multiple authentication tokens exist. Please select one") .with_prompt("Multiple authentication tokens exist. Please select one")
.default(0) .default(0)
.items(&options) .items(&options)
.interact() .interact();
.unwrap(); let selection = match user_select {
Err(error) => {
eprintln!("Failed to handle user input: {:?}", error);
std::process::exit(1);
}
Ok(value) => value,
};
debug!("Index of the chosen menu item: {:?}", selection); debug!("Index of the chosen menu item: {:?}", selection);
let (f_uname, f_token) = let (f_uname, f_token) =

View file

@ -13,6 +13,7 @@ use webauthn_authenticator_rs::{u2fhid::U2FHid, RequestChallengeResponse, Webaut
static TOKEN_DIR: &str = "~/.cache"; static TOKEN_DIR: &str = "~/.cache";
static TOKEN_PATH: &str = "~/.cache/kanidm_tokens"; static TOKEN_PATH: &str = "~/.cache/kanidm_tokens";
#[allow(clippy::result_unit_err)]
pub fn read_tokens() -> Result<BTreeMap<String, String>, ()> { pub fn read_tokens() -> Result<BTreeMap<String, String>, ()> {
let token_path = PathBuf::from(shellexpand::tilde(TOKEN_PATH).into_owned()); let token_path = PathBuf::from(shellexpand::tilde(TOKEN_PATH).into_owned());
if !token_path.exists() { if !token_path.exists() {
@ -59,6 +60,7 @@ pub fn read_tokens() -> Result<BTreeMap<String, String>, ()> {
}) })
} }
#[allow(clippy::result_unit_err)]
pub fn write_tokens(tokens: &BTreeMap<String, String>) -> Result<(), ()> { pub fn write_tokens(tokens: &BTreeMap<String, String>) -> Result<(), ()> {
let token_dir = PathBuf::from(shellexpand::tilde(TOKEN_DIR).into_owned()); let token_dir = PathBuf::from(shellexpand::tilde(TOKEN_DIR).into_owned());
let token_path = PathBuf::from(shellexpand::tilde(TOKEN_PATH).into_owned()); let token_path = PathBuf::from(shellexpand::tilde(TOKEN_PATH).into_owned());
@ -116,7 +118,7 @@ fn get_index_choice(len: usize) -> Result<u8, ClientError> {
return Err(ClientError::SystemError); return Err(ClientError::SystemError);
}; };
let response = buffer.trim(); let response = buffer.trim();
match u8::from_str_radix(response, 10) { match response.parse::<u8>() {
Ok(i) => { Ok(i) => {
if (i as usize) < len { if (i as usize) < len {
return Ok(i); return Ok(i);
@ -145,6 +147,7 @@ impl LoginOpt {
fn do_backup_code(&self, client: &mut KanidmClient) -> Result<AuthResponse, ClientError> { fn do_backup_code(&self, client: &mut KanidmClient) -> Result<AuthResponse, ClientError> {
print!("Enter Backup Code: "); print!("Enter Backup Code: ");
// We flush stdout so it'll write the buffer to screen, continuing operation. Without it, the application halts. // We flush stdout so it'll write the buffer to screen, continuing operation. Without it, the application halts.
#[allow(clippy::unwrap_used)]
io::stdout().flush().unwrap(); io::stdout().flush().unwrap();
let mut backup_code = String::new(); let mut backup_code = String::new();
loop { loop {
@ -152,7 +155,7 @@ impl LoginOpt {
eprintln!("Failed to read from stdin -> {:?}", e); eprintln!("Failed to read from stdin -> {:?}", e);
return Err(ClientError::SystemError); return Err(ClientError::SystemError);
}; };
if backup_code.trim().len() > 0 { if !backup_code.trim().is_empty() {
break; break;
}; };
} }
@ -171,7 +174,7 @@ impl LoginOpt {
}; };
let response = buffer.trim(); let response = buffer.trim();
match u32::from_str_radix(response, 10) { match response.parse::<u32>() {
Ok(i) => break i, Ok(i) => break i,
Err(_) => eprintln!("Invalid Number"), Err(_) => eprintln!("Invalid Number"),
}; };

View file

@ -60,15 +60,15 @@ fn main() {
println!("cargo:rerun-if-changed={}", profile_path.to_str().unwrap()); println!("cargo:rerun-if-changed={}", profile_path.to_str().unwrap());
let mut f = let mut f = File::open(&profile_path)
File::open(&profile_path).expect(format!("Failed to open {:?}", profile_path).as_str()); .unwrap_or_else(|_| panic!("Failed to open build profile {:?}", profile_path));
let mut contents = String::new(); let mut contents = String::new();
f.read_to_string(&mut contents) f.read_to_string(&mut contents)
.expect(format!("Failed to read {:?}", profile_path).as_str()); .unwrap_or_else(|_| panic!("Failed to read build profile {:?}", profile_path));
let profile_cfg: ProfileConfig = toml::from_str(contents.as_str()) let profile_cfg: ProfileConfig = toml::from_str(contents.as_str())
.expect(format!("Failed to parse {:?}", profile_path).as_str()); .unwrap_or_else(|_| panic!("Failed to parse build profile {:?}", profile_path));
match profile_cfg.cpu_flags { match profile_cfg.cpu_flags {
CpuOptLevel::none => {} CpuOptLevel::none => {}

View file

@ -225,8 +225,16 @@ impl QueryServerReadV1 {
// cleanup of maximum backup versions to keep // cleanup of maximum backup versions to keep
let mut backup_file_list: Vec<PathBuf> = Vec::new(); let mut backup_file_list: Vec<PathBuf> = Vec::new();
// pattern to find automatically generated backup files // pattern to find automatically generated backup files
let re = Regex::new(r"^backup-\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z\.json$") let re = match Regex::new(r"^backup-\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z\.json$") {
.expect("Failed to parse regexp for online backup files."); Ok(value) => value,
Err(error) => {
eprintln!(
"Failed to parse regexp for online backup files: {:?}",
error
);
return;
}
};
// get a list of backup files // get a list of backup files
match fs::read_dir(outpath) { match fs::read_dir(outpath) {

View file

@ -303,8 +303,7 @@ pub trait BackendTransaction {
let mut f_rem_count = f_rem.len() + f_andnot.len() - 1; let mut f_rem_count = f_rem.len() + f_andnot.len() - 1;
// Setup the query plan tracker // Setup the query plan tracker
let mut plan = Vec::new(); let mut plan = vec![fp];
plan.push(fp);
match &cand_idl { match &cand_idl {
IdList::Indexed(idl) | IdList::Partial(idl) | IdList::PartialThreshold(idl) => { IdList::Indexed(idl) | IdList::Partial(idl) | IdList::PartialThreshold(idl) => {

View file

@ -91,7 +91,7 @@ impl TryFrom<&str> for Password {
let hash = django_pbkdf[3]; let hash = django_pbkdf[3];
match algo { match algo {
"pbkdf2_sha256" => { "pbkdf2_sha256" => {
let c = usize::from_str_radix(cost, 10).map_err(|_| ())?; let c = cost.parse::<usize>().map_err(|_| ())?;
let s: Vec<_> = salt.as_bytes().to_vec(); let s: Vec<_> = salt.as_bytes().to_vec();
let h = base64::decode(hash).map_err(|_| ())?; let h = base64::decode(hash).map_err(|_| ())?;
if h.len() < PBKDF2_IMPORT_MIN_LEN { if h.len() < PBKDF2_IMPORT_MIN_LEN {
@ -808,12 +808,7 @@ impl Credential {
Some(mut backup_codes) => { Some(mut backup_codes) => {
backup_codes.remove(&code_to_remove); backup_codes.remove(&code_to_remove);
Ok(Credential { Ok(Credential {
type_: CredentialType::PasswordMfa( type_: CredentialType::PasswordMfa(pw, totp, wan, Some(backup_codes)),
pw.clone(),
totp.clone(),
wan.clone(),
Some(backup_codes),
),
claims: self.claims.clone(), claims: self.claims.clone(),
uuid: self.uuid, uuid: self.uuid,
}) })
@ -846,9 +841,9 @@ impl Credential {
match &self.type_ { match &self.type_ {
CredentialType::PasswordMfa(_, _, _, opt_bc) => opt_bc CredentialType::PasswordMfa(_, _, _, opt_bc) => opt_bc
.as_ref() .as_ref()
.ok_or(OperationError::InvalidAccountState( .ok_or(OperationError::InvalidAccountState(String::from(
"No backup codes are available for this account".to_string(), "No backup codes are available for this account",
)) )))
.and_then(|bc| { .and_then(|bc| {
Ok(BackupCodesView { Ok(BackupCodesView {
backup_codes: bc.code_set.clone().into_iter().collect(), backup_codes: bc.code_set.clone().into_iter().collect(),

View file

@ -90,7 +90,7 @@ pub fn f_id(id: &str) -> FC<'static> {
let nf = FC::Eq("name", PartialValue::new_iname(id)); let nf = FC::Eq("name", PartialValue::new_iname(id));
let f: Vec<_> = iter::once(uf) let f: Vec<_> = iter::once(uf)
.chain(iter::once(spnf)) .chain(iter::once(spnf))
.filter_map(|v| v) .flatten()
.chain(iter::once(nf)) .chain(iter::once(nf))
.collect(); .collect();
FC::Or(f) FC::Or(f)
@ -100,10 +100,7 @@ pub fn f_id(id: &str) -> FC<'static> {
pub fn f_spn_name(id: &str) -> FC<'static> { pub fn f_spn_name(id: &str) -> FC<'static> {
let spnf = PartialValue::new_spn_s(id).map(|spn| FC::Eq("spn", spn)); let spnf = PartialValue::new_spn_s(id).map(|spn| FC::Eq("spn", spn));
let nf = FC::Eq("name", PartialValue::new_iname(id)); let nf = FC::Eq("name", PartialValue::new_iname(id));
let f: Vec<_> = iter::once(spnf) let f: Vec<_> = iter::once(spnf).flatten().chain(iter::once(nf)).collect();
.filter_map(|v| v)
.chain(iter::once(nf))
.collect();
FC::Or(f) FC::Or(f)
} }

View file

@ -68,8 +68,8 @@ impl RadiusAccount {
Ok(RadiusAccount { Ok(RadiusAccount {
name, name,
uuid,
displayname, displayname,
uuid,
groups, groups,
radius_secret, radius_secret,
valid_from, valid_from,

View file

@ -98,8 +98,8 @@ impl LdapServer {
}; };
Ok(LdapServer { Ok(LdapServer {
basedn,
rootdse, rootdse,
basedn,
dnre, dnre,
binddnre, binddnre,
}) })

View file

@ -22,7 +22,7 @@ impl Cid {
} else { } else {
*max_ts + Duration::from_nanos(1) *max_ts + Duration::from_nanos(1)
}; };
Cid { d_uuid, s_uuid, ts } Cid { ts, d_uuid, s_uuid }
} }
#[cfg(test)] #[cfg(test)]

View file

@ -347,8 +347,8 @@ impl SchemaClass {
uuid, uuid,
description, description,
systemmay, systemmay,
systemmust,
may, may,
systemmust,
must, must,
}) })
} }

View file

@ -484,7 +484,7 @@ impl PartialValue {
} }
pub fn new_uint32_str(u: &str) -> Option<Self> { pub fn new_uint32_str(u: &str) -> Option<Self> {
u32::from_str_radix(u, 10).ok().map(PartialValue::Uint32) u.parse::<u32>().ok().map(PartialValue::Uint32)
} }
pub fn is_uint32(&self) -> bool { pub fn is_uint32(&self) -> bool {

View file

@ -136,7 +136,7 @@ impl<'a> IntoIterator for &'a ValueSet {
fn into_iter(self) -> Self::IntoIter { fn into_iter(self) -> Self::IntoIter {
Iter { Iter {
iter: (&self.inner).into_iter(), iter: (&self.inner).iter(),
} }
} }
} }

View file

@ -80,8 +80,8 @@ impl Group {
Group { Group {
name, name,
members,
uuid, uuid,
members,
} }
} }
} }

View file

@ -54,6 +54,7 @@ pub enum TargetServerBuilder {
} }
impl TargetServerBuilder { impl TargetServerBuilder {
#[allow(clippy::result_unit_err)]
pub fn build(self) -> Result<TargetServer, ()> { pub fn build(self) -> Result<TargetServer, ()> {
match self { match self {
TargetServerBuilder::Kanidm(a, b) => KaniHttpServer::build(a, b), TargetServerBuilder::Kanidm(a, b) => KaniHttpServer::build(a, b),

View file

@ -69,8 +69,8 @@ fn parse_rtime(s: &str) -> Result<Duration, ()> {
return Err(()); return Err(());
} }
let hh = u32::from_str_radix(v[0], 10).map_err(|_| ())?; let hh = v[0].parse::<u32>().map_err(|_| ())?;
let mm = u32::from_str_radix(v[1], 10).map_err(|_| ())?; let mm = v[1].parse::<u32>().map_err(|_| ())?;
let ss = f64::from_str(v[2]).map_err(|_| ())?; let ss = f64::from_str(v[2]).map_err(|_| ())?;
let ext_secs = ((mm * 60) + (hh * 3600)) as f64; let ext_secs = ((mm * 60) + (hh * 3600)) as f64;
@ -161,7 +161,7 @@ impl TryFrom<RawRecord> for Record {
op_type, op_type,
} = value; } = value;
let conn = i32::from_str_radix(&conn, 10).map_err(|_| ())?; let conn = conn.parse::<i32>().map_err(|_| ())?;
let etime = f64::from_str(&etime) let etime = f64::from_str(&etime)
.map(Duration::from_secs_f64) .map(Duration::from_secs_f64)
.map_err(|_| ())?; .map_err(|_| ())?;

View file

@ -1,13 +1,13 @@
use crate::setup::config; use crate::setup::config;
use crate::{TargetOpt, TestTypeOpt}; use crate::{TargetOpt, TestTypeOpt};
use std::path::PathBuf; use std::path::{Path, PathBuf};
mod search; mod search;
pub(crate) async fn doit( pub(crate) async fn doit(
testtype: &TestTypeOpt, testtype: &TestTypeOpt,
target: &TargetOpt, target: &TargetOpt,
profile_path: &PathBuf, profile_path: &Path,
) -> Result<(), ()> { ) -> Result<(), ()> {
info!( info!(
"Performing test {} against {:?} from {}", "Performing test {} against {:?} from {}",

View file

@ -12,7 +12,7 @@ use uuid::Uuid;
pub(crate) fn config( pub(crate) fn config(
target: &TargetOpt, target: &TargetOpt,
profile_path: &PathBuf, profile_path: &Path,
) -> Result<(TestData, Profile, TargetServer), ()> { ) -> Result<(TestData, Profile, TargetServer), ()> {
// read the profile that we are going to be using/testing // read the profile that we are going to be using/testing
let mut f = File::open(profile_path).map_err(|e| { let mut f = File::open(profile_path).map_err(|e| {
@ -91,7 +91,7 @@ pub(crate) fn config(
Ok((data, profile, server)) Ok((data, profile, server))
} }
pub(crate) async fn doit(target: &TargetOpt, profile_path: &PathBuf) -> Result<(), ()> { pub(crate) async fn doit(target: &TargetOpt, profile_path: &Path) -> Result<(), ()> {
info!( info!(
"Performing setup of {:?} from {}", "Performing setup of {:?} from {}",
target, target,