mirror of
https://github.com/sadoyan/aralez.git
synced 2026-05-30 03:44:06 +08:00
Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
faf840d102 | ||
|
|
d74883e16e | ||
|
|
d95bbfcd1a | ||
|
|
d301f7225f | ||
|
|
df02e523e4 | ||
|
|
2f5def5c3c | ||
|
|
1727a2b5e7 | ||
|
|
4bbedee27b | ||
|
|
37ef118861 | ||
|
|
00062b00da |
13
Dockerfile
Normal file
13
Dockerfile
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
FROM debian:trixie-slim
|
||||||
|
|
||||||
|
RUN apt-get update && apt-get install -y ca-certificates curl net-tools iputils-ping
|
||||||
|
RUN apt-get clean && rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
COPY aralez /usr/local/bin/aralez
|
||||||
|
|
||||||
|
RUN chmod +x /usr/local/bin/aralez
|
||||||
|
RUN mkdir -p /etc/aralez/certs/upstreams
|
||||||
|
|
||||||
|
WORKDIR /etc/aralez
|
||||||
|
|
||||||
|
ENTRYPOINT ["/usr/local/bin/aralez", "-c", "/etc/aralez/main.yaml"]
|
||||||
27
README.md
27
README.md
@@ -110,11 +110,7 @@ For getting the best performance on newer hardware use `aralez-x86_64-*.gz`.
|
|||||||
**Via docker**
|
**Via docker**
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
docker run -d \
|
docker run -d -v /path/to/config:/etc/aralez:rw -p 80:80 -p 443:443 sadoyan/aralez
|
||||||
-v /local/path/to/config:/etc/aralez:ro \
|
|
||||||
-p 80:80 \
|
|
||||||
-p 443:443 \
|
|
||||||
sadoyan/aralez
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Running the Proxy
|
## Running the Proxy
|
||||||
@@ -164,9 +160,10 @@ systemctl restart aralez.service.
|
|||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
provider: "file"
|
provider: "file"
|
||||||
sticky_sessions: false
|
sticky_sessions: 8600
|
||||||
to_https: false
|
to_https: false
|
||||||
rate_limit: 10
|
rate_limit: 20
|
||||||
|
x4xx_limit: 20
|
||||||
server_headers:
|
server_headers:
|
||||||
- "X-Forwarded-Proto:https"
|
- "X-Forwarded-Proto:https"
|
||||||
- "X-Forwarded-Port:443"
|
- "X-Forwarded-Port:443"
|
||||||
@@ -177,7 +174,8 @@ client_headers:
|
|||||||
myhost.mydomain.com:
|
myhost.mydomain.com:
|
||||||
paths:
|
paths:
|
||||||
"/":
|
"/":
|
||||||
rate_limit: 20
|
rate_limit: 10
|
||||||
|
x4xx_limit: 10
|
||||||
to_https: false
|
to_https: false
|
||||||
server_headers:
|
server_headers:
|
||||||
- "X-Something-Else:Foobar"
|
- "X-Something-Else:Foobar"
|
||||||
@@ -211,15 +209,20 @@ DEFAULT:
|
|||||||
|
|
||||||
**This means:**
|
**This means:**
|
||||||
|
|
||||||
- Sticky sessions are disabled globally. This setting applies to all upstreams. If enabled all requests will be 301 redirected to HTTPS.
|
- Sticky sessions are enabled globally. This setting applies to all upstreams. If enabled the value withh be set for `Max-Age=` cookie.
|
||||||
- HTTP to HTTPS redirect disabled globally, but can be overridden by `to_https` setting per upstream.
|
- HTTP to HTTPS redirect disabled globally, but can be overridden by `to_https` setting per upstream.
|
||||||
- All upstreams will receive custom headers : `X-Forwarded-Proto:https` and `X-Forwarded-Port:443`
|
- All upstreams will receive custom headers : `X-Forwarded-Proto:https` and `X-Forwarded-Port:443`
|
||||||
- Additionally, myhost.mydomain.com with path `/` will receive custom headers : `X-Another-Header:Hohohohoho` and `X-Something-Else:Foobar`
|
- Additionally, myhost.mydomain.com with path `/` will receive custom headers : `X-Another-Header:Hohohohoho` and `X-Something-Else:Foobar`
|
||||||
- Requests to each hosted domains will be limited to 10 requests per second per virtualhost.
|
- Requests with response 4xx to each hosted domains will be limited to 20 requests per second per virtualhost.
|
||||||
|
- Requests limits are calculated per requester ip plus requested virtualhost.
|
||||||
|
- If the requester exceeds the limit it will receive `429 Too Many Requests` error.
|
||||||
|
- Optional. Rate limiter will be disabled if the parameter is entirely removed from config.
|
||||||
|
- Requests to each hosted domains will be limited to 20 requests per second per virtualhost.
|
||||||
- Requests limits are calculated per requester ip plus requested virtualhost.
|
- Requests limits are calculated per requester ip plus requested virtualhost.
|
||||||
- If the requester exceeds the limit it will receive `429 Too Many Requests` error.
|
- If the requester exceeds the limit it will receive `429 Too Many Requests` error.
|
||||||
- Optional. Rate limiter will be disabled if the parameter is entirely removed from config.
|
- Optional. Rate limiter will be disabled if the parameter is entirely removed from config.
|
||||||
- Requests to `myhost.mydomain.com/` will be limited to 20 requests per second.
|
- Requests to `myhost.mydomain.com/` will be limited to 20 requests per second.
|
||||||
|
- Requests with 4xx responses to `myhost.mydomain.com/` will be limited to 10 requests per second.
|
||||||
- Requests to `myhost.mydomain.com/` will be proxied to `127.0.0.1` and `127.0.0.2`.
|
- Requests to `myhost.mydomain.com/` will be proxied to `127.0.0.1` and `127.0.0.2`.
|
||||||
- Plain HTTP to `myhost.mydomain.com/foo` will get 301 redirect to configured TLS port of Aralez.
|
- Plain HTTP to `myhost.mydomain.com/foo` will get 301 redirect to configured TLS port of Aralez.
|
||||||
- `myhost.mydomain.com/foo` will require authentication with JWT token, signed by `266463d1-210a-4787-9a81-4aacb37a8723`.
|
- `myhost.mydomain.com/foo` will require authentication with JWT token, signed by `266463d1-210a-4787-9a81-4aacb37a8723`.
|
||||||
@@ -231,10 +234,8 @@ DEFAULT:
|
|||||||
- Global headers (CORS for this case) will be injected to all upstreams.
|
- Global headers (CORS for this case) will be injected to all upstreams.
|
||||||
- Additional headers will be injected into the request for `myhost.mydomain.com`.
|
- Additional headers will be injected into the request for `myhost.mydomain.com`.
|
||||||
- You can choose any path, deep nested paths are supported, the best match chosen.
|
- You can choose any path, deep nested paths are supported, the best match chosen.
|
||||||
- All requests to servers will require JWT token authentication (You can comment out the authorization to disable it),
|
|
||||||
- Firs parameter specifies the mechanism of authorisation `jwt`
|
|
||||||
- Second is the secret key for validating `jwt` tokens
|
|
||||||
- `DEFAULT` catch up everything else and proxy to `127.0.0.1:3000`
|
- `DEFAULT` catch up everything else and proxy to `127.0.0.1:3000`
|
||||||
|
- This is a special upstream and in order to do the catch-up jub it must be **DEFAULT** all capitals
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -1,21 +1,17 @@
|
|||||||
use crate::utils::jwt::check_jwt;
|
use crate::utils::jwt::{check_jwt, JWT_TOKEN};
|
||||||
// use reqwest::Client;
|
use crate::utils::structs::InnerAuth;
|
||||||
use axum::http::StatusCode;
|
use axum::http::StatusCode;
|
||||||
use base64::engine::general_purpose::STANDARD;
|
use base64::engine::general_purpose::STANDARD;
|
||||||
use base64::Engine;
|
use base64::Engine;
|
||||||
use pingora_proxy::Session;
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::sync::{Arc, LazyLock};
|
|
||||||
use subtle::ConstantTimeEq;
|
|
||||||
use urlencoding::decode;
|
|
||||||
|
|
||||||
// use pingora::http::{RequestHeader, ResponseHeader, StatusCode};
|
|
||||||
use pingora::http::RequestHeader;
|
use pingora::http::RequestHeader;
|
||||||
// --------------------------------- //
|
|
||||||
use pingora_core::connectors::http::Connector;
|
use pingora_core::connectors::http::Connector;
|
||||||
use pingora_core::upstreams::peer::HttpPeer;
|
use pingora_core::upstreams::peer::HttpPeer;
|
||||||
use pingora_http::ResponseHeader;
|
use pingora_http::ResponseHeader;
|
||||||
// --------------------------------- //
|
use pingora_proxy::Session;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::LazyLock;
|
||||||
|
use subtle::ConstantTimeEq;
|
||||||
|
use urlencoding::decode;
|
||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
trait AuthValidator {
|
trait AuthValidator {
|
||||||
@@ -23,7 +19,7 @@ trait AuthValidator {
|
|||||||
}
|
}
|
||||||
struct BasicAuth<'a>(&'a str);
|
struct BasicAuth<'a>(&'a str);
|
||||||
struct ApiKeyAuth<'a>(&'a str);
|
struct ApiKeyAuth<'a>(&'a str);
|
||||||
struct JwtAuth<'a>(&'a str);
|
struct JwtAuth();
|
||||||
struct ForwardAuth<'a>(&'a str);
|
struct ForwardAuth<'a>(&'a str);
|
||||||
|
|
||||||
pub static AUTH_CONNECTOR: LazyLock<Connector> = LazyLock::new(|| Connector::new(None));
|
pub static AUTH_CONNECTOR: LazyLock<Connector> = LazyLock::new(|| Connector::new(None));
|
||||||
@@ -180,17 +176,18 @@ impl AuthValidator for ApiKeyAuth<'_> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl AuthValidator for JwtAuth<'_> {
|
impl AuthValidator for JwtAuth {
|
||||||
async fn validate(&self, session: &mut Session) -> bool {
|
async fn validate(&self, session: &mut Session) -> bool {
|
||||||
let jwtsecret = self.0;
|
if let Some(jwtsecret) = JWT_TOKEN.clone() {
|
||||||
if let Some(tok) = get_query_param(session, "araleztoken") {
|
if let Some(tok) = get_query_param(session, "araleztoken") {
|
||||||
return check_jwt(tok.as_str(), jwtsecret);
|
return check_jwt(tok.as_str(), jwtsecret.as_ref());
|
||||||
}
|
}
|
||||||
if let Some(auth_header) = session.get_header("authorization") {
|
if let Some(auth_header) = session.get_header("authorization") {
|
||||||
if let Ok(header_str) = auth_header.to_str() {
|
if let Ok(header_str) = auth_header.to_str() {
|
||||||
if let Some((scheme, token)) = header_str.split_once(' ') {
|
if let Some((scheme, token)) = header_str.split_once(' ') {
|
||||||
if scheme.eq_ignore_ascii_case("bearer") {
|
if scheme.eq_ignore_ascii_case("bearer") {
|
||||||
return check_jwt(token, jwtsecret);
|
return check_jwt(token, jwtsecret.as_ref());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -199,14 +196,14 @@ impl AuthValidator for JwtAuth<'_> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn authenticate(auth_type: &Arc<str>, credentials: &Arc<str>, session: &mut Session) -> bool {
|
pub async fn authenticate(auth: &InnerAuth, session: &mut Session) -> bool {
|
||||||
match &**auth_type {
|
match &*auth.auth_type {
|
||||||
"basic" => BasicAuth(credentials).validate(session).await,
|
"basic" => BasicAuth(&*auth.auth_cred).validate(session).await,
|
||||||
"apikey" => ApiKeyAuth(credentials).validate(session).await,
|
"apikey" => ApiKeyAuth(&*auth.auth_cred).validate(session).await,
|
||||||
"jwt" => JwtAuth(credentials).validate(session).await,
|
"jwt" => JwtAuth().validate(session).await,
|
||||||
"forward" => ForwardAuth(credentials).validate(session).await,
|
"forward" => ForwardAuth(&*auth.auth_cred).validate(session).await,
|
||||||
_ => {
|
_ => {
|
||||||
log::warn!("Unsupported authentication mechanism : {}", auth_type);
|
log::warn!("Unsupported authentication mechanism : {}", &*auth.auth_type);
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,13 +9,10 @@ use std::sync::Arc;
|
|||||||
pub struct APIUpstreamProvider {
|
pub struct APIUpstreamProvider {
|
||||||
pub config_api_enabled: bool,
|
pub config_api_enabled: bool,
|
||||||
pub address: String,
|
pub address: String,
|
||||||
pub masterkey: String,
|
pub masterkey: Option<String>,
|
||||||
pub certs_dir: String,
|
pub certs_dir: String,
|
||||||
pub config_dir: String,
|
pub config_dir: String,
|
||||||
pub upstreams_file: String,
|
pub upstreams_file: String,
|
||||||
// pub tls_address: Option<String>,
|
|
||||||
// pub tls_certificate: Option<String>,
|
|
||||||
// pub tls_key_file: Option<String>,
|
|
||||||
pub file_server_address: Option<String>,
|
pub file_server_address: Option<String>,
|
||||||
pub file_server_folder: Option<String>,
|
pub file_server_folder: Option<String>,
|
||||||
pub current_upstreams: Arc<UpstreamsDashMap>,
|
pub current_upstreams: Arc<UpstreamsDashMap>,
|
||||||
|
|||||||
@@ -69,6 +69,7 @@ async fn build_upstreams(fullist: &UpstreamsDashMap, method: &str, client: &Clie
|
|||||||
is_http2: is_h2,
|
is_http2: is_h2,
|
||||||
to_https: upstream.to_https,
|
to_https: upstream.to_https,
|
||||||
rate_limit: upstream.rate_limit,
|
rate_limit: upstream.rate_limit,
|
||||||
|
x4xx_limit: upstream.x4xx_limit,
|
||||||
healthcheck: upstream.healthcheck,
|
healthcheck: upstream.healthcheck,
|
||||||
redirect_to: upstream.redirect_to.clone(),
|
redirect_to: upstream.redirect_to.clone(),
|
||||||
authorization: upstream.authorization.clone(),
|
authorization: upstream.authorization.clone(),
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ pub async fn for_consul(url: String, token: Option<String>, conf: &GlobalService
|
|||||||
is_http2: false,
|
is_http2: false,
|
||||||
to_https: conf.to_https.unwrap_or(false),
|
to_https: conf.to_https.unwrap_or(false),
|
||||||
rate_limit: conf.rate_limit,
|
rate_limit: conf.rate_limit,
|
||||||
|
x4xx_limit: conf.x4xx_limit,
|
||||||
redirect_to: None,
|
redirect_to: None,
|
||||||
healthcheck: None,
|
healthcheck: None,
|
||||||
authorization: None,
|
authorization: None,
|
||||||
@@ -68,6 +69,7 @@ pub async fn for_kuber(url: &str, token: &str, conf: &GlobalServiceMapping) -> O
|
|||||||
is_http2: false,
|
is_http2: false,
|
||||||
to_https: conf.to_https.unwrap_or(false),
|
to_https: conf.to_https.unwrap_or(false),
|
||||||
rate_limit: conf.rate_limit,
|
rate_limit: conf.rate_limit,
|
||||||
|
x4xx_limit: conf.x4xx_limit,
|
||||||
healthcheck: None,
|
healthcheck: None,
|
||||||
redirect_to: None,
|
redirect_to: None,
|
||||||
authorization: None,
|
authorization: None,
|
||||||
|
|||||||
@@ -4,8 +4,9 @@ use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
|
|||||||
use moka::sync::Cache;
|
use moka::sync::Cache;
|
||||||
use moka::Expiry;
|
use moka::Expiry;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::env;
|
||||||
use std::hash::{Hash, Hasher};
|
use std::hash::{Hash, Hasher};
|
||||||
use std::sync::LazyLock;
|
use std::sync::{Arc, LazyLock};
|
||||||
use std::time::{Duration, Instant, SystemTime};
|
use std::time::{Duration, Instant, SystemTime};
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
@@ -23,6 +24,11 @@ struct Expired {
|
|||||||
|
|
||||||
static JWT_VALIDATION: LazyLock<Validation> = LazyLock::new(|| Validation::new(Algorithm::HS256));
|
static JWT_VALIDATION: LazyLock<Validation> = LazyLock::new(|| Validation::new(Algorithm::HS256));
|
||||||
|
|
||||||
|
pub static JWT_TOKEN: LazyLock<Option<Arc<str>>> = LazyLock::new(|| match env::var("JWT_KEY") {
|
||||||
|
Ok(key) if !key.is_empty() => Some(Arc::from(key.as_str())),
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
|
|
||||||
static JWT_CACHE: LazyLock<Cache<u64, u64>> = LazyLock::new(|| Cache::builder().max_capacity(100_000).expire_after(JwtExpiry).build());
|
static JWT_CACHE: LazyLock<Cache<u64, u64>> = LazyLock::new(|| Cache::builder().max_capacity(100_000).expire_after(JwtExpiry).build());
|
||||||
struct JwtExpiry;
|
struct JwtExpiry;
|
||||||
impl Expiry<u64, u64> for JwtExpiry {
|
impl Expiry<u64, u64> for JwtExpiry {
|
||||||
|
|||||||
@@ -11,10 +11,10 @@ use log4rs::{
|
|||||||
encode::pattern::PatternEncoder,
|
encode::pattern::PatternEncoder,
|
||||||
};
|
};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::fs;
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::sync::atomic::AtomicUsize;
|
use std::sync::atomic::AtomicUsize;
|
||||||
use std::sync::{Arc, LazyLock};
|
use std::sync::{Arc, LazyLock};
|
||||||
|
use std::{env, fs};
|
||||||
|
|
||||||
pub static DOMAINS: LazyLock<DashMap<String, bool>> = LazyLock::new(DashMap::new);
|
pub static DOMAINS: LazyLock<DashMap<String, bool>> = LazyLock::new(DashMap::new);
|
||||||
|
|
||||||
@@ -85,6 +85,7 @@ pub async fn load_configuration(d: &str, kind: &str) -> (Option<Configuration>,
|
|||||||
let mut parsed: Config = match serde_yml::from_str(&yaml_data) {
|
let mut parsed: Config = match serde_yml::from_str(&yaml_data) {
|
||||||
Ok(cfg) => cfg,
|
Ok(cfg) => cfg,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
|
println!("================================================");
|
||||||
error!("Failed to parse upstreams file: {}", e);
|
error!("Failed to parse upstreams file: {}", e);
|
||||||
return (None, e.to_string());
|
return (None, e.to_string());
|
||||||
}
|
}
|
||||||
@@ -136,6 +137,7 @@ async fn populate_headers_and_auth(config: &mut Configuration, parsed: &Config)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let global_headers: DashMap<Arc<str>, Vec<(String, Arc<str>)>> = DashMap::new();
|
let global_headers: DashMap<Arc<str>, Vec<(String, Arc<str>)>> = DashMap::new();
|
||||||
global_headers.insert(Arc::from("/"), ch);
|
global_headers.insert(Arc::from("/"), ch);
|
||||||
config.client_headers.insert(Arc::from("GLOBAL_CLIENT_HEADERS"), global_headers);
|
config.client_headers.insert(Arc::from("GLOBAL_CLIENT_HEADERS"), global_headers);
|
||||||
@@ -154,6 +156,7 @@ async fn populate_headers_and_auth(config: &mut Configuration, parsed: &Config)
|
|||||||
config.extraparams.to_https = parsed.to_https;
|
config.extraparams.to_https = parsed.to_https;
|
||||||
config.extraparams.sticky_sessions = parsed.sticky_sessions;
|
config.extraparams.sticky_sessions = parsed.sticky_sessions;
|
||||||
config.extraparams.rate_limit = parsed.rate_limit;
|
config.extraparams.rate_limit = parsed.rate_limit;
|
||||||
|
config.extraparams.x4xx_limit = parsed.x4xx_limit;
|
||||||
|
|
||||||
if let Some(rate) = &parsed.rate_limit {
|
if let Some(rate) = &parsed.rate_limit {
|
||||||
info!("Applied Global Rate Limit : {} request per second", rate);
|
info!("Applied Global Rate Limit : {} request per second", rate);
|
||||||
@@ -162,7 +165,7 @@ async fn populate_headers_and_auth(config: &mut Configuration, parsed: &Config)
|
|||||||
if let Some(pa) = &parsed.authorization {
|
if let Some(pa) = &parsed.authorization {
|
||||||
let y: InnerAuth = InnerAuth {
|
let y: InnerAuth = InnerAuth {
|
||||||
auth_type: Arc::from(pa.auth_type.clone()),
|
auth_type: Arc::from(pa.auth_type.clone()),
|
||||||
auth_cred: Arc::from(pa.auth_cred.clone()),
|
auth_cred: Arc::from(pa.auth_cred.clone().unwrap_or_default()),
|
||||||
};
|
};
|
||||||
config.extraparams.authentication = Some(Arc::from(y));
|
config.extraparams.authentication = Some(Arc::from(y));
|
||||||
}
|
}
|
||||||
@@ -191,10 +194,11 @@ async fn populate_file_upstreams(config: &mut Configuration, parsed: &Config) {
|
|||||||
if let Some(pa) = &path_config.authorization {
|
if let Some(pa) = &path_config.authorization {
|
||||||
let y: InnerAuth = InnerAuth {
|
let y: InnerAuth = InnerAuth {
|
||||||
auth_type: Arc::from(pa.auth_type.clone()),
|
auth_type: Arc::from(pa.auth_type.clone()),
|
||||||
auth_cred: Arc::from(pa.auth_cred.clone()),
|
auth_cred: Arc::from(pa.auth_cred.clone().unwrap_or_default()),
|
||||||
};
|
};
|
||||||
path_auth = Some(Arc::from(y));
|
path_auth = Some(Arc::from(y));
|
||||||
}
|
}
|
||||||
|
|
||||||
let redirect_link = path_config.redirect_to.as_ref().map(|www| Arc::from(www.as_str()));
|
let redirect_link = path_config.redirect_to.as_ref().map(|www| Arc::from(www.as_str()));
|
||||||
if let Some((ip, port_str)) = server.split_once(':') {
|
if let Some((ip, port_str)) = server.split_once(':') {
|
||||||
if let Ok(port) = port_str.parse::<u16>() {
|
if let Ok(port) = port_str.parse::<u16>() {
|
||||||
@@ -205,6 +209,7 @@ async fn populate_file_upstreams(config: &mut Configuration, parsed: &Config) {
|
|||||||
is_http2: false,
|
is_http2: false,
|
||||||
to_https: path_config.to_https.unwrap_or(false),
|
to_https: path_config.to_https.unwrap_or(false),
|
||||||
rate_limit: path_config.rate_limit,
|
rate_limit: path_config.rate_limit,
|
||||||
|
x4xx_limit: path_config.x4xx_limit,
|
||||||
healthcheck: path_config.healthcheck,
|
healthcheck: path_config.healthcheck,
|
||||||
redirect_to: redirect_link,
|
redirect_to: redirect_link,
|
||||||
authorization: path_auth,
|
authorization: path_auth,
|
||||||
@@ -236,6 +241,11 @@ pub fn parce_main_config(path: &str) -> AppConfig {
|
|||||||
let reply = DashMap::new();
|
let reply = DashMap::new();
|
||||||
let cfg: HashMap<String, String> = serde_yml::from_str(&data).expect("Failed to parse main config file");
|
let cfg: HashMap<String, String> = serde_yml::from_str(&data).expect("Failed to parse main config file");
|
||||||
let mut cfo: AppConfig = serde_yml::from_str(&data).expect("Failed to parse main config file");
|
let mut cfo: AppConfig = serde_yml::from_str(&data).expect("Failed to parse main config file");
|
||||||
|
|
||||||
|
if let Ok(jwt_key) = env::var("JWT_KEY") {
|
||||||
|
cfo.master_key = Some(jwt_key);
|
||||||
|
};
|
||||||
|
|
||||||
log_builder(&cfo, &cfo.log_file);
|
log_builder(&cfo, &cfo.log_file);
|
||||||
cfo.hc_method = cfo.hc_method.to_uppercase();
|
cfo.hc_method = cfo.hc_method.to_uppercase();
|
||||||
for (k, v) in cfg {
|
for (k, v) in cfg {
|
||||||
@@ -287,27 +297,6 @@ fn parce_tls_grades(what: Option<String>) -> Option<String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
fn log_builder1(conf: &AppConfig) {
|
|
||||||
let log_level = conf.log_level.clone();
|
|
||||||
unsafe {
|
|
||||||
match log_level.as_str() {
|
|
||||||
"info" => env::set_var("RUST_LOG", "info"),
|
|
||||||
"error" => env::set_var("RUST_LOG", "error"),
|
|
||||||
"warn" => env::set_var("RUST_LOG", "warn"),
|
|
||||||
"debug" => env::set_var("RUST_LOG", "debug"),
|
|
||||||
"trace" => env::set_var("RUST_LOG", "trace"),
|
|
||||||
"off" => env::set_var("RUST_LOG", "off"),
|
|
||||||
_ => {
|
|
||||||
println!("Error reading log level, defaulting to: INFO");
|
|
||||||
env::set_var("RUST_LOG", "info")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
env_logger::builder().init();
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
|
|
||||||
pub fn build_headers(path_config: &Option<Vec<String>>, _config: &Configuration, hl: &mut Vec<(String, Arc<str>)>) {
|
pub fn build_headers(path_config: &Option<Vec<String>>, _config: &Configuration, hl: &mut Vec<(String, Arc<str>)>) {
|
||||||
if let Some(headers) = &path_config {
|
if let Some(headers) = &path_config {
|
||||||
for header in headers {
|
for header in headers {
|
||||||
|
|||||||
@@ -14,9 +14,10 @@ pub type Headers = DashMap<Arc<str>, DashMap<Arc<str>, Vec<(String, Arc<str>)>>>
|
|||||||
#[derive(Clone, Debug, Default)]
|
#[derive(Clone, Debug, Default)]
|
||||||
pub struct Extraparams {
|
pub struct Extraparams {
|
||||||
pub to_https: Option<bool>,
|
pub to_https: Option<bool>,
|
||||||
pub sticky_sessions: bool,
|
pub sticky_sessions: Option<u64>,
|
||||||
pub authentication: Option<Arc<InnerAuth>>,
|
pub authentication: Option<Arc<InnerAuth>>,
|
||||||
pub rate_limit: Option<isize>,
|
pub rate_limit: Option<isize>,
|
||||||
|
pub x4xx_limit: Option<u32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
|
||||||
@@ -25,8 +26,9 @@ pub struct GlobalServiceMapping {
|
|||||||
pub hostname: String,
|
pub hostname: String,
|
||||||
pub path: Option<String>,
|
pub path: Option<String>,
|
||||||
pub to_https: Option<bool>,
|
pub to_https: Option<bool>,
|
||||||
pub sticky_sessions: Option<bool>,
|
pub sticky_sessions: Option<u64>,
|
||||||
pub rate_limit: Option<isize>,
|
pub rate_limit: Option<isize>,
|
||||||
|
pub x4xx_limit: Option<u32>,
|
||||||
pub client_headers: Option<Vec<String>>,
|
pub client_headers: Option<Vec<String>>,
|
||||||
pub server_headers: Option<Vec<String>>,
|
pub server_headers: Option<Vec<String>>,
|
||||||
}
|
}
|
||||||
@@ -48,7 +50,7 @@ pub struct Consul {
|
|||||||
pub struct Config {
|
pub struct Config {
|
||||||
pub provider: String,
|
pub provider: String,
|
||||||
pub to_https: Option<bool>,
|
pub to_https: Option<bool>,
|
||||||
pub sticky_sessions: bool,
|
pub sticky_sessions: Option<u64>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub upstreams: Option<HashMap<String, HostConfig>>,
|
pub upstreams: Option<HashMap<String, HostConfig>>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@@ -65,28 +67,30 @@ pub struct Config {
|
|||||||
pub kubernetes: Option<Kubernetes>,
|
pub kubernetes: Option<Kubernetes>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub rate_limit: Option<isize>,
|
pub rate_limit: Option<isize>,
|
||||||
|
pub x4xx_limit: Option<u32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||||
pub struct HostConfig {
|
pub struct HostConfig {
|
||||||
pub paths: HashMap<String, PathConfig>,
|
pub paths: HashMap<String, PathConfig>,
|
||||||
pub rate_limit: Option<isize>,
|
pub rate_limit: Option<isize>,
|
||||||
|
pub x4xx_limit: Option<u32>,
|
||||||
}
|
}
|
||||||
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
|
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
|
||||||
pub struct Auth {
|
pub struct Auth {
|
||||||
#[serde(rename = "type")]
|
#[serde(rename = "type")]
|
||||||
pub auth_type: String,
|
pub auth_type: String,
|
||||||
#[serde(rename = "data")]
|
#[serde(rename = "data")]
|
||||||
pub auth_cred: String,
|
pub auth_cred: Option<String>,
|
||||||
}
|
}
|
||||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||||
pub struct PathConfig {
|
pub struct PathConfig {
|
||||||
pub servers: Vec<String>,
|
pub servers: Vec<String>,
|
||||||
pub to_https: Option<bool>,
|
pub to_https: Option<bool>,
|
||||||
pub sticky_sessions: Option<bool>,
|
|
||||||
pub client_headers: Option<Vec<String>>,
|
pub client_headers: Option<Vec<String>>,
|
||||||
pub server_headers: Option<Vec<String>>,
|
pub server_headers: Option<Vec<String>>,
|
||||||
pub rate_limit: Option<isize>,
|
pub rate_limit: Option<isize>,
|
||||||
|
pub x4xx_limit: Option<u32>,
|
||||||
pub healthcheck: Option<bool>,
|
pub healthcheck: Option<bool>,
|
||||||
pub redirect_to: Option<String>,
|
pub redirect_to: Option<String>,
|
||||||
pub authorization: Option<Auth>,
|
pub authorization: Option<Auth>,
|
||||||
@@ -108,7 +112,7 @@ pub struct AppConfig {
|
|||||||
pub hc_method: String,
|
pub hc_method: String,
|
||||||
pub upstreams_conf: String,
|
pub upstreams_conf: String,
|
||||||
pub log_level: String,
|
pub log_level: String,
|
||||||
pub master_key: String,
|
pub master_key: Option<String>,
|
||||||
pub config_address: String,
|
pub config_address: String,
|
||||||
pub proxy_address_http: String,
|
pub proxy_address_http: String,
|
||||||
pub config_api_enabled: bool,
|
pub config_api_enabled: bool,
|
||||||
@@ -142,6 +146,7 @@ pub struct InnerMap {
|
|||||||
pub is_http2: bool,
|
pub is_http2: bool,
|
||||||
pub to_https: bool,
|
pub to_https: bool,
|
||||||
pub rate_limit: Option<isize>,
|
pub rate_limit: Option<isize>,
|
||||||
|
pub x4xx_limit: Option<u32>,
|
||||||
pub healthcheck: Option<bool>,
|
pub healthcheck: Option<bool>,
|
||||||
pub redirect_to: Option<Arc<str>>,
|
pub redirect_to: Option<Arc<str>>,
|
||||||
pub authorization: Option<Arc<InnerAuth>>,
|
pub authorization: Option<Arc<InnerAuth>>,
|
||||||
@@ -157,6 +162,7 @@ impl InnerMap {
|
|||||||
is_http2: Default::default(),
|
is_http2: Default::default(),
|
||||||
to_https: Default::default(),
|
to_https: Default::default(),
|
||||||
rate_limit: Default::default(),
|
rate_limit: Default::default(),
|
||||||
|
x4xx_limit: Default::default(),
|
||||||
healthcheck: Default::default(),
|
healthcheck: Default::default(),
|
||||||
redirect_to: Default::default(),
|
redirect_to: Default::default(),
|
||||||
authorization: Default::default(),
|
authorization: Default::default(),
|
||||||
@@ -172,6 +178,7 @@ pub struct InnerMapForJson {
|
|||||||
pub is_http2: bool,
|
pub is_http2: bool,
|
||||||
pub to_https: bool,
|
pub to_https: bool,
|
||||||
pub rate_limit: Option<isize>,
|
pub rate_limit: Option<isize>,
|
||||||
|
pub x4xx_limit: Option<u32>,
|
||||||
pub healthcheck: Option<bool>,
|
pub healthcheck: Option<bool>,
|
||||||
}
|
}
|
||||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||||
|
|||||||
@@ -29,13 +29,14 @@ pub fn print_upstreams(upstreams: &UpstreamsDashMap) {
|
|||||||
for f in path_entry.value().0.clone() {
|
for f in path_entry.value().0.clone() {
|
||||||
writeln!(
|
writeln!(
|
||||||
out,
|
out,
|
||||||
" IP: {}, Port: {}, SSL: {}, H2: {}, To HTTPS: {}, Rate Limit: {}",
|
" IP: {}, Port: {}, SSL: {}, H2: {}, To HTTPS: {}, Rate Limit: {}, 4xx Limit: {}",
|
||||||
f.address,
|
f.address,
|
||||||
f.port,
|
f.port,
|
||||||
f.is_ssl,
|
f.is_ssl,
|
||||||
f.is_http2,
|
f.is_http2,
|
||||||
f.to_https,
|
f.to_https,
|
||||||
f.rate_limit.unwrap_or(0)
|
f.rate_limit.unwrap_or(0),
|
||||||
|
f.x4xx_limit.unwrap_or(0)
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
@@ -152,13 +153,14 @@ pub fn clone_idmap_into(original: &UpstreamsDashMap, cloned: &UpstreamsIdMap) {
|
|||||||
let mut id = String::new();
|
let mut id = String::new();
|
||||||
write!(
|
write!(
|
||||||
&mut id,
|
&mut id,
|
||||||
"{}:{}:{}:{}:{}:{}:{}:{:?}",
|
"{}:{}:{}:{}:{}:{}:{}:{}:{:?}",
|
||||||
outer_entry.key(),
|
outer_entry.key(),
|
||||||
x.address,
|
x.address,
|
||||||
x.port,
|
x.port,
|
||||||
x.is_http2,
|
x.is_http2,
|
||||||
x.to_https,
|
x.to_https,
|
||||||
x.rate_limit.unwrap_or_default(),
|
x.rate_limit.unwrap_or_default(),
|
||||||
|
x.x4xx_limit.unwrap_or_default(),
|
||||||
x.healthcheck.unwrap_or_default(),
|
x.healthcheck.unwrap_or_default(),
|
||||||
x.authorization
|
x.authorization
|
||||||
)
|
)
|
||||||
@@ -177,6 +179,7 @@ pub fn clone_idmap_into(original: &UpstreamsDashMap, cloned: &UpstreamsIdMap) {
|
|||||||
is_http2: false,
|
is_http2: false,
|
||||||
to_https: false,
|
to_https: false,
|
||||||
rate_limit: None,
|
rate_limit: None,
|
||||||
|
x4xx_limit: None,
|
||||||
healthcheck: None,
|
healthcheck: None,
|
||||||
redirect_to: None,
|
redirect_to: None,
|
||||||
authorization: None,
|
authorization: None,
|
||||||
@@ -303,6 +306,7 @@ pub fn upstreams_to_json(upstreams: &UpstreamsDashMap) -> serde_json::Result<Str
|
|||||||
is_http2: a.is_http2,
|
is_http2: a.is_http2,
|
||||||
to_https: a.to_https,
|
to_https: a.to_https,
|
||||||
rate_limit: a.rate_limit,
|
rate_limit: a.rate_limit,
|
||||||
|
x4xx_limit: a.x4xx_limit,
|
||||||
healthcheck: a.healthcheck,
|
healthcheck: a.healthcheck,
|
||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
|
|||||||
@@ -99,6 +99,7 @@ impl BackgroundService for LB {
|
|||||||
new.sticky_sessions = ss.extraparams.sticky_sessions;
|
new.sticky_sessions = ss.extraparams.sticky_sessions;
|
||||||
new.authentication = ss.extraparams.authentication.clone();
|
new.authentication = ss.extraparams.authentication.clone();
|
||||||
new.rate_limit = ss.extraparams.rate_limit;
|
new.rate_limit = ss.extraparams.rate_limit;
|
||||||
|
new.x4xx_limit = ss.extraparams.x4xx_limit;
|
||||||
self.extraparams.store(Arc::new(new));
|
self.extraparams.store(Arc::new(new));
|
||||||
self.client_headers.clear();
|
self.client_headers.clear();
|
||||||
self.server_headers.clear();
|
self.server_headers.clear();
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ use async_trait::async_trait;
|
|||||||
use axum::body::Bytes;
|
use axum::body::Bytes;
|
||||||
use dashmap::DashMap;
|
use dashmap::DashMap;
|
||||||
use log::{debug, error, warn};
|
use log::{debug, error, warn};
|
||||||
|
use moka::sync::Cache;
|
||||||
use pingora::http::{RequestHeader, ResponseHeader, StatusCode};
|
use pingora::http::{RequestHeader, ResponseHeader, StatusCode};
|
||||||
use pingora::prelude::*;
|
use pingora::prelude::*;
|
||||||
use pingora::ErrorSource::Upstream;
|
use pingora::ErrorSource::Upstream;
|
||||||
@@ -17,6 +18,7 @@ use pingora_proxy::{ProxyHttp, Session};
|
|||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
use std::cell::RefCell;
|
use std::cell::RefCell;
|
||||||
use std::fmt::Write;
|
use std::fmt::Write;
|
||||||
|
use std::net::IpAddr;
|
||||||
use std::sync::{Arc, LazyLock};
|
use std::sync::{Arc, LazyLock};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use tokio::time::Instant;
|
use tokio::time::Instant;
|
||||||
@@ -24,6 +26,7 @@ use tokio::time::Instant;
|
|||||||
static REVERSE_STORE: LazyLock<DashMap<String, String>> = LazyLock::new(DashMap::new);
|
static REVERSE_STORE: LazyLock<DashMap<String, String>> = LazyLock::new(DashMap::new);
|
||||||
thread_local! {static IP_BUFFER: RefCell<String> = RefCell::new(String::with_capacity(50));}
|
thread_local! {static IP_BUFFER: RefCell<String> = RefCell::new(String::with_capacity(50));}
|
||||||
pub static RATE_LIMITER: LazyLock<Rate> = LazyLock::new(|| Rate::new(Duration::from_secs(1)));
|
pub static RATE_LIMITER: LazyLock<Rate> = LazyLock::new(|| Rate::new(Duration::from_secs(1)));
|
||||||
|
pub static REQUESTS_4XX: LazyLock<Cache<IpAddr, u32>> = LazyLock::new(|| Cache::builder().time_to_live(Duration::from_secs(1)).build());
|
||||||
pub static LOCALHOST: LazyLock<Arc<str>> = LazyLock::new(|| Arc::from("localhost"));
|
pub static LOCALHOST: LazyLock<Arc<str>> = LazyLock::new(|| Arc::from("localhost"));
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@@ -39,12 +42,12 @@ pub struct LB {
|
|||||||
|
|
||||||
pub struct Context {
|
pub struct Context {
|
||||||
backend_id: Option<String>,
|
backend_id: Option<String>,
|
||||||
sticky_sessions: bool,
|
|
||||||
start_time: Instant,
|
start_time: Instant,
|
||||||
hostname: Option<Arc<str>>,
|
hostname: Option<Arc<str>>,
|
||||||
upstream_peer: Option<Arc<InnerMap>>,
|
upstream_peer: Option<Arc<InnerMap>>,
|
||||||
extraparams: arc_swap::Guard<Arc<Extraparams>>,
|
extraparams: arc_swap::Guard<Arc<Extraparams>>,
|
||||||
client_headers: Option<Vec<(String, Arc<str>)>>,
|
client_headers: Option<Vec<(String, Arc<str>)>>,
|
||||||
|
x4xx_limit: Option<u32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
@@ -53,12 +56,12 @@ impl ProxyHttp for LB {
|
|||||||
fn new_ctx(&self) -> Self::CTX {
|
fn new_ctx(&self) -> Self::CTX {
|
||||||
Context {
|
Context {
|
||||||
backend_id: None,
|
backend_id: None,
|
||||||
sticky_sessions: false,
|
|
||||||
start_time: Instant::now(),
|
start_time: Instant::now(),
|
||||||
hostname: None,
|
hostname: None,
|
||||||
upstream_peer: None,
|
upstream_peer: None,
|
||||||
extraparams: self.extraparams.load(),
|
extraparams: self.extraparams.load(),
|
||||||
client_headers: None,
|
client_headers: None,
|
||||||
|
x4xx_limit: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async fn request_filter(&self, session: &mut Session, _ctx: &mut Self::CTX) -> Result<bool> {
|
async fn request_filter(&self, session: &mut Session, _ctx: &mut Self::CTX) -> Result<bool> {
|
||||||
@@ -66,7 +69,7 @@ impl ProxyHttp for LB {
|
|||||||
let hostname = return_header_host_from_upstream(session, &self.ump_upst);
|
let hostname = return_header_host_from_upstream(session, &self.ump_upst);
|
||||||
_ctx.hostname = hostname;
|
_ctx.hostname = hostname;
|
||||||
let mut backend_id = None;
|
let mut backend_id = None;
|
||||||
if _ctx.extraparams.sticky_sessions {
|
if let Some(_) = _ctx.extraparams.sticky_sessions {
|
||||||
if let Some(cookies) = session.req_header().headers.get("cookie") {
|
if let Some(cookies) = session.req_header().headers.get("cookie") {
|
||||||
if let Ok(cookie_str) = cookies.to_str() {
|
if let Ok(cookie_str) = cookies.to_str() {
|
||||||
if let Some(pos) = cookie_str.find("backend_id=") {
|
if let Some(pos) = cookie_str.find("backend_id=") {
|
||||||
@@ -85,13 +88,28 @@ impl ProxyHttp for LB {
|
|||||||
None => return Ok(false),
|
None => return Ok(false),
|
||||||
Some(ref innermap) => {
|
Some(ref innermap) => {
|
||||||
if let Some(auth) = _ctx.extraparams.authentication.as_ref().or(innermap.authorization.as_ref()) {
|
if let Some(auth) = _ctx.extraparams.authentication.as_ref().or(innermap.authorization.as_ref()) {
|
||||||
if !authenticate(&auth.auth_type, &auth.auth_cred, session).await {
|
if !authenticate(&auth, session).await {
|
||||||
let _ = session.respond_error(401).await;
|
let _ = session.respond_error(401).await;
|
||||||
warn!("Forbidden: {:?}, {}", session.client_addr(), session.req_header().uri.path());
|
warn!("Forbidden: {:?}, {}", session.client_addr(), session.req_header().uri.path());
|
||||||
return Ok(true);
|
return Ok(true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if let Some(rate) = innermap.x4xx_limit.or(_ctx.extraparams.x4xx_limit) {
|
||||||
|
_ctx.x4xx_limit = innermap.x4xx_limit;
|
||||||
|
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 {
|
||||||
|
let header = ResponseHeader::build(429, None)?;
|
||||||
|
session.set_keepalive(None);
|
||||||
|
session.write_response_header(Box::new(header), true).await?;
|
||||||
|
if let (Some(oi), Some(oa)) = (&_ctx.hostname, rate_key) {
|
||||||
|
warn!("Limit 4XX: {}-rps exceed on {} from {}", rate, oi, oa);
|
||||||
|
}
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
if let Some(rate) = innermap.rate_limit.or(_ctx.extraparams.rate_limit) {
|
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 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);
|
let curr_window_requests = RATE_LIMITER.observe(&rate_key, 1);
|
||||||
@@ -99,7 +117,9 @@ impl ProxyHttp for LB {
|
|||||||
let header = ResponseHeader::build(429, None)?;
|
let header = ResponseHeader::build(429, None)?;
|
||||||
session.set_keepalive(None);
|
session.set_keepalive(None);
|
||||||
session.write_response_header(Box::new(header), true).await?;
|
session.write_response_header(Box::new(header), true).await?;
|
||||||
debug!("Rate limited: {:?}, {}", rate_key, rate);
|
if let (Some(oi), Some(oa)) = (&_ctx.hostname, rate_key) {
|
||||||
|
warn!("Limit: {}-rps exceed on {} from {}", rate, oi, oa);
|
||||||
|
}
|
||||||
return Ok(true);
|
return Ok(true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -161,7 +181,7 @@ impl ProxyHttp for LB {
|
|||||||
peer.options.verify_cert = false;
|
peer.options.verify_cert = false;
|
||||||
peer.options.verify_hostname = false;
|
peer.options.verify_hostname = false;
|
||||||
}
|
}
|
||||||
if ctx.extraparams.sticky_sessions {
|
if let Some(_) = ctx.extraparams.sticky_sessions {
|
||||||
let mut s = String::with_capacity(64);
|
let mut s = String::with_capacity(64);
|
||||||
write!(
|
write!(
|
||||||
&mut s,
|
&mut s,
|
||||||
@@ -177,7 +197,6 @@ impl ProxyHttp for LB {
|
|||||||
)
|
)
|
||||||
.unwrap_or(());
|
.unwrap_or(());
|
||||||
ctx.backend_id = Some(s);
|
ctx.backend_id = Some(s);
|
||||||
ctx.sticky_sessions = true;
|
|
||||||
}
|
}
|
||||||
Ok(peer)
|
Ok(peer)
|
||||||
}
|
}
|
||||||
@@ -237,7 +256,7 @@ impl ProxyHttp for LB {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
async fn response_filter(&self, _session: &mut Session, _upstream_response: &mut ResponseHeader, ctx: &mut Self::CTX) -> Result<()> {
|
async fn response_filter(&self, _session: &mut Session, _upstream_response: &mut ResponseHeader, ctx: &mut Self::CTX) -> Result<()> {
|
||||||
if ctx.sticky_sessions {
|
if let Some(val) = ctx.extraparams.sticky_sessions {
|
||||||
if let Some(bid) = &ctx.backend_id {
|
if let Some(bid) = &ctx.backend_id {
|
||||||
let tt = if let Some(existing) = REVERSE_STORE.get(bid) {
|
let tt = if let Some(existing) = REVERSE_STORE.get(bid) {
|
||||||
existing.value().clone()
|
existing.value().clone()
|
||||||
@@ -255,7 +274,11 @@ impl ProxyHttp for LB {
|
|||||||
let mut buf = String::with_capacity(80);
|
let mut buf = String::with_capacity(80);
|
||||||
buf.push_str("backend_id=");
|
buf.push_str("backend_id=");
|
||||||
buf.push_str(&tt);
|
buf.push_str(&tt);
|
||||||
buf.push_str("; Path=/; Max-Age=86400; HttpOnly; SameSite=Lax");
|
buf.push_str("; Path=/; Max-Age=");
|
||||||
|
buf.push_str(&val.to_string());
|
||||||
|
buf.push_str("; HttpOnly; SameSite=Lax");
|
||||||
|
// buf.push_str("; Path=/; Max-Age=86400; HttpOnly; SameSite=Lax");
|
||||||
|
// println!("{}", buf);
|
||||||
let _ = _upstream_response.insert_header("set-cookie", buf.as_str());
|
let _ = _upstream_response.insert_header("set-cookie", buf.as_str());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -280,6 +303,14 @@ impl ProxyHttp for LB {
|
|||||||
};
|
};
|
||||||
calc_metrics(m);
|
calc_metrics(m);
|
||||||
ACTIVE_SESSIONS.dec();
|
ACTIVE_SESSIONS.dec();
|
||||||
|
if let Some(_) = ctx.x4xx_limit.or(ctx.extraparams.x4xx_limit) {
|
||||||
|
if 400 <= response_code && response_code <= 499 {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -33,9 +33,10 @@ pub fn run() {
|
|||||||
|
|
||||||
let ec_config = Arc::new(ArcSwap::from_pointee(Extraparams {
|
let ec_config = Arc::new(ArcSwap::from_pointee(Extraparams {
|
||||||
to_https: None,
|
to_https: None,
|
||||||
sticky_sessions: false,
|
sticky_sessions: None,
|
||||||
authentication: None,
|
authentication: None,
|
||||||
rate_limit: None,
|
rate_limit: None,
|
||||||
|
x4xx_limit: None,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
let cfg = Arc::new(maincfg);
|
let cfg = Arc::new(maincfg);
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ use crate::utils::structs::{Config, Configuration, UpstreamsDashMap};
|
|||||||
use crate::utils::tools::{upstreams_liveness_json, upstreams_to_json};
|
use crate::utils::tools::{upstreams_liveness_json, upstreams_to_json};
|
||||||
use axum::body::Body;
|
use axum::body::Body;
|
||||||
use axum::extract::{Query, State};
|
use axum::extract::{Query, State};
|
||||||
use axum::http::{header::HeaderMap, Response, StatusCode};
|
use axum::http::{Response, StatusCode};
|
||||||
use axum::response::IntoResponse;
|
use axum::response::IntoResponse;
|
||||||
use axum::routing::{any, get, post};
|
use axum::routing::{any, get, post};
|
||||||
use axum::{Json, Router};
|
use axum::{Json, Router};
|
||||||
@@ -21,7 +21,6 @@ use serde::Serialize;
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||||
use subtle::ConstantTimeEq;
|
|
||||||
use tokio::net::TcpListener;
|
use tokio::net::TcpListener;
|
||||||
use tower_http::services::ServeDir;
|
use tower_http::services::ServeDir;
|
||||||
|
|
||||||
@@ -32,7 +31,7 @@ struct OutToken {
|
|||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct AppState {
|
struct AppState {
|
||||||
master_key: String,
|
master_key: Option<String>,
|
||||||
cert_creds: String,
|
cert_creds: String,
|
||||||
certs_dir: String,
|
certs_dir: String,
|
||||||
upstreams_file: String,
|
upstreams_file: String,
|
||||||
@@ -95,32 +94,27 @@ pub async fn run_server(config: &APIUpstreamProvider, mut to_return: Sender<Conf
|
|||||||
axum::serve(listener, app).await.unwrap();
|
axum::serve(listener, app).await.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn conf(State(st): State<AppState>, Query(params): Query<HashMap<String, String>>, headers: HeaderMap, content: String) -> impl IntoResponse {
|
async fn conf(State(st): State<AppState>, Query(params): Query<HashMap<String, String>>, content: String) -> impl IntoResponse {
|
||||||
if !st.config_api_enabled {
|
if !st.config_api_enabled {
|
||||||
return Response::builder().status(StatusCode::FORBIDDEN).body(Body::from("Config API is disabled !\n")).unwrap();
|
return Response::builder().status(StatusCode::FORBIDDEN).body(Body::from("Config API is disabled !\n")).unwrap();
|
||||||
}
|
}
|
||||||
// if let Some(s) = headers.get("x-api-key").and_then(|v| v.to_str().ok()).or(params.get("key").map(|s| s.as_str())) {
|
|
||||||
|
|
||||||
if key_authorization(&headers, ¶ms, &st.master_key) {
|
let strcontent = content.as_str();
|
||||||
let strcontent = content.as_str();
|
let parsed = serde_yml::from_str::<Config>(strcontent);
|
||||||
let parsed = serde_yml::from_str::<Config>(strcontent);
|
match parsed {
|
||||||
match parsed {
|
Ok(_) => {
|
||||||
Ok(_) => {
|
if let Some(_) = params.get("save") {
|
||||||
if let Some(_) = params.get("save") {
|
drop(tokio::spawn(async move { apply_config(content.as_str(), st, true).await }));
|
||||||
drop(tokio::spawn(async move { apply_config(content.as_str(), st, true).await }));
|
} else {
|
||||||
} else {
|
drop(tokio::spawn(async move { apply_config(content.as_str(), st, false).await }));
|
||||||
drop(tokio::spawn(async move { apply_config(content.as_str(), st, false).await }));
|
|
||||||
}
|
|
||||||
// apply_config(content.as_str(), st).await;
|
|
||||||
return Response::builder().status(StatusCode::OK).body(Body::from("Accepted! Applying in background\n")).unwrap();
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
error!("Failed to parse upstreams file: {}", err);
|
|
||||||
return Response::builder().status(StatusCode::BAD_GATEWAY).body(Body::from(format!("Failed: {}\n", err))).unwrap();
|
|
||||||
}
|
}
|
||||||
|
Response::builder().status(StatusCode::OK).body(Body::from("Accepted! Applying in background\n")).unwrap()
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
error!("Failed to parse upstreams file: {}", err);
|
||||||
|
Response::builder().status(StatusCode::BAD_GATEWAY).body(Body::from(format!("Failed: {}\n", err))).unwrap()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Response::builder().status(StatusCode::FORBIDDEN).body(Body::from("Access Denied !\n")).unwrap()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn apply_config(content: &str, mut st: AppState, save: bool) {
|
async fn apply_config(content: &str, mut st: AppState, save: bool) {
|
||||||
@@ -137,34 +131,42 @@ async fn apply_config(content: &str, mut st: AppState, save: bool) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn jwt_gen(State(state): State<AppState>, Json(payload): Json<Claims>) -> (StatusCode, Json<OutToken>) {
|
async fn jwt_gen(State(state): State<AppState>, Json(payload): Json<Claims>) -> (StatusCode, Json<OutToken>) {
|
||||||
if payload.master_key == state.master_key {
|
if let Some(master_key) = &state.master_key {
|
||||||
let now = SystemTime::now() + Duration::from_secs(payload.exp * 60);
|
if &payload.master_key == master_key {
|
||||||
let expire = now.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
|
let now = SystemTime::now() + Duration::from_secs(payload.exp * 60);
|
||||||
|
let expire = now.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
|
||||||
|
|
||||||
let claim = Claims {
|
let claim = Claims {
|
||||||
master_key: String::new(),
|
master_key: String::new(),
|
||||||
owner: payload.owner,
|
owner: payload.owner,
|
||||||
exp: expire,
|
exp: expire,
|
||||||
random: payload.random,
|
random: payload.random,
|
||||||
};
|
};
|
||||||
match encode(&Header::default(), &claim, &EncodingKey::from_secret(payload.master_key.as_ref())) {
|
match encode(&Header::default(), &claim, &EncodingKey::from_secret(payload.master_key.as_ref())) {
|
||||||
Ok(t) => {
|
Ok(t) => {
|
||||||
let tok = OutToken { token: t };
|
let tok = OutToken { token: t };
|
||||||
debug!("Generating token: {:?}", tok.token);
|
debug!("Generating token: {:?}", tok.token);
|
||||||
(StatusCode::CREATED, Json(tok))
|
(StatusCode::CREATED, Json(tok))
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
let tok = OutToken { token: "ERROR".to_string() };
|
let tok = OutToken { token: "ERROR".to_string() };
|
||||||
error!("Failed to generate token: {:?}", e);
|
error!("Failed to generate token: {:?}", e);
|
||||||
(StatusCode::INTERNAL_SERVER_ERROR, Json(tok))
|
(StatusCode::INTERNAL_SERVER_ERROR, Json(tok))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
let tok = OutToken {
|
||||||
|
token: "Unauthorised".to_string(),
|
||||||
|
};
|
||||||
|
warn!("Unauthorised JWT generate request: {:?}", tok);
|
||||||
|
(StatusCode::FORBIDDEN, Json(tok))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let tok = OutToken {
|
let tok = OutToken {
|
||||||
token: "Unauthorised".to_string(),
|
token: "ERROR Getting JWT_KEY environment variable".to_string(),
|
||||||
};
|
};
|
||||||
warn!("Unauthorised JWT generate request: {:?}", tok);
|
error!("ERROR Getting JWT_KEY environment variable");
|
||||||
(StatusCode::FORBIDDEN, Json(tok))
|
(StatusCode::INTERNAL_SERVER_ERROR, Json(tok))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -221,11 +223,7 @@ async fn status(State(st): State<AppState>, Query(params): Query<HashMap<String,
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::needless_return)]
|
#[allow(clippy::needless_return)]
|
||||||
async fn acme_create(State(state): State<AppState>, Query(params): Query<HashMap<String, String>>, headers: HeaderMap) -> impl IntoResponse {
|
async fn acme_create(State(state): State<AppState>) -> impl IntoResponse {
|
||||||
if !key_authorization(&headers, ¶ms, &state.master_key) {
|
|
||||||
return Response::builder().status(StatusCode::FORBIDDEN).body(Body::from("Access Denied !\n")).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
match account::load_or_create(state.cert_creds.as_str()).await {
|
match account::load_or_create(state.cert_creds.as_str()).await {
|
||||||
Ok(txt) => {
|
Ok(txt) => {
|
||||||
return Response::builder()
|
return Response::builder()
|
||||||
@@ -243,16 +241,7 @@ async fn acme_create(State(state): State<AppState>, Query(params): Query<HashMap
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
#[allow(clippy::needless_return)]
|
#[allow(clippy::needless_return)]
|
||||||
async fn acme_order(
|
async fn acme_order(State(state): State<AppState>, axum::extract::Path(domain): axum::extract::Path<String>) -> impl IntoResponse {
|
||||||
State(state): State<AppState>,
|
|
||||||
axum::extract::Path(domain): axum::extract::Path<String>,
|
|
||||||
Query(params): Query<HashMap<String, String>>,
|
|
||||||
headers: HeaderMap,
|
|
||||||
) -> impl IntoResponse {
|
|
||||||
if !key_authorization(&headers, ¶ms, &state.master_key) {
|
|
||||||
return Response::builder().status(StatusCode::FORBIDDEN).body(Body::from("Access Denied !\n")).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
let domain_clean = domain.trim_matches('/');
|
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).await {
|
||||||
Ok(txt) => {
|
Ok(txt) => {
|
||||||
@@ -292,13 +281,13 @@ pub async fn http01_challenge(axum::extract::Path(token): axum::extract::Path<St
|
|||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn key_authorization(headers: &HeaderMap, params: &HashMap<String, String>, masterkey: &str) -> bool {
|
// fn key_authorization(headers: &HeaderMap, params: &HashMap<String, String>, masterkey: &str) -> bool {
|
||||||
if let Some(s) = headers.get("x-api-key").and_then(|v| v.to_str().ok()).or(params.get("key").map(|s| s.as_str())) {
|
// if let Some(s) = headers.get("x-api-key").and_then(|v| v.to_str().ok()).or(params.get("key").map(|s| s.as_str())) {
|
||||||
if s.as_bytes().ct_eq(masterkey.as_bytes()).into() {
|
// if s.as_bytes().ct_eq(masterkey.as_bytes()).into() {
|
||||||
return true;
|
// return true;
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
false
|
// false
|
||||||
}
|
// }
|
||||||
|
|
||||||
// -- ⚝ by Dave -- in NeoVim ⚝ --
|
// -- ⚝ by Dave -- in NeoVim ⚝ --
|
||||||
|
|||||||
Reference in New Issue
Block a user