fix: format
CI / Rust CI (push) Successful in 4m14s

This commit is contained in:
2026-04-09 16:58:59 +02:00
parent 495f2b335d
commit 40364b5638
5 changed files with 52 additions and 78 deletions
+6 -12
View File
@@ -1,8 +1,8 @@
use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation};
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::env;
use once_cell::sync::Lazy;
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Claims {
@@ -19,9 +19,7 @@ pub struct RealmAccess {
pub roles: Vec<String>,
}
static ISSUER: Lazy<String> = Lazy::new(|| {
env::var("ISSUER").expect("ISSUER not set")
});
static ISSUER: Lazy<String> = Lazy::new(|| env::var("ISSUER").expect("ISSUER not set"));
pub fn validate_token(token: &str, jwks: &Value) -> Result<Claims, String> {
// 1. Decode header
@@ -30,9 +28,7 @@ pub fn validate_token(token: &str, jwks: &Value) -> Result<Claims, String> {
let kid = header.kid.ok_or("Missing kid")?;
// 2. Find matching key
let keys = jwks["keys"]
.as_array()
.ok_or("Invalid JWKS")?;
let keys = jwks["keys"].as_array().ok_or("Invalid JWKS")?;
let key = keys
.iter()
@@ -44,8 +40,7 @@ pub fn validate_token(token: &str, jwks: &Value) -> Result<Claims, String> {
let e = key["e"].as_str().ok_or("Missing e")?;
let decoding_key =
DecodingKey::from_rsa_components(n, e)
.map_err(|_| "Invalid decoding key")?;
DecodingKey::from_rsa_components(n, e).map_err(|_| "Invalid decoding key")?;
// 4. Setup validation rules
let mut validation = Validation::new(Algorithm::RS256);
@@ -57,8 +52,7 @@ pub fn validate_token(token: &str, jwks: &Value) -> Result<Claims, String> {
validation.validate_aud = false; // depends on your Keycloak config
// 5. Decode & verify
let token_data =
decode::<Claims>(token, &decoding_key, &validation)
let token_data = decode::<Claims>(token, &decoding_key, &validation)
.map_err(|_| "Token validation failed")?;
Ok(token_data.claims)
+11 -13
View File
@@ -1,9 +1,9 @@
use serde_json::Value;
use std::sync::Arc;
use tokio::sync::RwLock;
use std::time::{Duration, Instant};
use std::env;
use once_cell::sync::Lazy;
use serde_json::Value;
use std::env;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
#[derive(Clone)]
struct JwksCache {
@@ -11,12 +11,9 @@ struct JwksCache {
last_fetched: Instant,
}
static JWK_CACHE: Lazy<Arc<RwLock<Option<JwksCache>>>> =
Lazy::new(|| Arc::new(RwLock::new(None)));
static JWK_CACHE: Lazy<Arc<RwLock<Option<JwksCache>>>> = Lazy::new(|| Arc::new(RwLock::new(None)));
static JWKS_URL: Lazy<String> = Lazy::new(|| {
env::var("JWKS_URL").expect("JWKS_URL not set")
});
static JWKS_URL: Lazy<String> = Lazy::new(|| env::var("JWKS_URL").expect("JWKS_URL not set"));
async fn fetch_jwks() -> Result<Value, reqwest::Error> {
let jwks = reqwest::get(JWKS_URL.as_str())
@@ -47,12 +44,13 @@ pub async fn get_jwks() -> Result<Value, reqwest::Error> {
// Read lock first (fast path)
let read = JWK_CACHE.read().await;
if let Some(cache) = &*read {
if cache.last_fetched.elapsed() < ttl {
if let Some(cache) = read
.as_ref()
.filter(|cache| cache.last_fetched.elapsed() < ttl)
{
return Ok(cache.jwks.clone());
}
}
}
// Expired or empty → refresh
refresh_jwks().await
+7 -14
View File
@@ -1,25 +1,18 @@
use axum::{
extract::Request,
http::{StatusCode},
middleware::Next,
response::Response,
use axum::{extract::Request, http::StatusCode, middleware::Next, response::Response};
use crate::auth::{
jwt::validate_token,
keycloak::{get_jwks, refresh_jwks},
};
use crate::auth::{jwt::validate_token, keycloak::{get_jwks, refresh_jwks}};
pub async fn auth_middleware(
mut request: Request,
next: Next,
) -> Result<Response, StatusCode> {
pub async fn auth_middleware(mut request: Request, next: Next) -> Result<Response, StatusCode> {
dbg!("Middleware hit");
let headers = request.headers();
dbg!("Headers extracted");
let auth_header = headers
.get("authorization")
.and_then(|v| v.to_str().ok());
let auth_header = headers.get("authorization").and_then(|v| v.to_str().ok());
dbg!("Auth header: {:?}", auth_header);
+7 -18
View File
@@ -1,25 +1,17 @@
mod auth;
use crate::auth::middleware::auth_middleware;
use crate::auth::jwt::Claims;
use crate::auth::middleware::auth_middleware;
use dotenvy::dotenv;
use axum::extract::Extension;
use axum::{
routing::get,
Router,
middleware,
};
use axum::{Router, middleware, routing::get};
use dotenvy::dotenv;
use std::net::SocketAddr;
pub async fn protected_route(
Extension(claims): Extension<Claims>,
) -> String {
pub async fn protected_route(Extension(claims): Extension<Claims>) -> String {
format!(
"Hello {}, your user id is {}",
claims
.preferred_username
.unwrap_or("unknown".to_string()),
claims.preferred_username.unwrap_or("unknown".to_string()),
claims.sub
)
}
@@ -30,16 +22,13 @@ pub async fn public_route() -> &'static str {
}
pub fn app() -> Router {
let public_routes = Router::new()
.route("/", get(public_route));
let public_routes = Router::new().route("/", get(public_route));
let protected_routes = Router::new()
.route("/protected", get(protected_route))
.layer(middleware::from_fn(auth_middleware));
Router::new()
.merge(public_routes)
.merge(protected_routes)
Router::new().merge(public_routes).merge(protected_routes)
}
#[tokio::main]