Skip to content

Commit

Permalink
Clippy fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
nichtsfrei committed Jan 8, 2025
1 parent 162a922 commit e1c5373
Show file tree
Hide file tree
Showing 11 changed files with 52 additions and 69 deletions.
8 changes: 4 additions & 4 deletions rust/src/nasl/builtin/ssh/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ fn default_config() -> ServerConfig {
}

async fn run_test(
f: impl Fn(&mut TestBuilder<NoOpLoader, DefaultDispatcher>) -> () + Send + Sync + 'static,
f: impl Fn(&mut TestBuilder<NoOpLoader, DefaultDispatcher>) + Send + Sync + 'static,
config: ServerConfig,
) {
// Acquire the global lock to prevent multiple
Expand All @@ -58,7 +58,7 @@ async fn run_test(

#[tokio::main]
async fn run_client(
f: impl Fn(&mut TestBuilder<NoOpLoader, DefaultDispatcher>) -> () + Send + Sync + 'static,
f: impl Fn(&mut TestBuilder<NoOpLoader, DefaultDispatcher>) + Send + Sync + 'static,
) {
std::thread::sleep(Duration::from_millis(100));
let mut t = TestBuilder::default();
Expand Down Expand Up @@ -126,7 +126,7 @@ async fn ssh_userauth() {
..
},
);
userauth(&mut t);
userauth(t);
},
default_config(),
)
Expand All @@ -148,7 +148,7 @@ async fn ssh_request_exec() {
format!(r#"session_id = ssh_connect(port: {});"#, PORT),
MIN_SESSION_ID,
);
userauth(&mut t);
userauth(t);
t.ok(
r#"auth = ssh_request_exec(session_id, stdout: 1, stderr: 0, cmd: "write_foo_stdout");"#,
"foo",
Expand Down
8 changes: 4 additions & 4 deletions rust/src/nasl/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ pub mod prelude {

pub use prelude::*;

pub use builtin::nasl_std_functions;

pub use syntax::NoOpLoader;

#[cfg(test)]
pub mod test_prelude {
pub use super::prelude::*;
Expand All @@ -43,7 +47,3 @@ pub mod test_prelude {
pub use crate::check_code_result_matches;
pub use crate::check_err_matches;
}

pub use builtin::nasl_std_functions;

pub use syntax::NoOpLoader;
8 changes: 4 additions & 4 deletions rust/src/nasl/syntax/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ pub enum LoadError {
impl LoadError {
pub fn filename(&self) -> &str {
match self {
LoadError::Retry(x) => &x,
LoadError::NotFound(x) => &x,
LoadError::PermissionDenied(x) => &x,
LoadError::Dirty(x) => &x,
LoadError::Retry(x) => x,
LoadError::NotFound(x) => x,
LoadError::PermissionDenied(x) => x,
LoadError::Dirty(x) => x,
}
}
}
Expand Down
10 changes: 4 additions & 6 deletions rust/src/nasl/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ where
}
}

impl<'a> Clone for Box<dyn 'a + CloneableFn> {
impl Clone for Box<dyn '_ + CloneableFn> {
fn clone(&self) -> Self {
(**self).clone_box()
}
Expand Down Expand Up @@ -238,7 +238,7 @@ where
// let code = self.lines.join("\n");
// let context = self.context();

let parser = CodeInterpreter::new(&code, register, &context);
let parser = CodeInterpreter::new(code, register, context);
parser.stream().map(|res| {
res.map_err(|e| match e.kind {
InterpretErrorKind::FunctionCallError(f) => f.kind,
Expand Down Expand Up @@ -375,10 +375,8 @@ impl<L: Loader, S: Storage> Drop for TestBuilder<L, S> {
fn drop(&mut self) {
if tokio::runtime::Handle::try_current().is_ok() {
panic!("To use TestBuilder in an asynchronous context, explicitly call async_verify()");
} else {
if let Err(err) = futures::executor::block_on(self.verify()) {
panic!("{}", err)
}
} else if let Err(err) = futures::executor::block_on(self.verify()) {
panic!("{}", err)
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion rust/src/openvasd/storage/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -591,7 +591,7 @@ pub(crate) mod tests {
scan.scan_id = "aha".to_string();
let tmp_path = "/tmp/openvasd/credential";
clear_tmp_files(Path::new(tmp_path));
let storage = example_feed_file_storage(&tmp_path).await;
let storage = example_feed_file_storage(tmp_path).await;
storage.insert_scan(scan.clone()).await.unwrap();
let (scan2, _) = storage.get_scan("aha").await.unwrap();
assert_eq!(scan, scan2);
Expand Down
6 changes: 1 addition & 5 deletions rust/src/osp/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,7 @@
//! # Responses of OSPD commands
use std::{collections::HashMap, fmt};

use redis::ToRedisArgs;
use serde::{
de::{IntoDeserializer, Visitor},
Deserialize, Serializer,
};
use serde::{de::Visitor, Deserialize};

use super::commands::Error;

Expand Down
2 changes: 1 addition & 1 deletion rust/src/scanner/scan_runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -458,7 +458,7 @@ exit({rc});
}

fn make_test_dispatcher(vts: &[(String, Nvt)]) -> DefaultDispatcher {
let dispatcher = prepare_vt_storage(&vts);
let dispatcher = prepare_vt_storage(vts);
dispatcher
.dispatch(
&ContextKey::Scan("sid".into(), Some("test.host".into())),
Expand Down
5 changes: 1 addition & 4 deletions rust/src/scannerctl/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@
//
// SPDX-License-Identifier: GPL-2.0-or-later WITH x11vnc-openssl-exception

use std::{
fmt::Display,
path::{Path, PathBuf},
};
use std::path::{Path, PathBuf};

use feed::VerifyError;
use scannerlib::nasl::{interpreter::InterpretError, syntax::LoadError};
Expand Down
13 changes: 6 additions & 7 deletions rust/src/scannerctl/ospd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::{io::BufReader, path::PathBuf, sync::Arc};

use clap::{arg, value_parser, Arg, ArgAction, Command};
use scannerlib::models::{Parameter, Scan, VT};
use scannerlib::storage::{self, DefaultDispatcher, Retriever, StorageError};
use scannerlib::storage::{self, DefaultDispatcher, StorageError};
use start_scan::StartScan;

use crate::{CliError, CliErrorKind};
Expand Down Expand Up @@ -66,13 +66,13 @@ where
.vt_selection
.vt_single
.into_iter()
.flat_map(|x| x)
.flatten()
.map(|x| VT {
oid: x.id,
parameters: x
.vt_value
.into_iter()
.flat_map(|x| x)
.flatten()
.filter_map(|x| x.id.parse().ok().map(|y| (y, x.text)))
.filter_map(|(id, x)| x.map(|v| Parameter { id, value: v }))
.collect(),
Expand All @@ -82,7 +82,7 @@ where
.vt_selection
.vt_group
.into_iter()
.flat_map(|x| x)
.flatten()
.filter_map(
|x| match x.filter.split_once('=').map(|(k, v)| (k.trim(), v.trim())) {
Some(("family", v)) => Some(v.to_string()),
Expand Down Expand Up @@ -172,7 +172,7 @@ pub async fn run(root: &clap::ArgMatches) -> Option<Result<(), CliError>> {
}),
None => Err(CliError {
filename: config.cloned().unwrap_or_default(),
kind: CliErrorKind::Corrupt(format!("Unknown ospd command.")),
kind: CliErrorKind::Corrupt("Unknown ospd command.".to_string()),
}),
};

Expand All @@ -183,9 +183,8 @@ pub async fn run(root: &clap::ArgMatches) -> Option<Result<(), CliError>> {
mod tests {
use std::io::Cursor;

use scannerlib::storage::{item::NVTField, ContextKey, DefaultDispatcher, Field, Storage};
use scannerlib::storage::{item::NVTField, ContextKey, DefaultDispatcher, Field};
use storage::Dispatcher;
use x509_parser::nom::ExtendInto;

use super::*;

Expand Down
57 changes: 25 additions & 32 deletions rust/src/scannerctl/ospd/start_scan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ pub struct Target {
pub credentials: Option<Credentials>,
}

impl Into<models::Target> for Target {
fn into(self) -> models::Target {
let credentials = self
impl From<Target> for models::Target {
fn from(val: Target) -> Self {
let credentials = val
.credentials
.into_iter()
.flat_map(|x| {
x.credential.into_iter().flat_map(|x| x).map(|x| {
x.credential.into_iter().flatten().map(|x| {
fn find_key(key: &str, x: &[(String, String)]) -> Option<String> {
x.iter().find(|(k, _)| k == key).map(|(_, v)| v.to_string())
}
Expand Down Expand Up @@ -69,22 +69,22 @@ impl Into<models::Target> for Target {
};
models::Credential {
service: (&x.service as &str).try_into().ok().unwrap_or(Service::SSH),
port: x.port.map(|x| x.parse().ok()).flatten(),
port: x.port.and_then(|x| x.parse().ok()),
credential_type: kind,
}
})
})
.collect();

models::Target {
hosts: self.hosts,
ports: self.ports.unwrap_or_default(),
excluded_hosts: self.exclude_hosts.unwrap_or_default(),
hosts: val.hosts,
ports: val.ports.unwrap_or_default(),
excluded_hosts: val.exclude_hosts.unwrap_or_default(),
credentials,
alive_test_ports: self.alive_test_ports.unwrap_or_default(),
alive_test_methods: self.alive_test_methods.unwrap_or_default(),
reverse_lookup_unify: self.reverse_lookup_unify,
reverse_lookup_only: self.reverse_lookup_only,
alive_test_ports: val.alive_test_ports.unwrap_or_default(),
alive_test_methods: val.alive_test_methods.unwrap_or_default(),
reverse_lookup_unify: val.reverse_lookup_unify,
reverse_lookup_only: val.reverse_lookup_only,
}
}
}
Expand Down Expand Up @@ -160,10 +160,7 @@ fn ports_to_ospd_string(ports: Option<&[models::Port]>) -> Option<String> {
}

fn ospd_string_to_bool(v: &str) -> bool {
match &v.to_lowercase() as &str {
"1" | "true" | "yes" => true,
_ => false,
}
matches!(&v.to_lowercase() as &str, "1" | "true" | "yes")
}

fn bool_to_ospd_string(v: bool) -> &'static str {
Expand Down Expand Up @@ -292,7 +289,7 @@ impl<'de> Deserialize<'de> for Target {
}
}
"alive_test" => {
if let Some(at) = map.next_value::<String>().ok() {
if let Ok(at) = map.next_value::<String>() {
if let Ok(at) = at.parse::<u8>() {
if let Ok(at) = models::AliveTestMethods::try_from(at) {
result.alive_test_methods = Some(vec![at]);
Expand All @@ -303,11 +300,11 @@ impl<'de> Deserialize<'de> for Target {
}
}
"alive_test_methods" => {
if let Some(at) = map.next_value::<HashMap<String, String>>().ok() {
if let Ok(at) = map.next_value::<HashMap<String, String>>() {
let alive_test_methods = at
.iter()
.filter_map(|(k, v)| {
if ospd_string_to_bool(&v) {
if ospd_string_to_bool(v) {
match &k.to_lowercase() as &str {
"icmp" => Some(models::AliveTestMethods::Icmp),
"tcp_syn" => Some(models::AliveTestMethods::TcpSyn),
Expand Down Expand Up @@ -503,15 +500,11 @@ impl<'de> Deserialize<'de> for ScannerParameter {
let mut values = Vec::new();

while let Some(key) = map.next_key::<String>()? {
match key.as_str() {
key => {
let value: String = map.next_value()?;
values.push(models::ScanPreference {
id: key.to_string(),
value,
});
}
}
let value: String = map.next_value()?;
values.push(models::ScanPreference {
id: key.to_string(),
value,
});
}

Ok(ScannerParameter { values })
Expand Down Expand Up @@ -729,7 +722,7 @@ mod test {
</scanner_params>
</start_scan>
"#;
let sc: StartScan = from_str(&input).unwrap();
let sc: StartScan = from_str(input).unwrap();
insta::assert_snapshot!(sc);
}

Expand Down Expand Up @@ -764,7 +757,7 @@ mod test {
</scanner_params>
</start_scan>
"#;
let sc: StartScan = from_str(&input).unwrap();
let sc: StartScan = from_str(input).unwrap();
insta::assert_snapshot!(sc);
}

Expand Down Expand Up @@ -799,7 +792,7 @@ mod test {
</scanner_params>
</start_scan>
"#;
let sc: StartScan = from_str(&input).unwrap();
let sc: StartScan = from_str(input).unwrap();
insta::assert_snapshot!(sc);
}

Expand Down Expand Up @@ -840,7 +833,7 @@ mod test {
</scanner_params>
</start_scan>
"#;
let sc: StartScan = from_str(&input).unwrap();
let sc: StartScan = from_str(input).unwrap();
insta::assert_snapshot!(sc);
}
}
2 changes: 1 addition & 1 deletion rust/src/scannerctl/scanconfig.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ where
.iter()
.fold(HashMap::new(), |mut acc, p| {
let oid = p.nvt.oid.clone();
let parameters = acc.entry(oid).or_insert(vec![]);
let parameters = acc.entry(oid).or_default();
parameters.push(Parameter {
id: p.id,
value: p.value.clone(),
Expand Down

0 comments on commit e1c5373

Please sign in to comment.