diff --git a/build.rs b/build.rs index b4e07677..53dbfa31 100644 --- a/build.rs +++ b/build.rs @@ -115,7 +115,7 @@ fn set_readme_version(package_version: &str, file: &str) -> Result<(), Box, inputs: &mut Inputs) { Rule::opt_timeout_d_arg => { let mut reversed = pair.as_str().split(':').rev(); let mut duration: Duration = - Duration::try_seconds(reversed.nth(0).unwrap().parse::().unwrap_or(0)) + Duration::try_seconds(reversed.next().unwrap().parse::().unwrap_or(0)) .unwrap_or_default(); if let Some(mins) = reversed.nth(1) { duration = duration @@ -398,7 +398,7 @@ fn match_pair(pair: &Pair, inputs: &mut Inputs) { .as_mut() .unwrap() .push(SActor::from_user_string( - pair.clone().into_inner().nth(0).unwrap().as_str(), + pair.clone().into_inner().next().unwrap().as_str(), )); } Rule::group => { @@ -892,10 +892,10 @@ pub fn main(storage: &Storage) -> Result> { if let Some(setgid) = cred_setgid { task.as_ref().borrow_mut().cred.setgid = Some(setgid); } - return Ok(true); + Ok(true) } Err(e) => { - return Err(e); + Err(e) } } } @@ -1125,7 +1125,7 @@ pub fn main(storage: &Storage) -> Result> { } => match storage { Storage::JSON(rconfig) => { perform_on_target_opt(rconfig, role_id, task_id, |opt: Rc>| { - opt.as_ref().borrow_mut().bounding = Some(options_bounding.clone()); + opt.as_ref().borrow_mut().bounding = Some(options_bounding); Ok(()) })?; Ok(true) @@ -1164,10 +1164,10 @@ pub fn main(storage: &Storage) -> Result> { let path = binding.path.as_mut().unwrap_or(&mut default_path); match setlist_type { Some(SetListType::WhiteList) => { - path.add = options_path.split(":").map(|s| s.to_string()).collect(); + path.add = options_path.split(':').map(|s| s.to_string()).collect(); } Some(SetListType::BlackList) => { - path.sub = options_path.split(":").map(|s| s.to_string()).collect(); + path.sub = options_path.split(':').map(|s| s.to_string()).collect(); } _ => { return Err("Unknown setlist type".into()); @@ -1257,28 +1257,26 @@ fn perform_on_target_opt( if let Some(task_id) = task_id { if let Some(task) = role.as_ref().borrow().task(&task_id) { if let Some(options) = &task.as_ref().borrow_mut().options { - return exec_on_opt(options.clone()); + exec_on_opt(options.clone()) } else { let options = Rc::new(RefCell::new(Opt::default())); let ret = exec_on_opt(options.clone()); task.as_ref().borrow_mut().options = Some(options); - return ret; + ret } } else { - return Err("Task not found".into()); + Err("Task not found".into()) } + } else if let Some(options) = &role.as_ref().borrow_mut().options { + exec_on_opt(options.clone()) } else { - if let Some(options) = &role.as_ref().borrow_mut().options { - return exec_on_opt(options.clone()); - } else { - let options = Rc::new(RefCell::new(Opt::default())); - let ret = exec_on_opt(options.clone()); - role.as_ref().borrow_mut().options = Some(options); - return ret; - } + let options = Rc::new(RefCell::new(Opt::default())); + let ret = exec_on_opt(options.clone()); + role.as_ref().borrow_mut().options = Some(options); + ret } } else { - return Err("Role not found".into()); + Err("Role not found".into()) } } else { return exec_on_opt(config.options.as_ref().unwrap().clone()); @@ -1352,15 +1350,13 @@ fn list_task( } else { return Err("Task not found".into()); } + } else if options { + println!( + "{}", + serde_json::to_string_pretty(&OptStack::from_role(role.clone()).to_opt())? + ); } else { - if options { - println!( - "{}", - serde_json::to_string_pretty(&OptStack::from_role(role.clone()).to_opt())? - ); - } else { - print_role(&role, &role_type.unwrap_or(RoleType::All)); - } + print_role(role, &role_type.unwrap_or(RoleType::All)); } Ok(()) } diff --git a/src/database/finder.rs b/src/database/finder.rs index 0e4f3417..979d267b 100644 --- a/src/database/finder.rs +++ b/src/database/finder.rs @@ -327,12 +327,10 @@ fn final_path(path: &String) -> PathBuf { let result; if let Ok(cannon_path) = std::fs::canonicalize(path) { result = cannon_path; + } else if let Some(env_path) = find_from_envpath(&path.parse().expect("The path is not valid")) { + result = env_path } else { - if let Some(env_path) = find_from_envpath(&path.parse().expect("The path is not valid")) { - result = env_path - } else { - result = path.parse().expect("The path is not valid"); - } + result = path.parse().expect("The path is not valid"); } result .to_str() @@ -513,14 +511,12 @@ fn get_setuid_min( } else { SetuidMin::SetuidRootSetgid(groups_len(setgid)) } + } else if groups_contains_root(setgid) { + SetuidMin::SetuidNotrootSetgidRoot(groups_len(setgid)) + } else if setgid.is_none() || groups_len(setgid) == 0 { + SetuidMin::Setuid } else { - if groups_contains_root(setgid) { - SetuidMin::SetuidNotrootSetgidRoot(groups_len(setgid)) - } else if setgid.is_none() || groups_len(setgid) == 0 { - SetuidMin::Setuid - } else { - SetuidMin::SetuidSetgid(groups_len(setgid)) - } + SetuidMin::SetuidSetgid(groups_len(setgid)) } } else { // root is a user @@ -552,8 +548,7 @@ impl TaskMatcher for Rc> { .borrow() .cred .capabilities - .as_ref() - .and_then(|caps| Some(caps.to_capset())); + .as_ref().map(|caps| caps.to_capset()); score.caps_min = get_caps_min(&capset); score.security_min = get_security_min(&self.as_ref().borrow().options); let setuid = &self.as_ref().borrow().cred.setuid; @@ -581,7 +576,7 @@ impl TaskMatcher for SCommands { let min_score: CmdMin; let mut settings = ExecSettings::new(); // if the command is forbidden, we return NoMatch - let is_forbidden = get_cmd_min(&input_command, &self.sub); + let is_forbidden = get_cmd_min(input_command, &self.sub); if !is_forbidden.is_empty() { debug!("Command is forbidden"); return Err(MatchError::NoMatch); @@ -589,7 +584,7 @@ impl TaskMatcher for SCommands { // otherwise, we check if behavior is No command allowed by default if get_default_behavior(&self.default_behavior).is_none() { // if the behavior is No command by default, we check if the command is allowed explicitly. - min_score = get_cmd_min(&input_command, &self.add); + min_score = get_cmd_min(input_command, &self.add); if min_score.is_empty() { return Err(MatchError::NoMatch); } @@ -903,8 +898,8 @@ mod tests { #[test] fn test_match_args() { let result = match_args( - &vec!["-l".to_string(), "-a".to_string()], - &vec!["-l".to_string(), "-a".to_string()], + &["-l".to_string(), "-a".to_string()], + &["-l".to_string(), "-a".to_string()], ); assert!(result.is_ok()); assert_eq!(result.unwrap(), CmdMin::Match); @@ -913,8 +908,8 @@ mod tests { #[test] fn test_match_command_line() { let result = match_command_line( - &vec!["/bin/ls".to_string(), "-l".to_string(), "-a".to_string()], - &vec!["/bin/ls".to_string(), "-l".to_string(), "-a".to_string()], + &["/bin/ls".to_string(), "-l".to_string(), "-a".to_string()], + &["/bin/ls".to_string(), "-l".to_string(), "-a".to_string()], ); assert_eq!(result, CmdMin::Match); } @@ -922,12 +917,10 @@ mod tests { #[test] fn test_get_cmd_min() { let result = get_cmd_min( - &vec!["/bin/ls".to_string(), "-l".to_string(), "-a".to_string()], - &vec![ - "/bin/l*".into(), + &["/bin/ls".to_string(), "-l".to_string(), "-a".to_string()], + &["/bin/l*".into(), "/bin/ls .*".into(), - "/bin/ls -l -a".into(), - ], + "/bin/ls -l -a".into()], ); assert_eq!(result, CmdMin::Match); } @@ -1123,12 +1116,12 @@ mod tests { .as_ref() .borrow_mut() .actors - .push(SActor::from_user_string("root".into())); + .push(SActor::from_user_string("root")); role1 .as_ref() .borrow_mut() .actors - .push(SActor::from_user_string("root".into())); + .push(SActor::from_user_string("root")); r0_task0 .as_ref() diff --git a/src/database/migration.rs b/src/database/migration.rs index 1cb722f1..93c2b173 100644 --- a/src/database/migration.rs +++ b/src/database/migration.rs @@ -128,7 +128,7 @@ impl Migration { ) -> Result> where { Self::migrate_from( - &version, + version, &Version::parse(PACKAGE_VERSION).unwrap(), doc, migrations, diff --git a/src/database/mod.rs b/src/database/mod.rs index 7323f0c1..eed23900 100644 --- a/src/database/mod.rs +++ b/src/database/mod.rs @@ -3,12 +3,12 @@ use std::{cell::RefCell, error::Error, rc::Rc}; use crate::common::config::save_settings; use crate::common::util::toggle_lock_config; use crate::common::version::PACKAGE_VERSION; -use crate::rc_refcell; + use chrono::Duration; use linked_hash_set::LinkedHashSet; use serde::{de, Deserialize, Serialize}; use tracing::debug; -use tracing::warn; + use self::{migration::Migration, options::EnvKey, structs::SConfig, version::Versioning}; @@ -29,9 +29,9 @@ pub mod wrapper; pub fn make_weak_config(config: &Rc>) { for role in &config.as_ref().borrow().roles { - role.as_ref().borrow_mut()._config = Some(Rc::downgrade(&config)); + role.as_ref().borrow_mut()._config = Some(Rc::downgrade(config)); for task in &role.as_ref().borrow().tasks { - task.as_ref().borrow_mut()._role = Some(Rc::downgrade(&role)); + task.as_ref().borrow_mut()._role = Some(Rc::downgrade(role)); } } } diff --git a/src/database/options.rs b/src/database/options.rs index f3c5b8e1..b6e55bf4 100644 --- a/src/database/options.rs +++ b/src/database/options.rs @@ -20,8 +20,10 @@ use super::{ }; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Default)] pub enum Level { None, + #[default] Default, Global, Role, @@ -40,26 +42,26 @@ pub enum OptType { #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, EnumIs, Display, Clone, Copy)] #[serde(rename_all = "lowercase")] +#[derive(Default)] pub enum PathBehavior { Delete, KeepSafe, KeepUnsafe, + #[default] Inherit, } #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, EnumIs, Clone, Copy, Display)] #[serde(rename_all = "lowercase")] +#[derive(Default)] pub enum TimestampType { + #[default] PPID, TTY, UID, } -impl Default for TimestampType { - fn default() -> Self { - TimestampType::PPID - } -} + #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] pub struct STimeout { @@ -113,9 +115,11 @@ pub struct SPathOptions { #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, EnumIs, Display, Clone, Copy)] #[serde(rename_all = "lowercase")] +#[derive(Default)] pub enum EnvBehavior { Delete, Keep, + #[default] Inherit, } @@ -164,16 +168,20 @@ pub struct SEnvOptions { #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, EnumIs, Display, Clone, Copy)] #[serde(rename_all = "lowercase")] +#[derive(Default)] pub enum SBounding { Strict, Ignore, + #[default] Inherit, } #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, EnumIs, Display, Clone, Copy)] #[serde(rename_all = "kebab-case")] +#[derive(Default)] pub enum SPrivileged { Privileged, + #[default] User, Inherit, } @@ -201,35 +209,15 @@ pub struct Opt { pub level: Level, } -impl Default for Level { - fn default() -> Self { - Level::Default - } -} -impl Default for EnvBehavior { - fn default() -> Self { - EnvBehavior::Inherit - } -} -impl Default for SBounding { - fn default() -> Self { - SBounding::Inherit - } -} -impl Default for SPrivileged { - fn default() -> Self { - SPrivileged::User - } -} -impl Default for PathBehavior { - fn default() -> Self { - PathBehavior::Inherit - } -} + + + + + impl Opt { pub fn new(level: Level) -> Self { @@ -308,9 +296,9 @@ impl PartialEq for EnvKey { } } -impl Into for EnvKey { - fn into(self) -> String { - self.value +impl From for String { + fn from(val: EnvKey) -> Self { + val.value } } @@ -376,7 +364,7 @@ impl EnvSet for LinkedHashSet { self.iter().any(|s| { Regex::new(&format!( "^{}$", - wildcarded.value.replace("*", ".*").replace("?", ".") + wildcarded.value.replace('*', ".*").replace('?', ".") )) // convert to regex .unwrap() .is_match(s.value.as_bytes()) @@ -501,7 +489,7 @@ impl OptStack { opt.root = Some(SPrivileged::User); opt.bounding = Some(SBounding::Strict); let mut env = SEnvOptions::new(EnvBehavior::Delete); - env.check = vec!["TZ".into(), "LOGNAME".into(), "LOGIN".into(), "USER".into()] + env.check = ["TZ".into(), "LOGNAME".into(), "LOGIN".into(), "USER".into()] .iter() .cloned() .collect(); @@ -587,7 +575,7 @@ impl OptStack { is_safe => std::env::vars() .find_map(|(key, value)| if key == "PATH" { Some(value) } else { None }) .unwrap_or(String::new()) - .split(":") + .split(':') .filter(|s| { !final_sub.as_ref().borrow().contains(*s) && (!is_safe.is_keep_safe() || PathBuf::from(s).exists()) @@ -725,12 +713,12 @@ impl OptStack { // policy is to delete, so we add whitelist and remove blacklist final_keep = final_keep .union(&p.keep) - .filter(|e| !p.check.env_matches(&e) || !p.delete.env_matches(e)) + .filter(|e| !p.check.env_matches(e) || !p.delete.env_matches(e)) .cloned() .collect(); final_check = final_check .union(&p.check) - .filter(|e| !p.delete.env_matches(&e)) + .filter(|e| !p.delete.env_matches(e)) .cloned() .collect(); p.default_behavior @@ -739,12 +727,12 @@ impl OptStack { //policy is to keep, so we remove blacklist and add whitelist final_delete = final_delete .union(&p.delete) - .filter(|e| !p.keep.env_matches(&e) || !p.check.env_matches(&e)) + .filter(|e| !p.keep.env_matches(e) || !p.check.env_matches(e)) .cloned() .collect(); final_check = final_check .union(&p.check) - .filter(|e| !p.keep.env_matches(&e)) + .filter(|e| !p.keep.env_matches(e)) .cloned() .collect(); p.default_behavior @@ -753,23 +741,23 @@ impl OptStack { if final_behavior.is_delete() { final_keep = final_keep .union(&p.keep) - .filter(|e| !p.delete.env_matches(&e) || !p.check.env_matches(&e)) + .filter(|e| !p.delete.env_matches(e) || !p.check.env_matches(e)) .cloned() .collect(); final_check = final_check .union(&p.check) - .filter(|e| !p.delete.env_matches(&e)) + .filter(|e| !p.delete.env_matches(e)) .cloned() .collect(); } else { final_delete = final_delete .union(&p.delete) - .filter(|e| !p.keep.env_matches(&e) || !p.check.env_matches(&e)) + .filter(|e| !p.keep.env_matches(e) || !p.check.env_matches(e)) .cloned() .collect(); final_check = final_check .union(&p.check) - .filter(|e| !p.keep.env_matches(&e)) + .filter(|e| !p.keep.env_matches(e)) .cloned() .collect(); } @@ -889,11 +877,7 @@ mod tests { let options = OptStack::from_role(config.as_ref().borrow().roles[0].clone()); let res: Option<(Level, SPathOptions)> = options.find_in_options(|opt| { - if let Some(value) = opt.path.clone() { - Some((opt.level, value)) - } else { - None - } + opt.path.clone().map(|value| (opt.level, value)) }); assert_eq!(res, Some((Level::Role, role_path))); } @@ -915,7 +899,7 @@ mod tests { config_role.path = Some(role_path); as_borrow_mut!(role).options = Some(rc_refcell!(config_role)); as_borrow_mut!(config).roles.push(role); - let options = OptStack::from_role(config.as_ref().borrow().roles.get(0).unwrap().clone()); + let options = OptStack::from_role(config.as_ref().borrow().roles.first().unwrap().clone()); let res = options.calculate_path(); assert_eq!(res, "path2:path1"); } diff --git a/src/database/structs.rs b/src/database/structs.rs index a2ceb7b6..89a46177 100644 --- a/src/database/structs.rs +++ b/src/database/structs.rs @@ -146,8 +146,10 @@ pub struct SCredentials { #[derive(Serialize, Deserialize, PartialEq, Eq, Display, Debug, EnumIs)] #[serde(rename_all = "lowercase")] +#[derive(Default)] pub enum SetBehavior { All, + #[default] None, } @@ -257,11 +259,7 @@ impl Default for SCommands { } } -impl Default for SetBehavior { - fn default() -> Self { - SetBehavior::None - } -} + impl Default for SCapabilities { fn default() -> Self { @@ -475,8 +473,7 @@ impl PartialEq for SActorType { match self { SActorType::Name(name) => name == other, SActorType::Id(id) => other - .parse() - .and_then(|oid: u32| Ok(oid == *id)) + .parse().map(|oid: u32| oid == *id) .unwrap_or(false), } } @@ -543,9 +540,9 @@ impl FromIterator for SGroups { } } -impl Into> for SGroups { - fn into(self) -> Vec { - match self { +impl From for Vec { + fn from(val: SGroups) -> Self { + match val { SGroups::Single(group) => vec![group], SGroups::Multiple(groups) => groups, } @@ -555,13 +552,13 @@ impl Into> for SGroups { impl SActorType { pub fn into_group(&self) -> Result, Errno> { match self { - SActorType::Name(name) => Group::from_name(&name), + SActorType::Name(name) => Group::from_name(name), SActorType::Id(id) => Group::from_gid(id.to_owned().into()), } } pub fn into_user(&self) -> Result, Errno> { match self { - SActorType::Name(name) => User::from_name(&name), + SActorType::Name(name) => User::from_name(name), SActorType::Id(id) => User::from_uid(id.to_owned().into()), } } @@ -582,10 +579,8 @@ impl PartialOrd> for SGroups { if group == &other[0] { return Some(Ordering::Equal); } - } else { - if other.iter().any(|x| group == x) { - return Some(Ordering::Less); - } + } else if other.iter().any(|x| group == x) { + return Some(Ordering::Less); } } SGroups::Multiple(groups) => { @@ -597,10 +592,8 @@ impl PartialOrd> for SGroups { if groups.iter().all(|x| other.iter().any(|y| x == y)) { return Some(Ordering::Less); } - } else { - if other.iter().all(|x| groups.iter().any(|y| y == x)) { - return Some(Ordering::Greater); - } + } else if other.iter().all(|x| groups.iter().any(|y| y == x)) { + return Some(Ordering::Greater); } } } @@ -608,9 +601,9 @@ impl PartialOrd> for SGroups { } } -impl Into> for SGroups { - fn into(self) -> Vec { - match self { +impl From for Vec { + fn from(val: SGroups) -> Self { + match val { SGroups::Single(group) => vec![group.into_group().unwrap().unwrap()], SGroups::Multiple(groups) => groups .into_iter() diff --git a/src/mod.rs b/src/mod.rs index e4863163..2d454797 100644 --- a/src/mod.rs +++ b/src/mod.rs @@ -17,7 +17,7 @@ pub fn subsribe(tool: &str) { let identity = CString::new(tool).unwrap(); let options = syslog_tracing::Options::LOG_PID; let facility = syslog_tracing::Facility::Auth; - let syslog = syslog_tracing::Syslog::new(identity, options, facility).unwrap(); + let _syslog = syslog_tracing::Syslog::new(identity, options, facility).unwrap(); tracing_subscriber::fmt() .with_max_level(Level::DEBUG) .with_file(true) diff --git a/src/plugin/hashchecker.rs b/src/plugin/hashchecker.rs index 8a71498f..f0111d05 100644 --- a/src/plugin/hashchecker.rs +++ b/src/plugin/hashchecker.rs @@ -66,7 +66,7 @@ fn complex_command_parse( Ok(checker) => { let path; if let SCommand::Simple(command) = &checker.command { - let opath = find_executable_in_path(&command); + let opath = find_executable_in_path(command); if opath.is_none() { return Err("Command not found".into()); } @@ -74,15 +74,15 @@ fn complex_command_parse( } else { return Err("Invalid command".into()); } - return if compute( + if compute( &checker.hash_type, - &String::from_utf8(std::fs::read(&path)?)?, + &String::from_utf8(std::fs::read(path)?)?, ) == compute(&checker.hash_type, &checker.hash) { parse_conf_command(&checker.command) } else { Err("Hashes do not match".into()) - }; + } } Err(e) => Err(Box::new(e)), } diff --git a/src/plugin/hierarchy.rs b/src/plugin/hierarchy.rs index baf4f015..c1f57242 100644 --- a/src/plugin/hierarchy.rs +++ b/src/plugin/hierarchy.rs @@ -16,8 +16,7 @@ pub struct Parents(Vec); fn get_parents(role: &SRole) -> Option> { role._extra_fields - .get("parents") - .and_then(|parents| Some(serde_json::from_value::(parents.clone()))) + .get("parents").map(|parents| serde_json::from_value::(parents.clone())) } fn find_in_parents( diff --git a/src/plugin/ssd.rs b/src/plugin/ssd.rs index e1c9acd3..9ba51db1 100644 --- a/src/plugin/ssd.rs +++ b/src/plugin/ssd.rs @@ -132,8 +132,7 @@ fn check_separation_of_duty(role: &SRole, actor: &Cred) -> PluginResult { fn get_ssd_entry(role: &SRole) -> Option> { role._extra_fields - .get("ssd") - .and_then(|ssd| Some(serde_json::from_value::(ssd.clone()))) + .get("ssd").map(|ssd| serde_json::from_value::(ssd.clone())) } pub fn register() { @@ -156,21 +155,21 @@ mod tests { fn test_user_contained_in() { let user = User::from_uid(0.into()).unwrap().unwrap(); let actors = vec![SActor::from_user_id(0)]; - assert_eq!(user_contained_in(&user, &actors), true); + assert!(user_contained_in(&user, &actors)); } #[test] fn test_group_contained_in() { let group = Group::from_gid(0.into()).unwrap().unwrap(); let actors = vec![SActor::from_group_id(0)]; - assert_eq!(group_contained_in(&group, &actors), true); + assert!(group_contained_in(&group, &actors)); } #[test] fn test_groups_subset_of() { let groups = vec![Group::from_gid(0.into()).unwrap().unwrap()]; let actors = vec![SActor::from_group_id(0)]; - assert_eq!(groups_subset_of(&groups, &actors), true); + assert!(groups_subset_of(&groups, &actors)); } #[test] @@ -178,7 +177,7 @@ mod tests { let user = User::from_uid(0.into()).unwrap().unwrap(); let sconfig = SConfig::default(); let roles = vec!["role1".to_string()]; - assert_eq!(user_is_forbidden(&user, &roles, &sconfig), false); + assert!(!user_is_forbidden(&user, &roles, &sconfig)); } #[test] @@ -190,7 +189,7 @@ mod tests { role.actors.push(SActor::from_group_id(0)); sconfig.roles.push(rc_refcell!(role)); let roles = vec!["role1".to_string()]; - assert_eq!(groups_are_forbidden(&groups, &roles, &sconfig), true); + assert!(groups_are_forbidden(&groups, &roles, &sconfig)); } #[test] diff --git a/src/sr/main.rs b/src/sr/main.rs index ea3f37ab..ed130473 100644 --- a/src/sr/main.rs +++ b/src/sr/main.rs @@ -167,19 +167,19 @@ fn from_json_execution_settings( user: &Cred, ) -> Result> { match (&args.role, &args.task) { - (None, None) => config.matches(&user, &args.command).map_err(|m| m.into()), + (None, None) => config.matches(user, &args.command).map_err(|m| m.into()), (Some(role), None) => as_borrow!(config) - .role(&role) + .role(role) .expect("Permission Denied") - .matches(&user, &args.command) + .matches(user, &args.command) .map_err(|m| m.into()), (Some(role), Some(task)) => as_borrow!(config) .task( - &role, + role, &common::database::structs::IdTask::Name(task.to_string()), ) .expect("Permission Denied") - .matches(&user, &args.command) + .matches(user, &args.command) .map_err(|m| m.into()), (None, Some(_)) => Err("You must specify a role to designate a task".into()), } @@ -191,9 +191,9 @@ fn main() -> Result<(), Box> { register_plugins(); let args = add_dashes(); let args = Cli::parse_from(args.iter()); - read_effective(true).expect(&cap_effective_error("dac_read")); + read_effective(true).unwrap_or_else(|_| { panic!("{}", cap_effective_error("dac_read")) }); let settings = config::get_settings().expect("Failed to get settings"); - read_effective(false).expect(&cap_effective_error("dac_read")); + read_effective(false).unwrap_or_else(|_| { panic!("{}", cap_effective_error("dac_read")) }); let user = User::from_uid(getuid()) .expect("Failed to get user") .expect("Failed to get user"); @@ -231,7 +231,7 @@ fn main() -> Result<(), Box> { ppid, }; - dac_override_effective(true).expect(&cap_effective_error("dac_override")); + dac_override_effective(true).unwrap_or_else(|_| { panic!("{}", cap_effective_error("dac_override")) }); let config = match settings.clone().as_ref().borrow().storage.method { config::StorageMethod::JSON => { Storage::JSON(read_json_config(settings).expect("Failed to read config")) @@ -249,7 +249,7 @@ fn main() -> Result<(), Box> { let optstack = &execcfg.opt; check_auth(optstack, &config, &user, &args.prompt)?; - dac_override_effective(false).expect(&cap_effective_error("dac_override")); + dac_override_effective(false).unwrap_or_else(|_| { panic!("{}", cap_effective_error("dac_override")) }); if !taskmatch.fully_matching() { println!("You are not allowed to execute this command, this incident will be reported."); @@ -264,7 +264,7 @@ fn main() -> Result<(), Box> { println!("Role: {}", execcfg.role().as_ref().borrow().name); println!( "Task: {}", - execcfg.task().as_ref().borrow().name.to_string() + execcfg.task().as_ref().borrow().name ); println!( "With capabilities: {}", @@ -302,7 +302,7 @@ fn main() -> Result<(), Box> { } } SGroups::Multiple(g) => { - let res = g.get(0).unwrap().into_group().unwrap_or(None); + let res = g.first().unwrap().into_group().unwrap_or(None); if let Some(group) = res { Some(group.gid.as_raw()) } else { @@ -331,16 +331,16 @@ fn main() -> Result<(), Box> { } }); - setgid_effective(true).expect(&cap_effective_error("setgid")); - setuid_effective(true).expect(&cap_effective_error("setuid")); - capctl::cap_set_ids(uid, gid, groups.as_ref().map(|g| g.as_slice())) + setgid_effective(true).unwrap_or_else(|_| { panic!("{}", cap_effective_error("setgid")) }); + setuid_effective(true).unwrap_or_else(|_| { panic!("{}", cap_effective_error("setuid")) }); + capctl::cap_set_ids(uid, gid, groups.as_deref()) .expect("Failed to set ids"); - setgid_effective(false).expect(&cap_effective_error("setgid")); - setuid_effective(false).expect(&cap_effective_error("setuid")); + setgid_effective(false).unwrap_or_else(|_| { panic!("{}", cap_effective_error("setgid")) }); + setuid_effective(false).unwrap_or_else(|_| { panic!("{}", cap_effective_error("setuid")) }); //set capabilities if let Some(caps) = execcfg.caps { - setpcap_effective(true).expect(&cap_effective_error("setpcap")); + setpcap_effective(true).unwrap_or_else(|_| { panic!("{}", cap_effective_error("setpcap")) }); let mut capstate = CapState::empty(); if !optstack.get_bounding().1.is_ignore() { for cap in (!caps).iter() { @@ -353,15 +353,15 @@ fn main() -> Result<(), Box> { for cap in caps.iter() { capctl::ambient::raise(cap).expect("Failed to set ambiant cap"); } - setpcap_effective(false).expect(&cap_effective_error("setpcap")); + setpcap_effective(false).unwrap_or_else(|_| { panic!("{}", cap_effective_error("setpcap")) }); } else { - setpcap_effective(true).expect(&cap_effective_error("setpcap")); + setpcap_effective(true).unwrap_or_else(|_| { panic!("{}", cap_effective_error("setpcap")) }); if !optstack.get_bounding().1.is_ignore() { capctl::bounding::clear().expect("Failed to clear bounding cap"); } let capstate = CapState::empty(); capstate.set_current().expect("Failed to set current cap"); - setpcap_effective(false).expect(&cap_effective_error("setpcap")); + setpcap_effective(false).unwrap_or_else(|_| { panic!("{}", cap_effective_error("setpcap")) }); } //execute command @@ -401,7 +401,7 @@ fn check_auth( ) -> Result<(), Box> { let timeout = optstack.get_timeout().1; let is_valid = match config { - Storage::JSON(_) => timeout::is_valid(&user, &user, &timeout), + Storage::JSON(_) => timeout::is_valid(user, user, &timeout), }; debug!("need to re-authenticate : {}", !is_valid); if !is_valid { @@ -416,7 +416,7 @@ fn check_auth( } match config { Storage::JSON(_) => { - timeout::update_cookie(&user, &user, &timeout)?; + timeout::update_cookie(user, user, &timeout)?; } } Ok(()) diff --git a/src/sr/timeout.rs b/src/sr/timeout.rs index 70394e18..c4151608 100644 --- a/src/sr/timeout.rs +++ b/src/sr/timeout.rs @@ -283,10 +283,10 @@ mod test { #[test] fn test_lockfile() { let lockpath = std::path::Path::new("/tmp/test.lock"); - assert!(wait_for_lockfile(&lockpath).is_ok()); - write_lockfile(&lockpath); - assert!(wait_for_lockfile(&lockpath).is_err()); - std::fs::remove_file(&lockpath).unwrap(); - assert!(wait_for_lockfile(&lockpath).is_ok()); + assert!(wait_for_lockfile(lockpath).is_ok()); + write_lockfile(lockpath); + assert!(wait_for_lockfile(lockpath).is_err()); + std::fs::remove_file(lockpath).unwrap(); + assert!(wait_for_lockfile(lockpath).is_ok()); } }