Compare commits

..
9 Commits
29 changed files with 585 additions and 167 deletions
Generated
+178 -3
View File
@@ -130,7 +130,7 @@ checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"
[[package]]
name = "aralez"
version = "0.94.1"
version = "0.94.2"
dependencies = [
"ahash",
"anyhow",
@@ -143,6 +143,7 @@ dependencies = [
"dashmap 7.0.0-rc2",
"elasticsearch",
"futures",
"hickory-resolver",
"http-body-util",
"humantime",
"hyper",
@@ -170,6 +171,7 @@ dependencies = [
"prometheus",
"rand 0.10.2",
"rcgen",
"reqwest",
"rustls",
"rustls-pemfile",
"sd-notify",
@@ -708,6 +710,16 @@ dependencies = [
"tiny-keccak",
]
[[package]]
name = "core-foundation"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "core-foundation"
version = "0.10.1"
@@ -751,6 +763,12 @@ dependencies = [
"cfg-if",
]
[[package]]
name = "critical-section"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b"
[[package]]
name = "crossbeam-channel"
version = "0.5.16"
@@ -1635,6 +1653,76 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hickory-net"
version = "0.26.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c480823ed7c2c5d0f09c41020cb6b7c28029ce60ec42dc942158dcf22f8e0a4d"
dependencies = [
"async-trait",
"cfg-if",
"data-encoding",
"futures-channel",
"futures-io",
"futures-util",
"hickory-proto",
"idna",
"ipnet",
"jni",
"rand 0.10.2",
"thiserror 2.0.18",
"tinyvec",
"tokio",
"tracing",
"url",
]
[[package]]
name = "hickory-proto"
version = "0.26.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12b92608f679a6fa515dd1d15c1ff89443026e391200a2c840c7afcba482893d"
dependencies = [
"data-encoding",
"idna",
"ipnet",
"jni",
"once_cell",
"prefix-trie",
"rand 0.10.2",
"ring",
"thiserror 2.0.18",
"tinyvec",
"tracing",
"url",
]
[[package]]
name = "hickory-resolver"
version = "0.26.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f3da5255c95d5a716857d54b5b8f4e8d67c3484d3beaaaae2ce25063b3ba981"
dependencies = [
"cfg-if",
"futures-util",
"hickory-net",
"hickory-proto",
"ipconfig",
"ipnet",
"jni",
"moka",
"ndk-context",
"once_cell",
"parking_lot",
"rand 0.10.2",
"resolv-conf",
"smallvec",
"system-configuration",
"thiserror 2.0.18",
"tokio",
"tracing",
]
[[package]]
name = "hkdf"
version = "0.12.4"
@@ -1817,9 +1905,11 @@ dependencies = [
"percent-encoding",
"pin-project-lite",
"socket2",
"system-configuration",
"tokio",
"tower-service",
"tracing",
"windows-registry",
]
[[package]]
@@ -2034,11 +2124,27 @@ dependencies = [
"rustversion",
]
[[package]]
name = "ipconfig"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d40460c0ce33d6ce4b0630ad68ff63d6661961c48b6dba35e5a4d81cfb48222"
dependencies = [
"socket2",
"widestring",
"windows-registry",
"windows-result",
"windows-sys 0.61.2",
]
[[package]]
name = "ipnet"
version = "2.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
dependencies = [
"serde",
]
[[package]]
name = "is_terminal_polyfill"
@@ -2604,6 +2710,12 @@ dependencies = [
"tempfile",
]
[[package]]
name = "ndk-context"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"
[[package]]
name = "nix"
version = "0.30.1"
@@ -2796,6 +2908,10 @@ name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
dependencies = [
"critical-section",
"portable-atomic",
]
[[package]]
name = "once_cell_polyfill"
@@ -3374,6 +3490,17 @@ dependencies = [
"zerocopy",
]
[[package]]
name = "prefix-trie"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cf6e3177f0684016a5c209b00882e15f8bdd3f3bb48f0491df10cd102d0c6e7"
dependencies = [
"either",
"ipnet",
"num-traits",
]
[[package]]
name = "primeorder"
version = "0.13.6"
@@ -3615,15 +3742,19 @@ checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
dependencies = [
"base64 0.22.1",
"bytes",
"encoding_rs",
"futures-core",
"h2",
"http",
"http-body",
"http-body-util",
"hyper",
"hyper-rustls",
"hyper-tls",
"hyper-util",
"js-sys",
"log",
"mime",
"native-tls",
"percent-encoding",
"pin-project-lite",
@@ -3643,6 +3774,12 @@ dependencies = [
"web-sys",
]
[[package]]
name = "resolv-conf"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7"
[[package]]
name = "rfc6979"
version = "0.4.0"
@@ -3805,7 +3942,7 @@ version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0"
dependencies = [
"core-foundation",
"core-foundation 0.10.1",
"core-foundation-sys",
"jni",
"log",
@@ -3950,7 +4087,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
dependencies = [
"bitflags 2.13.0",
"core-foundation",
"core-foundation 0.10.1",
"core-foundation-sys",
"libc",
"security-framework-sys",
@@ -4385,6 +4522,27 @@ dependencies = [
"syn 3.0.3",
]
[[package]]
name = "system-configuration"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"
dependencies = [
"bitflags 2.13.0",
"core-foundation 0.9.4",
"system-configuration-sys",
]
[[package]]
name = "system-configuration-sys"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "tagptr"
version = "0.2.0"
@@ -4976,6 +5134,12 @@ dependencies = [
"rustls-pki-types",
]
[[package]]
name = "widestring"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471"
[[package]]
name = "winapi"
version = "0.3.9"
@@ -5048,6 +5212,17 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-registry"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
dependencies = [
"windows-link",
"windows-result",
"windows-strings",
]
[[package]]
name = "windows-result"
version = "0.4.1"
+5 -3
View File
@@ -1,7 +1,7 @@
[package]
name = "aralez"
version = "0.94.1"
edition = "2021"
version = "0.94.2"
edition = "2024"
license = "Apache-2.0"
description = "Reverse proxy built on top of Cloudflare's Pingora"
exclude = ["configs/*"]
@@ -32,7 +32,6 @@ noyalib = { version = "0.0.44", features = ["compat-serde-yaml"] }
rand = "0.10.2"
base64 = "0.23.1"
jsonwebtoken = { version = "11.1.0", default-features = false, features = ["use_pem", "rust_crypto"] }
#sha2 = { version = "0.11.0-rc.5", default-features = false }
sha2 = { version = "0.11.0", default-features = false }
base16ct = { version = "1.0.0", features = ["alloc"] }
urlencoding = "2.1.3"
@@ -68,4 +67,7 @@ anyhow = "1.0.103"
inventory = "0.3.24"
elasticsearch = "9.1.0-alpha.1"
humantime = "2.4.0"
reqwest = "0.12.28"
hickory-resolver = { version = "0.26", features = ["tokio"] }
+3 -3
View File
@@ -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
+3 -1
View File
@@ -72,6 +72,7 @@ impl BackgroundService for LB {
file_server_folder: self.config.file_server_folder.clone(),
current_upstreams: self.ump_upst.clone(),
full_upstreams: self.ump_full.clone(),
acme_dns_provider: self.config.acme_dns_provider.clone(),
};
tokio::spawn(async move { api_load.start(tx_api).await });
let uu = self.ump_upst.clone();
@@ -80,7 +81,8 @@ impl BackgroundService for LB {
let (hc_method, hc_interval) = (self.config.hc_method.clone(), self.config.hc_interval);
tokio::spawn(async move { healthcheck::hc2(uu, ff, im, (&*hc_method.to_string(), hc_interval.to_string().parse().unwrap())).await });
tokio::spawn(async move { calc_cache_metrics().await });
tokio::spawn(async move { refresh_order(certdir, confdir).await });
let acme_provider = self.config.acme_dns_provider.clone();
tokio::spawn(async move { refresh_order(certdir, confdir, acme_provider).await });
init_access_logging(self.config.access_log.clone()).await;
loop {
+34 -47
View File
@@ -8,9 +8,9 @@ use arc_swap::ArcSwap;
use async_trait::async_trait;
use axum::body::Bytes;
use log::error;
use pingora::ErrorSource::Upstream;
use pingora::http::{Method, RequestHeader, ResponseHeader, StatusCode};
use pingora::prelude::*;
use pingora::ErrorSource::Upstream;
use pingora_cache::cache_control::CacheControl;
use pingora_cache::{CacheKey, CacheMetaDefaults, RespCacheable};
use pingora_core::listeners::ALPN;
@@ -43,7 +43,7 @@ pub struct Context {
upstream_peer: Option<Arc<InnerMap>>,
extraparams: arc_swap::Guard<Arc<Extraparams>>,
client_headers: Option<Vec<(String, Arc<str>)>>,
x4xx_limit: Option<u32>,
x4xx_limit: u32,
}
thread_local! {
@@ -60,7 +60,7 @@ impl ProxyHttp for LB {
upstream_peer: None,
extraparams: self.extraparams.load(),
client_headers: None,
x4xx_limit: None,
x4xx_limit: 0,
}
}
@@ -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 > 0 {
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,17 +128,30 @@ 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);
}
}
if let Some(rate) = innermap.x4xx_limit.or(_ctx.extraparams.x4xx_limit) {
_ctx.x4xx_limit = innermap.x4xx_limit;
let rate = if innermap.rate_limit > 0 { innermap.rate_limit } else { _ctx.extraparams.rate_limit };
let xrate = if innermap.x4xx_limit > 0 { innermap.x4xx_limit } else { _ctx.extraparams.x4xx_limit };
if xrate > 0 || rate > 0 {
let rate_key = session.client_addr().and_then(|addr| addr.as_inet()).map(|inet| inet.ip());
if let Some(rk) = rate_key {
let count = REQUESTS_4XX.get(&rk).unwrap_or(0);
if count > rate {
if xrate > 0 {
_ctx.x4xx_limit = xrate;
if let Some(rk) = rate_key {
let count = REQUESTS_4XX.get(&rk).unwrap_or(0);
if count > xrate {
let header = ResponseHeader::build(429, None)?;
session.set_keepalive(None);
session.write_response_header(Box::new(header), true).await?;
return Ok(true);
}
}
}
if rate > 0 {
let curr_window_requests = RATE_LIMITER.observe(&rate_key, 1);
if curr_window_requests > rate {
let header = ResponseHeader::build(429, None)?;
session.set_keepalive(None);
session.write_response_header(Box::new(header), true).await?;
@@ -146,16 +159,6 @@ impl ProxyHttp for LB {
}
}
}
if let Some(rate) = innermap.rate_limit.or(_ctx.extraparams.rate_limit) {
let rate_key = session.client_addr().and_then(|addr| addr.as_inet()).map(|inet| inet.ip());
let curr_window_requests = RATE_LIMITER.observe(&rate_key, 1);
if curr_window_requests > rate {
let header = ResponseHeader::build(429, None)?;
session.set_keepalive(None);
session.write_response_header(Box::new(header), true).await?;
return Ok(true);
}
}
if let Some(redirect_to) = &innermap.redirect_to {
let uri = session.req_header().uri.path();
@@ -170,7 +173,7 @@ impl ProxyHttp for LB {
return Ok(true);
}
if _ctx.extraparams.to_https.unwrap_or(false) || innermap.to_https {
if _ctx.extraparams.to_https || innermap.to_https {
if let Some(stream) = session.stream() {
if stream.get_ssl().is_none() {
if let Some(host) = _ctx.hostname.as_ref() {
@@ -213,21 +216,7 @@ impl ProxyHttp for LB {
peer.options.verify_cert = false;
peer.options.verify_hostname = false;
}
/*
Experimental optionsv
The following TCP optimizations were tested but caused performance degrade under heavy load:
peer.options.tcp_keepalive = Some(TcpKeepalive {
idle: Duration::from_secs(60),
interval: Duration::from_secs(10),
count: 5,
user_timeout: Duration::from_secs(30),
});
peer.options.idle_timeout = Some(Duration::from_secs(300));
peer.options.tcp_recv_buf = Some(128 * 1024);
End of experimental options
*/
if let Some(_) = ctx.extraparams.sticky_sessions {
if ctx.extraparams.sticky_sessions > 0 {
let mut s = String::with_capacity(64);
write!(
&mut s,
@@ -237,9 +226,9 @@ impl ProxyHttp for LB {
innermap.port,
innermap.is_http2,
innermap.to_https,
innermap.x4xx_limit.unwrap_or_default(),
innermap.rate_limit.unwrap_or_default(),
innermap.healthcheck.unwrap_or_default(),
innermap.x4xx_limit,
innermap.rate_limit,
innermap.healthcheck,
innermap.authorization
)
.unwrap_or(());
@@ -303,7 +292,7 @@ impl ProxyHttp for LB {
Ok(())
}
async fn response_filter(&self, _session: &mut Session, _upstream_response: &mut ResponseHeader, ctx: &mut Self::CTX) -> Result<()> {
if let Some(val) = ctx.extraparams.sticky_sessions {
if ctx.extraparams.sticky_sessions > 0 {
if let Some(bid) = &ctx.backend_id {
let tt = if let Some(existing) = REVERSE_STORE.get(bid) {
existing.value().clone()
@@ -321,7 +310,7 @@ impl ProxyHttp for LB {
buf.push_str("backend_id=");
buf.push_str(&tt);
buf.push_str("; Path=/; Max-Age=");
buf.push_str(&val.to_string());
buf.push_str(&ctx.extraparams.sticky_sessions.to_string());
buf.push_str("; HttpOnly; SameSite=Lax");
let _ = _upstream_response.append_header("set-cookie", buf.as_str());
}
@@ -347,12 +336,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 > 0 && (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;
+11 -16
View File
@@ -11,9 +11,9 @@ use dashmap::DashMap;
use log::info;
use pingora::tls::ssl::{SslAlert, SslRef};
use pingora_cache::eviction::simple_lru::Manager;
use pingora_core::listeners::tls::TlsSettings;
use pingora_core::listeners::TcpSocketOptions;
use pingora_core::prelude::{background_service, Opt};
use pingora_core::listeners::tls::TlsSettings;
use pingora_core::prelude::{Opt, background_service};
use pingora_core::protocols::TcpKeepalive;
use pingora_core::server::Server;
use privdrop::reexports::libc::SIGQUIT;
@@ -23,8 +23,8 @@ use signal_hook::{
consts::{SIGINT, SIGTERM},
iterator::Signals,
};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender, channel};
use std::time::Duration;
use std::{fs, thread};
@@ -51,11 +51,12 @@ pub fn run() {
let sh_config = Arc::new(DashMap::new());
let ec_config = Arc::new(ArcSwap::from_pointee(Extraparams {
to_https: None,
sticky_sessions: None,
to_https: false,
ssl_verify: false,
sticky_sessions: 0,
authentication: None,
rate_limit: None,
x4xx_limit: None,
rate_limit: 0,
x4xx_limit: 0,
}));
let cfg = Arc::new(maincfg);
@@ -68,10 +69,8 @@ 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());
let grade = cfg.proxy_tls_grade.clone().unwrap_or("medium".to_string());
info!("TLS grade set to: [ {} ]", grade);
@@ -84,9 +83,6 @@ pub fn run() {
check_priv(bind_address_http.as_str());
// let mut tcp_options: Option<TcpSocketOptions> = Some(TcpSocketOptions::default());
// let mut tcp_options = TcpSocketOptions::default();
let mut tcp_options: Option<TcpSocketOptions> = None;
if let Some(idle) = cfg.tcp_keepalive_idle {
let mut to = TcpSocketOptions::default();
@@ -164,8 +160,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 +171,5 @@ pub fn run() {
}
_ => unreachable!(),
}
break;
}
}
+10 -9
View File
@@ -1,7 +1,7 @@
use crate::auth::jwt::Claims;
use crate::ingress::APIUpstreamProvider;
use crate::tls::acme::http01::{acme_create, acme_order, http01_challenge};
use crate::utils::metrics::{get_memory_usage, get_open_files, MEMORY_USAGE, OPEN_FILES};
use crate::utils::metrics::{MEMORY_USAGE, OPEN_FILES, get_memory_usage, get_open_files};
use crate::utils::tools::{upstreams_liveness_json, upstreams_to_json};
use crate::utils::types::{Config, Configuration, UpstreamsDashMap};
use axum::body::Body;
@@ -10,9 +10,9 @@ use axum::http::{Response, StatusCode};
use axum::response::IntoResponse;
use axum::routing::{any, get, post};
use axum::{Json, Router};
use jsonwebtoken::{encode, EncodingKey, Header};
use jsonwebtoken::{EncodingKey, Header, encode};
use log::{debug, error, info, warn};
use prometheus::{gather, Encoder, TextEncoder};
use prometheus::{Encoder, TextEncoder, gather};
use serde::Serialize;
use signal_hook::{consts::SIGQUIT, iterator::Signals};
use std::collections::HashMap;
@@ -32,6 +32,7 @@ struct OutToken {
#[derive(Clone)]
pub struct AppState {
master_key: Option<String>,
pub acme_dns_provider: Option<String>,
pub cert_creds: String,
pub certs_dir: String,
upstreams_file: String,
@@ -53,6 +54,7 @@ pub async fn run_server(config: &APIUpstreamProvider, mut to_return: mpsc::Sende
config_api_enabled: config.config_api_enabled,
current_upstreams: upstreams_curr,
full_upstreams: upstreams_full,
acme_dns_provider: config.acme_dns_provider.clone(),
};
let app = Router::new()
// .route("/{*wildcard}", get(senderror))
@@ -67,7 +69,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 +88,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 +110,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 });
@@ -215,7 +216,7 @@ async fn status(State(st): State<AppState>, Query(params): Query<HashMap<String,
.status(StatusCode::OK)
.header("Content-Type", "application/json")
.body(Body::from(j))
.unwrap()
.unwrap();
}
Err(e) => {
return Response::builder()
+1
View File
@@ -12,6 +12,7 @@ pub struct APIUpstreamProvider {
pub config_api_enabled: bool,
pub address: String,
pub masterkey: Option<String>,
pub acme_dns_provider: Option<String>,
pub certs_dir: String,
pub config_dir: String,
pub upstreams_file: String,
+1 -1
View File
@@ -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
View File
@@ -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();
}
}
+74
View File
@@ -0,0 +1,74 @@
use crate::tls::acme::lookup::lookup_wait;
use crate::tls::acme::types::{DnsBackendPlugin, DnsProvider};
use log::info;
use reqwest::Client;
use serde_json::json;
pub struct CloudflareProvider {
pub client: Client,
pub api_token: String,
pub zone_id: String,
}
impl CloudflareProvider {
pub fn new() -> Self {
let api_token = std::env::var("CLOUDFLARE_API_TOKEN").expect("Environment variable CLOUDFLARE_API_TOKEN is required");
let zone_id = std::env::var("CLOUDFLARE_ZONE_ID").expect("Environment variable CLOUDFLARE_ZONE_ID is required");
Self {
client: Client::new(),
api_token,
zone_id,
}
}
}
#[async_trait::async_trait]
impl DnsProvider for CloudflareProvider {
async fn create_txt_record(&self, _domain: &str, name: &str, value: &str) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
let url = format!("https://api.cloudflare.com/client/v4/zones/{}/dns_records", self.zone_id);
let response = self
.client
.post(&url)
.bearer_auth(&self.api_token)
.json(&json!({
"type": "TXT",
"name": name,
"content": value,
"ttl": 120,
}))
.send()
.await?;
let res_json: serde_json::Value = response.json().await?;
if !res_json["success"].as_bool().unwrap_or(false) {
return Err(format!("Cloudflare API error: {:?}", res_json["errors"]).into());
}
let record_id = res_json["result"]["id"].as_str().ok_or("missing id")?.to_string();
info!("Created TXT record name: {}, id: {}", name, record_id);
lookup_wait(name, Some("1.1.1.1"), 60, value).await;
Ok(record_id)
}
async fn delete_txt_record(&self, record_id: &str, record_name: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let url = format!("https://api.cloudflare.com/client/v4/zones/{}/dns_records/{}", self.zone_id, record_id);
let response = self.client.delete(&url).bearer_auth(&self.api_token).send().await?;
let res_json: serde_json::Value = response.json().await?;
if !res_json["success"].as_bool().unwrap_or(false) {
return Err(format!("Cloudflare API error deleting record: {:?}", res_json["errors"]).into());
}
info!("Deleted TXT record name: {}, id: {}", record_name, record_id);
Ok(())
}
}
inventory::submit! {
DnsBackendPlugin {
name: "cloudflare",
factory: || Box::new(CloudflareProvider::new()),
}
}
+2
View File
@@ -0,0 +1,2 @@
pub mod cloudflare;
pub mod route53;
+33
View File
@@ -0,0 +1,33 @@
use crate::tls::acme::types::{DnsBackendPlugin, DnsProvider};
pub struct Route53Provider {
pub hosted_zone_id: String,
}
impl Route53Provider {
pub fn new() -> Self {
Self {
hosted_zone_id: std::env::var("AWS_HOSTED_ZONE_ID").unwrap_or_default(),
}
}
}
// Not working, just a placeholder.
#[async_trait::async_trait]
impl DnsProvider for Route53Provider {
async fn create_txt_record(&self, _domain: &str, _name: &str, _value: &str) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
println!(" ====> Route53 Created TXT Record for {}: {}: {}", _name, _domain, _value);
Ok("route53_change_id".to_string())
}
async fn delete_txt_record(&self, _record_id: &str, _record_name: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
println!(" ====> Route53 Deleted TXT Record for {}: {}", _record_name, _record_id);
Ok(())
}
}
inventory::submit! {
DnsBackendPlugin {
name: "route53",
factory: || Box::new(Route53Provider::new()),
}
}
+5 -5
View File
@@ -14,32 +14,32 @@ pub async fn acme_create(State(state): State<webserver::AppState>) -> impl IntoR
.status(StatusCode::OK)
.header("Content-Type", "text/plain")
.body(Body::from(txt))
.unwrap()
.unwrap();
}
Err(e) => {
return Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Body::from(format!("Failed to create account: {}", e)))
.unwrap()
.unwrap();
}
};
}
#[allow(clippy::needless_return)]
pub async fn acme_order(State(state): State<webserver::AppState>, axum::extract::Path(domain): axum::extract::Path<String>) -> impl IntoResponse {
let domain_clean = domain.trim_matches('/');
match order::order(domain_clean, state.cert_creds.as_str(), state.certs_dir).await {
match order::order(domain_clean, state.cert_creds.as_str(), state.certs_dir, state.acme_dns_provider).await {
Ok(txt) => {
return Response::builder()
.status(StatusCode::OK)
.header("Content-Type", "text/plain")
.body(Body::from(txt))
.unwrap()
.unwrap();
}
Err(e) => {
return Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Body::from(format!("Failed to order a certificate: {}", e)))
.unwrap()
.unwrap();
}
};
}
+45
View File
@@ -0,0 +1,45 @@
use hickory_resolver::TokioResolver;
use hickory_resolver::config::{NameServerConfig, ResolverConfig, ResolverOpts};
use hickory_resolver::net::runtime::TokioRuntimeProvider;
use hickory_resolver::proto::rr::RData;
use log::info;
use std::net::IpAddr;
use std::str::FromStr;
use std::time::Duration;
pub async fn lookup_wait(record_name: &str, dns_server_ip: Option<&str>, max_wait_secs: u64, expected_value: &str) -> bool {
let target_ip = dns_server_ip.and_then(|ip| IpAddr::from_str(ip).ok()).unwrap_or_else(|| IpAddr::from([1, 1, 1, 1]));
let name_server = NameServerConfig::udp(target_ip);
let config = ResolverConfig::from_name_servers(vec![name_server]);
let mut opts = ResolverOpts::default();
opts.cache_size = 0;
let resolver = TokioResolver::builder_with_config(config, TokioRuntimeProvider::default())
.with_options(opts)
.build()
.expect("failed to build DNS resolver");
let start = std::time::Instant::now();
let poll_interval = Duration::from_secs(3);
while start.elapsed().as_secs() < max_wait_secs {
if let Ok(txt_lookup) = resolver.txt_lookup(record_name).await {
for record in txt_lookup.answers() {
if let RData::TXT(txt) = &record.data {
for data in &txt.txt_data {
if let Ok(txt_str) = std::str::from_utf8(data) {
if txt_str == expected_value {
tokio::time::sleep(Duration::from_secs(5)).await;
info!("DNS record propagated successfully for {} : {}", record_name, txt_str);
return true;
}
}
}
}
}
} else {
info!("Waiting for TXT record {}", record_name);
}
tokio::time::sleep(poll_interval).await;
}
false
}
+3
View File
@@ -1,6 +1,9 @@
pub mod account;
pub mod dns;
pub mod http01;
pub mod lookup;
pub mod order;
pub mod types;
pub use account::*;
pub use order::*;
+43 -9
View File
@@ -1,24 +1,30 @@
use crate::tls::acme::account::get_account;
use crate::tls::acme::types::get_provider;
use crate::utils::lazylock::CHALLENGES;
use crate::utils::parceyaml::DOMAINS;
use crate::utils::lazylock::DOMAINS;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use instant_acme::{ChallengeType, Identifier, NewOrder, RetryPolicy};
use log::{error, info};
use pingora::prelude::sleep;
use rcgen::{CertificateParams, DistinguishedName, KeyPair};
use sha2::{Digest, Sha256};
use std::fs;
use std::time::Duration;
use x509_parser::prelude::*;
pub async fn refresh_order(certs_dir: String, autoconf_dir: String) {
static DNS: bool = true;
pub async fn refresh_order(certs_dir: String, autoconf_dir: String, provider: Option<String>) {
let credsfile = autoconf_dir + "/acme_credentials.json";
loop {
for item in DOMAINS.iter() {
let _what = order(item.key(), credsfile.as_str(), certs_dir.clone()).await;
let _what = order(item.key(), credsfile.as_str(), certs_dir.clone(), provider.clone()).await;
}
sleep(Duration::from_secs(12 * 3600)).await;
}
}
pub async fn order(domain: &str, credsfile: &str, certs_dir: String) -> Result<String, Box<dyn std::error::Error>> {
pub async fn order(domain: &str, credsfile: &str, certs_dir: String, provider: Option<String>) -> Result<String, Box<dyn std::error::Error>> {
let crt = certs_dir.clone() + "/" + domain + ".crt";
let key = certs_dir.clone() + "/" + domain + ".key";
@@ -36,7 +42,6 @@ pub async fn order(domain: &str, credsfile: &str, certs_dir: String) -> Result<S
}
}
}
if let Ok(expiry) = cert_expiry(crt.as_str()) {
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs();
if expiry > now + 30 * 24 * 3600 {
@@ -49,14 +54,38 @@ pub async fn order(domain: &str, credsfile: &str, certs_dir: String) -> Result<S
let mut order = account.new_order(&NewOrder::new(&[Identifier::Dns(domain.to_string())])).await?;
let mut authorizations = order.authorizations();
while let Some(auth) = authorizations.next().await {
let mut auth = auth?;
let mut challenge_handle = auth.challenge(ChallengeType::Http01).ok_or("no http01 challenge found")?;
let domain = auth.identifier().to_string();
let challenge_type = if DNS { ChallengeType::Dns01 } else { ChallengeType::Http01 };
let mut challenge_handle = auth.challenge(challenge_type).ok_or("No challenge found")?;
let key_auth = challenge_handle.key_authorization();
let key_auth_str = key_auth.as_str().to_string();
let token = key_auth_str.split('.').next().ok_or("invalid key authorization")?.to_string();
CHALLENGES.write().unwrap().insert(token, key_auth_str);
challenge_handle.set_ready().await?;
if let Some(prov) = provider.clone() {
let dns_provider = get_provider(prov.clone());
let dns_value = calculate_dns_value(&key_auth_str);
let clean_domain = domain.trim_start_matches("*.").to_string();
let record_name = format!("_acme-challenge.{}", clean_domain);
match dns_provider.create_txt_record(&clean_domain, &record_name, &dns_value).await {
Ok(record_id) => {
let ready_res = challenge_handle.set_ready().await;
let _ = dns_provider.delete_txt_record(&record_id, &record_name).await;
ready_res?;
}
Err(e) => {
eprintln!("Failed to create DNS record: {}", e);
return Err(e);
}
}
} else {
let token = key_auth_str.split('.').next().ok_or("invalid key authorization")?.to_string();
CHALLENGES.write().unwrap().insert(token, key_auth_str);
challenge_handle.set_ready().await?;
}
}
let status = order.poll_ready(&RetryPolicy::default()).await?;
@@ -86,3 +115,8 @@ fn cert_expiry(path: &str) -> Result<u64, Box<dyn std::error::Error>> {
let expiry = cert.validity().not_after.timestamp() as u64;
Ok(expiry)
}
fn calculate_dns_value(key_auth: &str) -> String {
let hash = Sha256::digest(key_auth.as_bytes());
URL_SAFE_NO_PAD.encode(hash)
}
+32
View File
@@ -0,0 +1,32 @@
use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::LazyLock;
pub struct DnsBackendPlugin {
pub name: &'static str,
pub factory: fn() -> Box<dyn DnsProvider>,
}
inventory::collect!(DnsBackendPlugin);
static PROVIDERS: LazyLock<HashMap<&'static str, Box<dyn DnsProvider>>> = LazyLock::new(|| {
let mut map = HashMap::new();
for plugin in inventory::iter::<DnsBackendPlugin> {
map.insert(plugin.name, (plugin.factory)());
}
map
});
#[async_trait]
pub trait DnsProvider: Send + Sync {
async fn create_txt_record(&self, domain: &str, name: &str, value: &str) -> Result<String, Box<dyn std::error::Error + Send + Sync>>;
async fn delete_txt_record(&self, record_id: &str, record_name: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
}
pub fn get_provider(provider: String) -> &'static dyn DnsProvider {
PROVIDERS
.get(provider.as_str())
.map(|boxed| boxed.as_ref())
.unwrap_or_else(|| panic!("Unknown DNS provider '{}'. Available providers: {:?}", provider, PROVIDERS.keys().collect::<Vec<_>>()))
}
+2 -2
View File
@@ -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
View File
@@ -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;
}
}
+2 -1
View File
@@ -8,12 +8,13 @@ pub static DEALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
pub static ALLOC_BYTES: AtomicUsize = AtomicUsize::new(0);
#[allow(dead_code)]
unsafe impl GlobalAlloc for CountingAllocator {
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
ALLOC_COUNT.fetch_add(1, Ordering::Relaxed);
ALLOC_BYTES.fetch_add(layout.size(), Ordering::Relaxed);
System.alloc(layout)
}
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
DEALLOC_COUNT.fetch_add(1, Ordering::Relaxed);
System.dealloc(ptr, layout)
+22 -1
View File
@@ -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",
+15 -5
View File
@@ -1,11 +1,11 @@
use crate::utils::hcclient::httpclient;
use crate::utils::hcclient::{HttpClientRequest, httpclient};
use crate::utils::lazylock::REVERSE_STORE;
use crate::utils::tools::*;
use crate::utils::types::{InnerMap, UpstreamsDashMap, UpstreamsIdMap};
use bytes::Bytes;
use dashmap::DashMap;
use std::sync::atomic::AtomicUsize;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::time::Duration;
use tokio::net::TcpStream;
use tokio::time::{interval, timeout};
@@ -44,7 +44,7 @@ async fn build_upstreams(fullist: &UpstreamsDashMap, method: &str) -> UpstreamsD
let mut innervec = Vec::new();
for upstream in path_entry.value().0.iter() {
let tls = if upstream.healthcheck.unwrap_or(true) {
let tls = if upstream.healthcheck {
detect_tls(upstream.address.as_ref(), &upstream.port, host).await
} else {
false
@@ -62,13 +62,23 @@ async fn build_upstreams(fullist: &UpstreamsDashMap, method: &str) -> UpstreamsD
authorization: upstream.authorization.clone(),
};
if scheme.healthcheck.unwrap_or(true) {
if scheme.healthcheck {
let link = if tls {
format!("https://{}:{}{}", upstream.address, upstream.port, path)
} 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;
+8 -12
View File
@@ -90,10 +90,10 @@ pub async fn for_consul(url: &str, token: Option<String>, conf: &GlobalServiceMa
is_ssl: false,
is_http2: false,
to_https: conf.to_https.unwrap_or(false),
rate_limit: conf.rate_limit,
x4xx_limit: conf.x4xx_limit,
rate_limit: conf.rate_limit.unwrap_or(0),
x4xx_limit: conf.x4xx_limit.unwrap_or(0),
redirect_to: conf.redirect_to.clone().map(Arc::<str>::from),
healthcheck: None,
healthcheck: true,
authorization: None,
});
inner_vec.push(to_add);
@@ -132,9 +132,9 @@ pub async fn for_kuber(url: &str, token: &str, conf: &GlobalServiceMapping) -> O
is_ssl: false,
is_http2: false,
to_https: conf.to_https.unwrap_or(false),
rate_limit: conf.rate_limit,
x4xx_limit: conf.x4xx_limit,
healthcheck: None,
rate_limit: conf.rate_limit.unwrap_or(0),
x4xx_limit: conf.x4xx_limit.unwrap_or(0),
healthcheck: true,
redirect_to: None,
authorization: None,
});
@@ -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));
@@ -213,11 +213,7 @@ pub async fn getfromapi(url: &str, token: Option<String>, provider: &str) -> Opt
CONNECTOR.release_http_session(http_session.0, &peer, None).await;
if status == 200 && !body_bytes.is_empty() {
Some(body_bytes)
} else {
None
}
if status == 200 && !body_bytes.is_empty() { Some(body_bytes) } else { None }
}
fn parse_url(url: &str) -> Result<(&str, u16, &str, bool), &'static str> {
+2 -1
View File
@@ -1,8 +1,8 @@
use dashmap::DashMap;
use moka::sync::Cache;
use pingora_cache::MemCache;
use pingora_cache::eviction::simple_lru::Manager;
use pingora_cache::lock::CacheLock;
use pingora_cache::MemCache;
use pingora_limits::rate::Rate;
use std::collections::HashMap;
use std::net::IpAddr;
@@ -19,3 +19,4 @@ pub static CACHE_LOCK: LazyLock<CacheLock> = LazyLock::new(|| CacheLock::new(Dur
pub static EVICTION: OnceLock<Manager> = OnceLock::new();
pub static CACHE_TTL: OnceLock<u64> = OnceLock::new();
pub static CHALLENGES: LazyLock<RwLock<HashMap<String, String>>> = LazyLock::new(|| RwLock::new(HashMap::new()));
pub static DOMAINS: LazyLock<DashMap<String, bool>> = LazyLock::new(DashMap::new);
+9 -11
View File
@@ -1,5 +1,5 @@
use crate::utils::healthcheck;
use crate::utils::lazylock::REVERSE_STORE;
use crate::utils::lazylock::{DOMAINS, REVERSE_STORE};
use crate::utils::state::{is_first_run, mark_not_first_run};
use crate::utils::tools::{clone_dashmap, clone_dashmap_into, print_upstreams};
use crate::utils::types::*;
@@ -7,12 +7,10 @@ use dashmap::DashMap;
use log::{error, info, warn};
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::{Arc, LazyLock};
use std::{env, fs};
pub static DOMAINS: LazyLock<DashMap<String, bool>> = LazyLock::new(DashMap::new);
pub async fn load_configuration(d: &str, kind: &str) -> (Option<Configuration>, String) {
let mut conf_files = Vec::new();
let yaml_data = match kind {
@@ -172,10 +170,10 @@ async fn populate_headers_and_auth(config: &mut Configuration, parsed: &Config)
let server_global_headers: DashMap<Arc<str>, Vec<(String, Arc<str>)>> = DashMap::new();
server_global_headers.insert(Arc::from("/"), sh);
config.server_headers.insert(Arc::from("GLOBAL_SERVER_HEADERS"), server_global_headers);
config.extraparams.to_https = parsed.to_https;
config.extraparams.sticky_sessions = parsed.sticky_sessions;
config.extraparams.rate_limit = parsed.rate_limit;
config.extraparams.x4xx_limit = parsed.x4xx_limit;
config.extraparams.to_https = parsed.to_https.unwrap_or(false);
config.extraparams.sticky_sessions = parsed.sticky_sessions.unwrap_or(0);
config.extraparams.rate_limit = parsed.rate_limit.unwrap_or(0);
config.extraparams.x4xx_limit = parsed.x4xx_limit.unwrap_or(0);
if let Some(rate) = &parsed.rate_limit {
info!("Applied Global Rate Limit : {} request per second", rate);
@@ -228,9 +226,9 @@ async fn populate_file_upstreams(config: &mut Configuration, parsed: &Config) {
is_ssl: false,
is_http2: false,
to_https: path_config.to_https.unwrap_or(false),
rate_limit: path_config.rate_limit,
x4xx_limit: path_config.x4xx_limit,
healthcheck: path_config.healthcheck,
rate_limit: path_config.rate_limit.unwrap_or(0),
x4xx_limit: path_config.x4xx_limit.unwrap_or(0),
healthcheck: path_config.healthcheck.unwrap_or(true),
redirect_to: redirect_link,
authorization: path_auth,
}));
+7 -7
View File
@@ -4,7 +4,7 @@ use crate::utils::types::{Extraparams, InnerMapForJson, UpstreamSnapshotForJson,
use dashmap::DashMap;
use log::{error, info};
use privdrop::PrivDrop;
use serde_json::{json, Value};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use std::collections::{HashMap, HashSet};
use std::fmt::Write;
@@ -16,8 +16,8 @@ use std::os::unix::fs::MetadataExt;
use std::os::unix::fs::OpenOptionsExt;
use std::process::Command;
use std::str::FromStr;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::{env, fs, process, thread, time};
pub fn print_upstreams(upstreams: &UpstreamsDashMap, extraparams: &Extraparams) {
@@ -35,8 +35,8 @@ pub fn print_upstreams(upstreams: &UpstreamsDashMap, extraparams: &Extraparams)
f.is_ssl,
f.is_http2,
f.to_https,
f.rate_limit.unwrap_or(extraparams.rate_limit.unwrap_or(0)),
f.x4xx_limit.unwrap_or(extraparams.x4xx_limit.unwrap_or(0))
if f.rate_limit > 0 { f.rate_limit } else { extraparams.rate_limit },
if f.x4xx_limit > 0 { f.x4xx_limit } else { extraparams.x4xx_limit }
)
.unwrap();
}
@@ -138,9 +138,9 @@ pub fn clone_idmap_into(original: &UpstreamsDashMap, cloned: &UpstreamsIdMap) {
x.port,
x.is_http2,
x.to_https,
x.x4xx_limit.unwrap_or_default(),
x.rate_limit.unwrap_or_default(),
x.healthcheck.unwrap_or_default(),
x.x4xx_limit,
x.rate_limit,
x.healthcheck,
x.authorization
)
.unwrap_or(());
+20 -11
View File
@@ -1,8 +1,8 @@
use dashmap::DashMap;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::atomic::AtomicUsize;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
pub type UpstreamsDashMap = DashMap<Arc<str>, DashMap<Arc<str>, (Vec<Arc<InnerMap>>, AtomicUsize)>>;
@@ -11,11 +11,12 @@ pub type Headers = DashMap<Arc<str>, DashMap<Arc<str>, Vec<(String, Arc<str>)>>>
#[derive(Clone, Debug, Default)]
pub struct Extraparams {
pub to_https: Option<bool>,
pub sticky_sessions: Option<u64>,
pub sticky_sessions: u64,
pub rate_limit: isize,
pub x4xx_limit: u32,
pub to_https: bool,
pub ssl_verify: bool,
pub authentication: Option<Arc<InnerAuth>>,
pub rate_limit: Option<isize>,
pub x4xx_limit: Option<u32>,
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
@@ -133,6 +134,7 @@ pub struct AppConfig {
pub log_file: Option<String>,
pub log_pattern: Option<String>,
pub log_structured: Option<String>,
pub acme_dns_provider: Option<String>,
pub tcp_keepalive_idle: Option<u64>,
pub tcp_keepalive_interval: Option<u64>,
pub tcp_keepalive_count: Option<usize>,
@@ -151,13 +153,20 @@ pub struct InnerMap {
pub is_ssl: bool,
pub is_http2: bool,
pub to_https: bool,
pub rate_limit: Option<isize>,
pub x4xx_limit: Option<u32>,
pub healthcheck: Option<bool>,
pub rate_limit: isize,
pub x4xx_limit: u32,
pub healthcheck: bool,
pub redirect_to: Option<Arc<str>>,
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 {
@@ -183,9 +192,9 @@ pub struct InnerMapForJson {
pub is_ssl: bool,
pub is_http2: bool,
pub to_https: bool,
pub rate_limit: Option<isize>,
pub x4xx_limit: Option<u32>,
pub healthcheck: Option<bool>,
pub rate_limit: isize,
pub x4xx_limit: u32,
pub healthcheck: bool,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct UpstreamSnapshotForJson {
+10 -14
View File
@@ -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);
}
_ => {}
},