Created proxy wide authentication

This commit is contained in:
Ara Sadoyan
2025-04-14 19:01:09 +02:00
parent e5782414dd
commit 0a6f501e2c
12 changed files with 141 additions and 51 deletions

52
src/utils/auth.rs Normal file
View 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
}
}
}