adding jwt middlewares, and improving overall middlewares structure and server

This commit is contained in:
2026-03-11 21:01:01 +01:00
parent 587498c7bc
commit 2093456d91
12 changed files with 1082 additions and 217 deletions
+42
View File
@@ -0,0 +1,42 @@
use crate::{
middleware::{Middleware, MiddlewareFuture, MiddlewareResult},
Responder,
};
use http::Request;
use hyper::body::Incoming;
use log::warn;
pub struct ApiKeyMiddleware {
api_key: String,
}
impl ApiKeyMiddleware {
pub fn new(api_key: &str) -> Self {
Self {
api_key: api_key.to_string(),
}
}
}
impl Middleware for ApiKeyMiddleware {
fn run<'a>(&'a self, req: Request<Incoming>) -> MiddlewareFuture<'a> {
let expected_key = self.api_key.clone();
Box::pin(async move {
match req.headers().get("X-API-Key") {
Some(header) => {
if header == expected_key.as_str() {
MiddlewareResult::Continue(req)
} else {
warn!("X-API-Key wrong");
MiddlewareResult::Respond(Responder::unauthorized().unwrap())
}
}
None => {
warn!("X-API-Key missing");
MiddlewareResult::Respond(Responder::unauthorized().unwrap())
}
}
})
}
}
+17
View File
@@ -0,0 +1,17 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize)]
pub struct Claims {
pub sub: String,
pub exp: usize,
}
impl Claims {
pub fn is_expired(&self, current_timestamp: i64) -> bool {
current_timestamp > self.exp as i64
}
pub fn username(&self) -> &str {
&self.sub
}
}
+56
View File
@@ -0,0 +1,56 @@
use crate::{
Responder,
middleware::{Middleware, MiddlewareFuture, MiddlewareResult},
};
use http::Request;
use hyper::body::Incoming;
use log::warn;
use std::net::IpAddr;
pub struct IpFilterMiddleware {
allowed_ips: Vec<String>,
allow_private: bool,
}
impl IpFilterMiddleware {
pub fn new(allowed_ips: Vec<String>, allow_private: bool) -> Self {
Self {
allowed_ips,
allow_private,
}
}
fn is_authorized(&self, ip: &IpAddr) -> bool {
if self.allow_private {
let is_private = match ip {
IpAddr::V4(ip4) => ip4.is_private(),
IpAddr::V6(_) => false,
};
if is_private {
return true;
}
}
if self.allowed_ips.is_empty() {
return true;
}
self.allowed_ips.iter().any(|auth| &ip.to_string() == auth)
}
}
impl Middleware for IpFilterMiddleware {
fn run<'a>(&'a self, req: Request<Incoming>) -> MiddlewareFuture<'a> {
Box::pin(async move {
let client_ip = req.extensions().get::<IpAddr>();
match client_ip {
Some(ip) if self.is_authorized(ip) => MiddlewareResult::Continue(req),
_ => {
warn!("Unauthorized IP");
MiddlewareResult::Respond(Responder::unauthorized().unwrap())
}
}
})
}
}
+71
View File
@@ -0,0 +1,71 @@
use crate::{
middleware::{auth_types::Claims, Middleware, MiddlewareFuture, MiddlewareResult},
Responder,
};
use http::Request;
use hyper::body::Incoming;
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use log::error;
pub struct JwtMiddleware {
decoding_key: DecodingKey,
public_routes: Vec<String>,
}
impl JwtMiddleware {
pub fn new(
public_key: &str,
public_routes: Vec<String>,
) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
let decoding_key = DecodingKey::from_rsa_pem(public_key.as_bytes())?;
Ok(Self {
decoding_key,
public_routes,
})
}
fn validate_request(
&self,
req: &Request<Incoming>,
) -> Result<Claims, Box<dyn std::error::Error + Send + Sync>> {
let auth_header = req
.headers()
.get("Authorization")
.and_then(|v| v.to_str().ok())
.filter(|h| h.starts_with("Bearer "))
.map(|h| &h[7..])
.ok_or("No token found")?;
let mut validation = Validation::new(Algorithm::RS256);
validation.set_required_spec_claims(&["exp", "sub"]);
let token_data = decode::<Claims>(auth_header, &self.decoding_key, &validation)?;
Ok(token_data.claims)
}
}
impl Middleware for JwtMiddleware {
fn run(&self, mut req: Request<Incoming>) -> MiddlewareFuture<'_> {
let path = req.uri().path().to_string();
let public_routes = self.public_routes.clone();
Box::pin(async move {
if public_routes.contains(&path) {
return MiddlewareResult::Continue(req);
}
match self.validate_request(&req) {
Ok(claims) => {
req.extensions_mut().insert(claims);
MiddlewareResult::Continue(req)
}
Err(e) => {
error!(target: "auth", "JWT validation failed: {}", e);
let res = Responder::unauthorized().expect("Responder failed");
MiddlewareResult::Respond(res)
}
}
})
}
}
+26
View File
@@ -0,0 +1,26 @@
mod api_key;
mod auth_types;
mod ip_filter;
mod jwt;
use http::{Request, Response};
use http_body_util::Full;
use hyper::body::{Bytes, Incoming};
use std::future::Future;
use std::pin::Pin;
pub enum MiddlewareResult {
Continue(Request<Incoming>),
Respond(Response<Full<Bytes>>),
}
pub type MiddlewareFuture<'a> = Pin<Box<dyn Future<Output = MiddlewareResult> + Send + 'a>>;
pub trait Middleware: Send + Sync {
fn run<'a>(&'a self, req: Request<Incoming>) -> MiddlewareFuture<'a>;
}
pub use api_key::ApiKeyMiddleware;
pub use auth_types::Claims;
pub use ip_filter::IpFilterMiddleware;
pub use jwt::JwtMiddleware;