mirror of
https://github.com/sadoyan/aralez.git
synced 2026-10-22 21:51:35 +08:00
+3
-3
@@ -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
|
||||
|
||||
@@ -109,7 +109,7 @@ impl ProxyHttp for LB {
|
||||
let hostname = return_header_host_from_upstream(session, &self.ump_upst);
|
||||
_ctx.hostname = hostname;
|
||||
let mut backend_id = None;
|
||||
if let Some(_) = _ctx.extraparams.sticky_sessions {
|
||||
if _ctx.extraparams.sticky_sessions.is_some() {
|
||||
if let Some(cookies) = session.req_header().headers.get("cookie") {
|
||||
if let Ok(cookie_str) = cookies.to_str() {
|
||||
if let Some(pos) = cookie_str.find("backend_id=") {
|
||||
@@ -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;
|
||||
|
||||
+3
-4
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ pub async fn run_server(config: &APIUpstreamProvider, mut to_return: mpsc::Sende
|
||||
|
||||
let mut static_handle: Option<tokio::task::JoinHandle<()>> = 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<AppState>, Query(params): Query<HashMap<String, S
|
||||
let parsed = noyalib::from_str::<Config>(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 });
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
|
||||
+4
-4
@@ -160,7 +160,7 @@ pub async fn log_builder(conf: &AppConfig, location: &Option<String>) {
|
||||
}
|
||||
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<String>) {
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -22,7 +22,7 @@ pub enum TlsGrade {
|
||||
}
|
||||
|
||||
impl TlsGrade {
|
||||
pub fn from_str(s: &str) -> Option<Self> {
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
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));
|
||||
|
||||
+1
-1
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
+22
-1
@@ -9,7 +9,28 @@ use std::time::Duration;
|
||||
|
||||
pub static HC_CONNECTOR: LazyLock<Connector> = 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",
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -154,7 +154,7 @@ pub async fn for_kuber(url: &str, token: &str, conf: &GlobalServiceMapping) -> O
|
||||
}
|
||||
|
||||
pub async fn getfromapi(url: &str, token: Option<String>, provider: &str) -> Option<Vec<u8>> {
|
||||
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));
|
||||
|
||||
@@ -158,6 +158,13 @@ pub struct InnerMap {
|
||||
pub authorization: Option<Arc<InnerAuth>>,
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
impl Default for InnerMap {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
impl InnerMap {
|
||||
pub fn new() -> Self {
|
||||
|
||||
+10
-14
@@ -38,13 +38,11 @@ pub async fn file_watch(fp: String, toreturn: Sender<Configuration>) {
|
||||
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<Vec<Certificat
|
||||
loop {
|
||||
match rx.recv_timeout(Duration::from_secs(1)) {
|
||||
Ok(Ok(event)) => 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);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user