Skip to content

Commit

Permalink
fix: some other clippy and fmt the code (#118)
Browse files Browse the repository at this point in the history
* fix: clippy manual_flatten
* fix: regrex clippy
* fix: clippy if_same_then_else
* fix: some of clippy
* fix: others and fmt
  • Loading branch information
yihong0618 authored Feb 20, 2025
1 parent b1a5782 commit 3714d68
Show file tree
Hide file tree
Showing 19 changed files with 80 additions and 95 deletions.
10 changes: 0 additions & 10 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -110,24 +110,14 @@ version = "0.2"
result_large_err = "allow"
ptr_arg = "allow"
let_and_return = "allow"
if_same_then_else = "allow"
should_implement_trait = "allow"
new_without_default = "allow"
vec_init_then_push = "allow"
nonminimal_bool = "allow"
cmp_owned = "allow"
field_reassign_with_default = "allow"
await_holding_lock = "allow"
manual_strip = "allow"
comparison_chain = "allow"
unnecessary_get_then_check = "allow"
too_many_arguments = "allow"
module_inception = "allow"
unnecessary_unwrap = "allow"
collapsible_match = "allow"
large_enum_variant = "allow"
manual_flatten = "allow"
regex_creation_in_loops = "allow"
unnecessary_map_or = "allow"

[[bin]]
Expand Down
7 changes: 5 additions & 2 deletions src/cli/command/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ use serde_json::{json, Map, Value};

use crate::{api::secret::Secret, errors::RvError, rv_error_string};

lazy_static! {
static ref UNDERSCORE_REGEX: Regex = Regex::new(r"_(\w)").unwrap();
}

#[derive(Args)]
#[group(required = false, multiple = true)]
pub struct OutputOptions {
Expand Down Expand Up @@ -133,8 +137,7 @@ pub fn convert_keys(value: &Value) -> Value {
Value::Object(map) => {
let mut new_map = Map::new();
for (key, value) in map {
let new_key = Regex::new(r"_(\w)")
.unwrap()
let new_key = UNDERSCORE_REGEX
.replace_all(&key.to_string(), |caps: &regex::Captures| {
let captured_char = caps.get(1).unwrap().as_str();
format!(" {}", captured_char.to_ascii_uppercase())
Expand Down
5 changes: 1 addition & 4 deletions src/cli/command/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,6 @@ impl Server {

let log_file = std::fs::OpenOptions::new()
.read(true)

.append(true)
.create(true)
.truncate(false)
Expand Down Expand Up @@ -213,9 +212,7 @@ impl Server {
}

if listener.tls_require_and_verify_client_cert {
builder.set_verify_callback(SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT, move |p, _x| {
p
});
builder.set_verify_callback(SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT, move |p, _x| p);

if !listener.tls_client_ca_file.is_empty() {
let mut store = X509StoreBuilder::new()?;
Expand Down
20 changes: 9 additions & 11 deletions src/cli/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,18 +262,16 @@ fn load_config_dir(dir: &str) -> Result<Config, RvError> {
let mut paths: Vec<String> = Vec::new();

if let Ok(entries) = fs::read_dir(dir) {
for entry in entries {
if let Ok(entry) = entry {
let path = entry.path();
if !path.is_file() {
continue;
}
for entry in entries.flatten() {
let path = entry.path();
if !path.is_file() {
continue;
}

if let Some(ext) = path.extension() {
if ext == "hcl" || ext == "json" {
let filename = path.to_string_lossy().into_owned();
paths.push(filename);
}
if let Some(ext) = path.extension() {
if ext == "hcl" || ext == "json" {
let filename = path.to_string_lossy().into_owned();
paths.push(filename);
}
}
}
Expand Down
10 changes: 4 additions & 6 deletions src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -396,11 +396,7 @@ impl Core {

// Perform initial setup
self.hmac_key = self.barrier.derive_hmac_key()?;
self.mounts.load_or_default(
self.barrier.as_storage(),
Some(&self.hmac_key),
self.mount_entry_hmac_level,
)?;
self.mounts.load_or_default(self.barrier.as_storage(), Some(&self.hmac_key), self.mount_entry_hmac_level)?;

self.setup_mounts()?;

Expand Down Expand Up @@ -436,7 +432,9 @@ impl Core {
}

if err.is_none() {
if let Err(e) = self.handle_post_route_phase(&handlers, req, &mut resp).await { err = Some(e) }
if let Err(e) = self.handle_post_route_phase(&handlers, req, &mut resp).await {
err = Some(e)
}
}
}

Expand Down
6 changes: 2 additions & 4 deletions src/http/sys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,8 @@ async fn sys_init_put_request_handler(
let mut core = core.write()?;
let result = core.init(&seal_config)?;

let resp = InitResponse {
keys: result.secret_shares.iter().map(hex::encode).collect(),
root_token: result.root_token,
};
let resp =
InitResponse { keys: result.secret_shares.iter().map(hex::encode).collect(), root_token: result.root_token };

Ok(response_json_ok(None, resp))
}
Expand Down
4 changes: 1 addition & 3 deletions src/logical/field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,7 @@ impl FieldTrait for Value {
}

if let Some(secs_str) = self.as_str() {
if secs_str.parse::<u64>().ok().is_some() {
return true;
} else if parse_duration(secs_str).is_ok() {
if secs_str.parse::<u64>().ok().is_some() || parse_duration(secs_str).is_ok() {
return true;
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/metrics/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub async fn metrics_midleware(
let path = req.path().to_string();
let method = match *req.method() {
Method::GET => MetricsMethod::GET,
_ if req.method().to_string() == "LIST" => MetricsMethod::LIST,
_ if *req.method() == "LIST" => MetricsMethod::LIST,
Method::POST => MetricsMethod::POST,
Method::PUT => MetricsMethod::PUT,
Method::DELETE => MetricsMethod::DELETE,
Expand Down
3 changes: 1 addition & 2 deletions src/modules/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,8 +261,7 @@ impl AuthModule {

pub fn load_auth(&self, hmac_key: Option<&[u8]>, hmac_level: MountEntryHMACLevel) -> Result<(), RvError> {
let router_store = self.router_store.read()?;
if router_store.mounts.load(self.barrier.as_storage(), AUTH_CONFIG_PATH, hmac_key, hmac_level).is_err()
{
if router_store.mounts.load(self.barrier.as_storage(), AUTH_CONFIG_PATH, hmac_key, hmac_level).is_err() {
router_store.mounts.set_default(DEFAULT_AUTH_MOUNTS.to_vec(), hmac_key)?;
router_store.mounts.persist(AUTH_CONFIG_PATH, self.barrier.as_storage())?;
}
Expand Down
49 changes: 24 additions & 25 deletions src/modules/credential/approle/path_role.rs
Original file line number Diff line number Diff line change
Expand Up @@ -889,28 +889,29 @@ or 'secret_id_ttl' option on the role, and/or the backend mount's maximum TTL va
}

pub fn role_paths(&self) -> Vec<Path> {
let mut paths: Vec<Path> = Vec::with_capacity(21);
paths.push(self.role_path());
paths.push(self.role_name_path());
paths.push(self.role_policies_path());
paths.push(self.role_local_secret_ids_path());
paths.push(self.role_bound_cidr_list_path());
paths.push(self.role_secret_id_bound_cidrs_path());
paths.push(self.role_token_bound_cidrs_path());
paths.push(self.role_bind_secret_id_path());
paths.push(self.role_secret_id_num_uses_path());
paths.push(self.role_secret_id_ttl_path());
paths.push(self.role_period_path());
paths.push(self.role_token_num_uses_path());
paths.push(self.role_token_ttl_path());
paths.push(self.role_token_max_ttl_path());
paths.push(self.role_role_id_path());
paths.push(self.role_secret_id_path());
paths.push(self.role_secret_id_lookup_path());
paths.push(self.role_secret_id_destroy_path());
paths.push(self.role_secret_id_accessor_lookup_path());
paths.push(self.role_secret_id_accessor_destroy_path());
paths.push(self.role_custom_secret_id_path());
let paths: Vec<Path> = vec![
self.role_path(),
self.role_name_path(),
self.role_policies_path(),
self.role_local_secret_ids_path(),
self.role_bound_cidr_list_path(),
self.role_secret_id_bound_cidrs_path(),
self.role_token_bound_cidrs_path(),
self.role_bind_secret_id_path(),
self.role_secret_id_num_uses_path(),
self.role_secret_id_ttl_path(),
self.role_period_path(),
self.role_token_num_uses_path(),
self.role_token_ttl_path(),
self.role_token_max_ttl_path(),
self.role_role_id_path(),
self.role_secret_id_path(),
self.role_secret_id_lookup_path(),
self.role_secret_id_destroy_path(),
self.role_secret_id_accessor_lookup_path(),
self.role_secret_id_accessor_destroy_path(),
self.role_custom_secret_id_path(),
];
paths
}
}
Expand Down Expand Up @@ -1897,9 +1898,7 @@ impl AppRoleBackendInner {
return Err(RvError::ErrResponse("num_uses cannot be negative".to_string()));
}
// If the specified num_uses is higher than the role's secret_id_num_uses, throw an error rather than implicitly overriding
if (num_uses == 0 && role.secret_id_num_uses > 0)
|| (role.secret_id_num_uses > 0 && num_uses > role.secret_id_num_uses)
{
if role.secret_id_num_uses > 0 && (num_uses == 0 || num_uses > role.secret_id_num_uses) {
return Err(RvError::ErrResponse(
"num_uses cannot be higher than the role's secret_id_num_uses".to_string(),
));
Expand Down
5 changes: 4 additions & 1 deletion src/modules/policy/acl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,10 @@ impl ACL {

if bare_mount && i == path_parts.len() - 2 {
let joined_path = segments.join("/") + "/";
if joined_path.starts_with(path) && permissions.capabilities_bitmap & Capability::Deny.to_bits() == 0 && permissions.capabilities_bitmap > 0 {
if joined_path.starts_with(path)
&& permissions.capabilities_bitmap & Capability::Deny.to_bits() == 0
&& permissions.capabilities_bitmap > 0
{
return Some(permissions.clone());
}
skip = true;
Expand Down
1 change: 1 addition & 0 deletions src/modules/policy/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use crate::{
logical::{Backend, Request, Response},
};

#[allow(clippy::module_inception)]
pub mod policy;
pub use policy::{Permissions, Policy, PolicyPathRules, PolicyType};

Expand Down
8 changes: 5 additions & 3 deletions src/modules/policy/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,9 @@ impl Permissions {
_ => return Ok(ret),
};

if self.capabilities_bitmap & cap.to_bits() == 0 && (req.operation != Operation::Write || self.capabilities_bitmap & Capability::Create.to_bits() == 0) {
if self.capabilities_bitmap & cap.to_bits() == 0
&& (req.operation != Operation::Write || self.capabilities_bitmap & Capability::Create.to_bits() == 0)
{
return Ok(ret);
}

Expand Down Expand Up @@ -453,7 +455,7 @@ impl Permissions {
return Ok(ret);
}

if self.denied_parameters.get("*").is_some() {
if self.denied_parameters.contains_key("*") {
return Ok(ret);
}

Expand All @@ -465,7 +467,7 @@ impl Permissions {
}
}

let allowed_all = self.allowed_parameters.get("*").is_some();
let allowed_all = self.allowed_parameters.contains_key("*");

if self.allowed_parameters.is_empty() || (allowed_all && self.allowed_parameters.len() == 1) {
ret.capabilities_bitmap = self.capabilities_bitmap;
Expand Down
8 changes: 2 additions & 6 deletions src/modules/policy/policy_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -400,12 +400,8 @@ impl PolicyStore {
keys.retain(|s| !NON_ASSIGNABLE_POLICIES.iter().any(|&x| s == x));
Ok(keys)
}
PolicyType::Rgp | PolicyType::Egp => {
view.get_keys()
}
_ => {
Err(rv_error_string!("invalid type of policy"))
}
PolicyType::Rgp | PolicyType::Egp => view.get_keys(),
_ => Err(rv_error_string!("invalid type of policy")),
}
}

Expand Down
3 changes: 1 addition & 2 deletions src/mount.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,7 @@ impl MountEntry {
let mut msg = format!("{}-{}-{}-{}", self.table, self.path, self.logical_type, self.description);

if let Some(options) = &self.options {
let options_btree: BTreeMap<String, String> =
options.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
let options_btree: BTreeMap<String, String> = options.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
for (key, value) in options_btree.iter() {
msg = format!("{}-{}:{}", msg, key, value);
}
Expand Down
19 changes: 12 additions & 7 deletions src/shamir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,15 +283,20 @@ impl ShamirSecret {
fn add_polynomials(a: &[u8], b: &[u8]) -> Vec<u8> {
let mut a = a.to_owned();
let mut b = b.to_owned();
if a.len() < b.len() {
let mut t = vec![0; b.len() - a.len()];
a.append(&mut t);
} else if a.len() > b.len() {
let mut t = vec![0; a.len() - b.len()];
b.append(&mut t);

match a.len().cmp(&b.len()) {
std::cmp::Ordering::Less => {
let mut t = vec![0; b.len() - a.len()];
a.append(&mut t);
}
std::cmp::Ordering::Greater => {
let mut t = vec![0; a.len() - b.len()];
b.append(&mut t);
}
std::cmp::Ordering::Equal => {}
}
let mut results: Vec<u8> = vec![];

let mut results: Vec<u8> = vec![];
for i in 0..a.len() {
results.push(ShamirSecret::gf256_add(a[i], b[i]));
}
Expand Down
4 changes: 2 additions & 2 deletions src/storage/physical/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ impl Backend for FileBackend {
for entry in entries {
let entry = entry?;
let name = entry.file_name().to_string_lossy().into_owned();
if name.starts_with('_') {
names.push(name[1..].to_owned());
if let Some(stripped) = name.strip_prefix('_') {
names.push(stripped.to_owned());
} else {
names.push(name + "/");
}
Expand Down
2 changes: 1 addition & 1 deletion src/utils/kv_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ impl KvPairParse for Vec<String> {

let parsed_value = if value.starts_with('@') {
// Read from file
let file_path = &value[1..];
let file_path = value.strip_prefix('@').unwrap();
match fs::read_to_string(file_path) {
Ok(content) => Value::String(content),
Err(err) => {
Expand Down
9 changes: 4 additions & 5 deletions src/utils/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,10 @@ pub fn sanitize_policies(policies: &mut Vec<String>, add_default: bool) {
// the "default" policy out of its comparisons as it may be added later by core
// after a set of policies has been saved by a backend.
pub fn equivalent_policies(a: &Vec<String>, b: &Vec<String>) -> bool {
if a.is_empty() && b.is_empty() {
return true;
} else if a.is_empty() && b.len() == 1 && b[0] == "default" {
return true;
} else if b.is_empty() && a.len() == 1 && a[0] == "default" {
if (a.is_empty() && b.is_empty())
|| (a.is_empty() && b.len() == 1 && b[0] == "default")
|| (b.is_empty() && a.len() == 1 && a[0] == "default")
{
return true;
} else if a.is_empty() || b.is_empty() {
return false;
Expand Down

0 comments on commit 3714d68

Please # to comment.