diff --git a/src/auth/types.rs b/src/auth/types.rs index 2fcf3da..4862e41 100644 --- a/src/auth/types.rs +++ b/src/auth/types.rs @@ -11,10 +11,10 @@ pub trait AuthValidator { } pub async fn authenticate(auth: &InnerAuth, session: &mut Session) -> bool { match &*auth.auth_type { - "basic" => BasicAuth(&*auth.auth_cred).validate(session).await, - "apikey" => ApiKeyAuth(&*auth.auth_cred).validate(session).await, + "basic" => BasicAuth(&auth.auth_cred).validate(session).await, + "apikey" => ApiKeyAuth(&auth.auth_cred).validate(session).await, "jwt" => JwtAuth().validate(session).await, - "forward" => ForwardAuth(&*auth.auth_cred).validate(session).await, + "forward" => ForwardAuth(&auth.auth_cred).validate(session).await, _ => { log::warn!("Unsupported authentication mechanism : {}", &*auth.auth_type); false diff --git a/src/core/proxyhttp.rs b/src/core/proxyhttp.rs index 33217e6..b9d1b05 100644 --- a/src/core/proxyhttp.rs +++ b/src/core/proxyhttp.rs @@ -128,7 +128,7 @@ impl ProxyHttp for LB { None => return Ok(false), Some(ref innermap) => { if let Some(auth) = _ctx.extraparams.authentication.as_ref().or(innermap.authorization.as_ref()) { - if !authenticate(&auth, session).await { + if !authenticate(auth, session).await { let _ = session.respond_error(401).await; return Ok(true); } @@ -227,7 +227,7 @@ impl ProxyHttp for LB { peer.options.tcp_recv_buf = Some(128 * 1024); End of experimental options */ - if let Some(_) = ctx.extraparams.sticky_sessions { + if ctx.extraparams.sticky_sessions.is_some() { let mut s = String::with_capacity(64); write!( &mut s, @@ -347,12 +347,10 @@ impl ProxyHttp for LB { }; calc_metrics(m); ACTIVE_SESSIONS.dec(); - if let Some(_) = ctx.x4xx_limit.or(ctx.extraparams.x4xx_limit) { - if (400..=499).contains(&response_code) { - if let Some(ip) = session.client_addr().and_then(|a| a.as_inet()).map(|i| i.ip()) { - let current = REQUESTS_4XX.get(&ip).unwrap_or(0); - REQUESTS_4XX.insert(ip, current + 1); - } + if ctx.x4xx_limit.or(ctx.extraparams.x4xx_limit).is_some() && (400..=499).contains(&response_code) { + if let Some(ip) = session.client_addr().and_then(|a| a.as_inet()).map(|i| i.ip()) { + let current = REQUESTS_4XX.get(&ip).unwrap_or(0); + REQUESTS_4XX.insert(ip, current + 1); } } access_log(response_code, &self.request_summary(session, ctx), session).await; diff --git a/src/core/start.rs b/src/core/start.rs index 0c82545..e422601 100644 --- a/src/core/start.rs +++ b/src/core/start.rs @@ -68,7 +68,7 @@ pub fn run() { client_headers: ch_config, server_headers: sh_config, extraparams: ec_config, - cache_enabled: cache_enabled, + cache_enabled, }; // let al = cfg.access_log.clone().unwrap_or("none".to_string()); // init_access_log(al.as_str()); @@ -164,8 +164,8 @@ pub fn run() { if let Err(e) = write_pid_file(pf.as_str()) { panic!("Failed to write PID file: {} : {}", pf, e); } - let mut signals = Signals::new(&[SIGINT, SIGTERM, SIGQUIT]).unwrap(); - for sig in signals.forever() { + let mut signals = Signals::new([SIGINT, SIGTERM, SIGQUIT]).unwrap(); + if let Some(sig) = signals.forever().next() { match sig { SIGINT => info!("SIGINT received! Exiting..."), SIGTERM => info!("SIGTERM received! Exiting..."), @@ -175,6 +175,5 @@ pub fn run() { } _ => unreachable!(), } - break; } } diff --git a/src/core/webserver.rs b/src/core/webserver.rs index 0eaa216..7f63ac4 100644 --- a/src/core/webserver.rs +++ b/src/core/webserver.rs @@ -67,7 +67,7 @@ pub async fn run_server(config: &APIUpstreamProvider, mut to_return: mpsc::Sende let mut static_handle: Option> = None; if let (Some(address), Some(folder)) = (&config.file_server_address, &config.file_server_folder) { - let static_listen = port_is_available("File Server", &address).await; + let static_listen = port_is_available("File Server", address).await; let static_files = ServeDir::new(folder); let static_serve: Router = Router::new().fallback_service(static_files); info!("Starting file server on: {}", address); @@ -86,10 +86,9 @@ pub async fn run_server(config: &APIUpstreamProvider, mut to_return: mpsc::Sende let (tx, mut rx) = mpsc::channel(1); std::thread::spawn(move || { - let mut signals = Signals::new(&[SIGQUIT]).unwrap(); - for sig in signals.forever() { + let mut signals = Signals::new([SIGQUIT]).unwrap(); + if let Some(sig) = signals.forever().next() { tx.blocking_send(sig).unwrap(); - break; } }); rx.recv().await; @@ -109,7 +108,7 @@ async fn conf(State(st): State, Query(params): Query(strcontent); match parsed { Ok(_) => { - if let Some(_) = params.get("save") { + if params.contains_key("save") { tokio::spawn(async move { apply_config(content.as_str(), st, true).await }); } else { tokio::spawn(async move { apply_config(content.as_str(), st, false).await }); diff --git a/src/ingress/kubewatcher.rs b/src/ingress/kubewatcher.rs index 2807568..43a51ca 100644 --- a/src/ingress/kubewatcher.rs +++ b/src/ingress/kubewatcher.rs @@ -107,7 +107,7 @@ async fn process_ingress_change(client: &Client, ing: &Ingress, target_class: &s let key_clone = key.clone(); tokio::spawn(async move { if let Err(e) = patch_ingress_status_address(&client_clone, &ns_clone, &name_clone, &external_ip).await { - error!("Failed to patch ingress status address {}/{}: {}", &ns_clone, &name_clone, e); + error!("Failed to patch ingress status address {}/{}: {}", ns_clone, name_clone, e); PATCHED_INGRESSES.remove(&key_clone); } }); diff --git a/src/logging/core.rs b/src/logging/core.rs index 92423fc..2b4413a 100644 --- a/src/logging/core.rs +++ b/src/logging/core.rs @@ -160,7 +160,7 @@ pub async fn log_builder(conf: &AppConfig, location: &Option) { } if let Some(location) = location { let parts: Vec<&str> = location.split(',').map(|s| s.trim()).collect(); - let path = match parts.get(0).filter(|s| !s.is_empty()) { + let path = match parts.first().filter(|s| !s.is_empty()) { Some(p) => p, None => { error!("Invalid log location string provided; falling back to stdout"); @@ -213,7 +213,7 @@ pub async fn log_builder(conf: &AppConfig, location: &Option) { } pub async fn init_access_log(level_str: &str) { - let level = LogLevel::from_str(level_str); + let level = LogLevel::parse(level_str); let _ = ACCESS_LOG.set(level); } @@ -225,7 +225,7 @@ pub enum LogLevel { } impl LogLevel { - pub fn from_str(s: &str) -> Self { + pub fn parse(s: &str) -> Self { match s { "all" => LogLevel::Access, "error" => LogLevel::Error, @@ -288,7 +288,7 @@ pub async fn access_log(response_code: u16, summary: &str, session: &Session) { return; } if let Some(sender) = ACCESS_LOG_SENDER.get() { - if let Err(_) = sender.try_send(msg) { + if sender.try_send(msg).is_err() { LOGGING_ERRORS.inc(); } } diff --git a/src/tls/grades.rs b/src/tls/grades.rs index 4def7a3..b3cdee1 100644 --- a/src/tls/grades.rs +++ b/src/tls/grades.rs @@ -22,7 +22,7 @@ pub enum TlsGrade { } impl TlsGrade { - pub fn from_str(s: &str) -> Option { + pub fn parse(s: &str) -> Option { match s.to_ascii_lowercase().as_str() { "high" => Some(TlsGrade::High), "medium" => Some(TlsGrade::Medium), @@ -39,7 +39,7 @@ pub fn prefer_h2<'a>(_ssl: &mut SslRef, alpn_in: &'a [u8]) -> Result<&'a [u8], A } pub fn set_tsl_grade(tls_settings: &mut TlsSettings, grade: &str) { - let config_grade = TlsGrade::from_str(grade); + let config_grade = TlsGrade::parse(grade); match config_grade { Some(TlsGrade::High) => { let _ = tls_settings.set_min_proto_version(Some(SslVersion::TLS1_2)); diff --git a/src/tls/load.rs b/src/tls/load.rs index e55b213..5672204 100644 --- a/src/tls/load.rs +++ b/src/tls/load.rs @@ -54,7 +54,7 @@ impl Certificates { cert_infos.push(cert) } None => { - error!("Unable to load certificate info | public: {}, private: {}", &config.cert_path, &config.key_path); + error!("Unable to load certificate info | public: {}, private: {}", config.cert_path, config.key_path); return None; } } diff --git a/src/utils/hcclient.rs b/src/utils/hcclient.rs index ec4995f..351fd50 100644 --- a/src/utils/hcclient.rs +++ b/src/utils/hcclient.rs @@ -9,7 +9,28 @@ use std::time::Duration; pub static HC_CONNECTOR: LazyLock = LazyLock::new(|| Connector::new(None)); -pub async fn httpclient(method: &str, tls: bool, host: &str, path: &str, address: &str, port: u16, url: &str, payload: Bytes) -> (bool, bool) { +pub struct HttpClientRequest<'a> { + pub method: &'a str, + pub tls: bool, + pub host: &'a str, + pub path: &'a str, + pub address: &'a str, + pub port: u16, + pub url: &'a str, + pub payload: Bytes, +} + +pub async fn httpclient(req: HttpClientRequest<'_>) -> (bool, bool) { + let HttpClientRequest { + method, + tls, + host, + path, + address, + port, + url, + payload, + } = req; let method = match method { "HEAD" => "HEAD", "GET" => "GET", diff --git a/src/utils/healthcheck.rs b/src/utils/healthcheck.rs index 6e9cef4..2c3c077 100644 --- a/src/utils/healthcheck.rs +++ b/src/utils/healthcheck.rs @@ -1,4 +1,4 @@ -use crate::utils::hcclient::httpclient; +use crate::utils::hcclient::{httpclient, HttpClientRequest}; use crate::utils::lazylock::REVERSE_STORE; use crate::utils::tools::*; use crate::utils::types::{InnerMap, UpstreamsDashMap, UpstreamsIdMap}; @@ -68,7 +68,17 @@ async fn build_upstreams(fullist: &UpstreamsDashMap, method: &str) -> UpstreamsD } else { format!("http://{}:{}{}", upstream.address, upstream.port, path) }; - let resp = httpclient(method, tls, host, path, upstream.address.as_ref(), upstream.port, link.as_str(), EMPTY_PAYLOAD).await; + let resp = httpclient(HttpClientRequest { + method, + tls, + host, + path, + address: upstream.address.as_ref(), + port: upstream.port, + url: link.as_str(), + payload: EMPTY_PAYLOAD, + }) + .await; if resp.0 { if resp.1 { scheme.is_http2 = resp.1; diff --git a/src/utils/httpclient.rs b/src/utils/httpclient.rs index 8684d1c..ca82140 100644 --- a/src/utils/httpclient.rs +++ b/src/utils/httpclient.rs @@ -154,7 +154,7 @@ pub async fn for_kuber(url: &str, token: &str, conf: &GlobalServiceMapping) -> O } pub async fn getfromapi(url: &str, token: Option, provider: &str) -> Option> { - let (host, port, path, is_tls) = parse_url(&url).ok()?; + let (host, port, path, is_tls) = parse_url(url).ok()?; let mut peer = HttpPeer::new((host, port), is_tls, host.to_string()); peer.options.total_connection_timeout = Some(Duration::from_secs(5)); diff --git a/src/utils/types.rs b/src/utils/types.rs index 0abf7db..bf38131 100644 --- a/src/utils/types.rs +++ b/src/utils/types.rs @@ -158,6 +158,13 @@ pub struct InnerMap { pub authorization: Option>, } +#[allow(dead_code)] +impl Default for InnerMap { + fn default() -> Self { + Self::new() + } +} + #[allow(dead_code)] impl InnerMap { pub fn new() -> Self { diff --git a/src/utils/watch.rs b/src/utils/watch.rs index 2cbaf7a..b10950a 100644 --- a/src/utils/watch.rs +++ b/src/utils/watch.rs @@ -38,13 +38,11 @@ pub async fn file_watch(fp: String, toreturn: Sender) { while let Some(event) = local_rx.recv().await { match event { Ok(e) => match e.kind { - EventKind::Modify(ModifyKind::Data(_)) | EventKind::Create(..) | EventKind::Remove(..) => { - if start.elapsed() > Duration::from_secs(2) { - start = Instant::now(); - let snd = load_configuration(file_path, "filepath").await.0; - if let Some(snd) = snd { - toreturn.send(snd).await.unwrap(); - } + EventKind::Modify(ModifyKind::Data(_)) | EventKind::Create(..) | EventKind::Remove(..) if start.elapsed() > Duration::from_secs(2) => { + start = Instant::now(); + let snd = load_configuration(file_path, "filepath").await.0; + if let Some(snd) = snd { + toreturn.send(snd).await.unwrap(); } } _ => (), @@ -64,13 +62,11 @@ pub fn folder_watch(path: String, sender: std::sync::mpsc::Sender match &event.kind { - EventKind::Modify(ModifyKind::Data(_)) | EventKind::Create(_) | EventKind::Remove(_) => { - if start.elapsed() > Duration::from_secs(1) { - start = Instant::now(); - let certificate_configs = listdir(path.clone()); - sender.send(certificate_configs)?; - info!("Certificate changed: {:?}, {:?}", event.kind, event.paths); - } + EventKind::Modify(ModifyKind::Data(_)) | EventKind::Create(_) | EventKind::Remove(_) if start.elapsed() > Duration::from_secs(1) => { + start = Instant::now(); + let certificate_configs = listdir(path.clone()); + sender.send(certificate_configs)?; + info!("Certificate changed: {:?}, {:?}", event.kind, event.paths); } _ => {} },