mirror of
https://github.com/sadoyan/aralez.git
synced 2026-04-29 22:38:36 +08:00
Created proxy wide authentication
This commit is contained in:
52
src/utils/auth.rs
Normal file
52
src/utils/auth.rs
Normal file
@@ -0,0 +1,52 @@
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use base64::Engine;
|
||||
use pingora_proxy::Session;
|
||||
|
||||
trait AuthValidator {
|
||||
fn validate(&self, session: &Session) -> bool;
|
||||
}
|
||||
struct BasicAuth<'a>(&'a str);
|
||||
struct ApiKeyAuth<'a>(&'a str);
|
||||
|
||||
impl AuthValidator for BasicAuth<'_> {
|
||||
fn validate(&self, session: &Session) -> bool {
|
||||
if let Some(header) = session.get_header("authorization") {
|
||||
if let Some((_, val)) = header.to_str().ok().unwrap().split_once(' ') {
|
||||
let decoded = STANDARD.decode(val).ok().unwrap();
|
||||
let decoded_str = String::from_utf8(decoded).ok().unwrap();
|
||||
return decoded_str == self.0;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthValidator for ApiKeyAuth<'_> {
|
||||
fn validate(&self, session: &Session) -> bool {
|
||||
if let Some(header) = session.get_header("x-api-key") {
|
||||
return header.to_str().ok().unwrap() == self.0;
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn validate(auth: &dyn AuthValidator, session: &Session) -> bool {
|
||||
auth.validate(session)
|
||||
}
|
||||
|
||||
pub fn authenticate(c: &[String], session: &Session) -> bool {
|
||||
match c[0].as_str() {
|
||||
"basic" => {
|
||||
let auth = BasicAuth(c[1].as_str().into());
|
||||
validate(&auth, session)
|
||||
}
|
||||
"apikey" => {
|
||||
let auth = ApiKeyAuth(c[1].as_str().into());
|
||||
validate(&auth, session)
|
||||
}
|
||||
_ => {
|
||||
println!("Unsupported authentication mechanism : {}", c[0]);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::utils::parceyaml::{load_configuration, ServiceMapping};
|
||||
use crate::utils::tools::{clone_dashmap_into, compare_dashmaps, Headers, UpstreamsDashMap};
|
||||
use crate::utils::parceyaml::{load_configuration, Configuration, ServiceMapping};
|
||||
use crate::utils::tools::{clone_dashmap_into, compare_dashmaps, UpstreamsDashMap};
|
||||
use dashmap::DashMap;
|
||||
use futures::channel::mpsc::Sender;
|
||||
use futures::SinkExt;
|
||||
@@ -33,7 +33,7 @@ struct TaggedAddress {
|
||||
port: u16,
|
||||
}
|
||||
|
||||
pub async fn start(fp: String, mut toreturn: Sender<(UpstreamsDashMap, Headers)>) {
|
||||
pub async fn start(fp: String, mut toreturn: Sender<Configuration>) {
|
||||
let config = load_configuration(fp.as_str(), "filepath");
|
||||
let headers = DashMap::new();
|
||||
|
||||
@@ -45,7 +45,7 @@ pub async fn start(fp: String, mut toreturn: Sender<(UpstreamsDashMap, Headers)>
|
||||
}
|
||||
|
||||
info!("Consul Discovery is enabled : {}", config.typecfg);
|
||||
let consul = config.consul;
|
||||
let consul = config.consul.clone();
|
||||
let prev_upstreams = UpstreamsDashMap::new();
|
||||
match consul {
|
||||
Some(consul) => {
|
||||
@@ -54,20 +54,32 @@ pub async fn start(fp: String, mut toreturn: Sender<(UpstreamsDashMap, Headers)>
|
||||
let end = servers.len();
|
||||
|
||||
loop {
|
||||
// println!(" ==> {:?}", consul.services);
|
||||
let num = rand::rng().random_range(1..end);
|
||||
headers.clear();
|
||||
for (k, v) in config.headers.clone() {
|
||||
headers.insert(k.to_string(), v);
|
||||
}
|
||||
let consul_data = servers.get(num).unwrap().to_string();
|
||||
// let upstreams = http_request(consul_data, consul.whitelist.clone());
|
||||
let upstreams = consul_request(consul_data, consul.services.clone(), consul.token.clone());
|
||||
|
||||
match upstreams.await {
|
||||
Some(upstreams) => {
|
||||
if !compare_dashmaps(&upstreams, &prev_upstreams) {
|
||||
let mut tosend: Configuration = Configuration {
|
||||
upstreams: Default::default(),
|
||||
headers: Default::default(),
|
||||
consul: None,
|
||||
typecfg: "".to_string(),
|
||||
globals: Default::default(),
|
||||
};
|
||||
|
||||
clone_dashmap_into(&upstreams, &prev_upstreams);
|
||||
toreturn.send((upstreams, headers.clone())).await.unwrap();
|
||||
clone_dashmap_into(&upstreams, &tosend.upstreams);
|
||||
tosend.headers = headers.clone();
|
||||
tosend.globals = config.globals.clone();
|
||||
tosend.typecfg = config.typecfg.clone();
|
||||
tosend.consul = config.consul.clone();
|
||||
toreturn.send(tosend).await.unwrap();
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::utils::consul;
|
||||
use crate::utils::filewatch;
|
||||
use crate::utils::tools::*;
|
||||
use crate::utils::parceyaml::Configuration;
|
||||
use crate::web::webserver;
|
||||
use async_trait::async_trait;
|
||||
use futures::channel::mpsc::Sender;
|
||||
@@ -18,26 +18,26 @@ pub struct ConsulProvider {
|
||||
|
||||
#[async_trait]
|
||||
pub trait Discovery {
|
||||
async fn start(&self, tx: Sender<(UpstreamsDashMap, Headers)>);
|
||||
async fn start(&self, tx: Sender<Configuration>);
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Discovery for APIUpstreamProvider {
|
||||
async fn start(&self, toreturn: Sender<(UpstreamsDashMap, Headers)>) {
|
||||
async fn start(&self, toreturn: Sender<Configuration>) {
|
||||
webserver::run_server(self.address.clone(), toreturn).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Discovery for FromFileProvider {
|
||||
async fn start(&self, tx: Sender<(UpstreamsDashMap, Headers)>) {
|
||||
async fn start(&self, tx: Sender<Configuration>) {
|
||||
tokio::spawn(filewatch::start(self.path.clone(), tx.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Discovery for ConsulProvider {
|
||||
async fn start(&self, tx: Sender<(UpstreamsDashMap, Headers)>) {
|
||||
async fn start(&self, tx: Sender<Configuration>) {
|
||||
tokio::spawn(consul::start(self.path.clone(), tx.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use crate::utils::parceyaml::load_configuration;
|
||||
use crate::utils::tools::*;
|
||||
use crate::utils::parceyaml::{load_configuration, Configuration};
|
||||
use futures::channel::mpsc::Sender;
|
||||
use futures::SinkExt;
|
||||
use log::{error, info};
|
||||
@@ -10,17 +9,16 @@ use std::path::Path;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::task;
|
||||
|
||||
pub async fn start(fp: String, mut toreturn: Sender<(UpstreamsDashMap, Headers)>) {
|
||||
pub async fn start(fp: String, mut toreturn: Sender<Configuration>) {
|
||||
sleep(Duration::from_millis(50)).await; // For having nice logs :-)
|
||||
let file_path = fp.as_str();
|
||||
let parent_dir = Path::new(file_path).parent().unwrap();
|
||||
let (local_tx, mut local_rx) = tokio::sync::mpsc::channel::<notify::Result<Event>>(1);
|
||||
info!("Watching for changes in {:?}", parent_dir);
|
||||
let snd = load_configuration(file_path, "filepath");
|
||||
|
||||
match snd {
|
||||
Some(snd) => {
|
||||
toreturn.send((snd.upstreams, snd.headers)).await.unwrap();
|
||||
toreturn.send(snd).await.unwrap();
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
@@ -53,7 +51,7 @@ pub async fn start(fp: String, mut toreturn: Sender<(UpstreamsDashMap, Headers)>
|
||||
let snd = load_configuration(file_path, "filepath");
|
||||
match snd {
|
||||
Some(snd) => {
|
||||
toreturn.send((snd.upstreams, snd.headers)).await.unwrap();
|
||||
toreturn.send(snd).await.unwrap();
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
|
||||
@@ -38,12 +38,12 @@ struct PathConfig {
|
||||
servers: Vec<String>,
|
||||
headers: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
pub struct Configuration {
|
||||
pub upstreams: UpstreamsDashMap,
|
||||
pub headers: Headers,
|
||||
pub consul: Option<Consul>,
|
||||
pub typecfg: String,
|
||||
pub globals: Option<DashMap<String, Vec<String>>>,
|
||||
}
|
||||
|
||||
// pub fn load_configuration(d: &str, kind: &str) -> Option<(UpstreamsDashMap, Headers, String)> {
|
||||
@@ -53,6 +53,7 @@ pub fn load_configuration(d: &str, kind: &str) -> Option<Configuration> {
|
||||
headers: Default::default(),
|
||||
consul: None,
|
||||
typecfg: "".to_string(),
|
||||
globals: Default::default(),
|
||||
};
|
||||
toreturn.upstreams = UpstreamsDashMap::new();
|
||||
toreturn.headers = Headers::new();
|
||||
@@ -96,6 +97,14 @@ pub fn load_configuration(d: &str, kind: &str) -> Option<Configuration> {
|
||||
}
|
||||
global_headers.insert("/".to_string(), hl);
|
||||
toreturn.headers.insert("GLOBAL_HEADERS".to_string(), global_headers);
|
||||
|
||||
let cfg = DashMap::new();
|
||||
if let Some(k) = globals.get("authorization") {
|
||||
cfg.insert("authorization".to_string(), k.to_owned());
|
||||
toreturn.globals = Some(cfg);
|
||||
} else {
|
||||
toreturn.globals = None;
|
||||
}
|
||||
}
|
||||
match parsed.provider.as_str() {
|
||||
"file" => {
|
||||
@@ -107,17 +116,6 @@ pub fn load_configuration(d: &str, kind: &str) -> Option<Configuration> {
|
||||
for (path, path_config) in host_config.paths {
|
||||
let mut server_list = Vec::new();
|
||||
let mut hl = Vec::new();
|
||||
// Set global headers
|
||||
// if let Some(globals) = &parsed.globals {
|
||||
// for headers in globals.get("headers").iter().by_ref() {
|
||||
// for header in headers.iter() {
|
||||
// if let Some((key, val)) = header.split_once(':') {
|
||||
// hl.push((key.to_string(), val.to_string()));
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// Set per host/path headers
|
||||
if let Some(headers) = &path_config.headers {
|
||||
for header in headers.iter().by_ref() {
|
||||
if let Some((key, val)) = header.split_once(':') {
|
||||
|
||||
Reference in New Issue
Block a user