reafctor: all code without stream
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
pub struct KeycloakClaims {
|
||||
pub sub: String,
|
||||
pub preferred_username: Option<String>,
|
||||
pub exp: usize,
|
||||
pub iss: String,
|
||||
pub _aud: Option<Vec<String>>,
|
||||
pub realm_access: Option<RealmAccess>,
|
||||
pub resource_access: HashMap<String, ResourceAccess>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct RealmAccess {
|
||||
pub roles: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct ResourceAccess {
|
||||
pub roles: Vec<String>,
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum AuthError {
|
||||
#[error("invalid authorization header")]
|
||||
InvalidHeader,
|
||||
|
||||
#[error("missing 'kid' in token header")]
|
||||
MissingKid,
|
||||
|
||||
#[error("invalid JWKS structure")]
|
||||
InvalidJwks,
|
||||
|
||||
#[error("no matching key found for kid")]
|
||||
JwkNotFound,
|
||||
|
||||
#[error("missing RSA modulus")]
|
||||
MissingModulus,
|
||||
|
||||
#[error("missing RSA exponent")]
|
||||
MissingExponent,
|
||||
|
||||
#[error("invalid decoding key")]
|
||||
InvalidDecodingKey,
|
||||
|
||||
#[error("token validation failed")]
|
||||
TokenValidationFailed,
|
||||
|
||||
#[error("invalid or expired token")]
|
||||
InvalidToken,
|
||||
|
||||
#[error("failed to fetch JWKS")]
|
||||
JwksFetchFailed,
|
||||
|
||||
#[error("failed to refresh JWKS")]
|
||||
JwksRefreshFailed,
|
||||
|
||||
#[error(transparent)]
|
||||
Reqwest(#[from] reqwest::Error),
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
use super::errors::AuthError;
|
||||
|
||||
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 {
|
||||
jwks: Value,
|
||||
last_fetched: Instant,
|
||||
}
|
||||
|
||||
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"));
|
||||
|
||||
async fn fetch_jwks() -> Result<Value, AuthError> {
|
||||
let jwks = reqwest::get(JWKS_URL.as_str())
|
||||
.await?
|
||||
.json::<Value>()
|
||||
.await?;
|
||||
|
||||
Ok(jwks)
|
||||
}
|
||||
|
||||
pub async fn refresh_jwks() -> Result<Value, AuthError> {
|
||||
let jwks = fetch_jwks().await?;
|
||||
|
||||
let mut write = JWK_CACHE.write().await;
|
||||
|
||||
*write = Some(JwksCache {
|
||||
jwks: jwks.clone(),
|
||||
last_fetched: Instant::now(),
|
||||
});
|
||||
|
||||
Ok(jwks)
|
||||
}
|
||||
|
||||
pub async fn get_jwks() -> Result<Value, AuthError> {
|
||||
let ttl = Duration::from_secs(3600); // 1 hour
|
||||
|
||||
{
|
||||
// Read lock first (fast path)
|
||||
let read = JWK_CACHE.read().await;
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
pub mod claims;
|
||||
pub mod errors;
|
||||
pub mod jwks;
|
||||
pub mod validator;
|
||||
@@ -0,0 +1,64 @@
|
||||
use super::claims::KeycloakClaims;
|
||||
use super::errors::AuthError;
|
||||
|
||||
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header};
|
||||
use once_cell::sync::Lazy;
|
||||
use serde_json::Value;
|
||||
use std::env;
|
||||
|
||||
static ISSUER: Lazy<String> = Lazy::new(|| env::var("ISSUER").expect("ISSUER not set"));
|
||||
|
||||
fn validate_token(token: &str, jwks: &Value) -> Result<KeycloakClaims, AuthError> {
|
||||
// 1. Decode header
|
||||
let header = decode_header(token).map_err(|_| AuthError::InvalidHeader)?;
|
||||
|
||||
let kid = header.kid.ok_or(AuthError::MissingKid)?;
|
||||
|
||||
// 2. Find matching key
|
||||
let keys = jwks["keys"].as_array().ok_or(AuthError::InvalidJwks)?;
|
||||
|
||||
let key = keys
|
||||
.iter()
|
||||
.find(|k| k["kid"] == kid)
|
||||
.ok_or(AuthError::InvalidDecodingKey)?;
|
||||
|
||||
// 3. Extract RSA components
|
||||
let n = key["n"].as_str().ok_or(AuthError::MissingModulus)?;
|
||||
let e = key["e"].as_str().ok_or(AuthError::MissingExponent)?;
|
||||
|
||||
let decoding_key =
|
||||
DecodingKey::from_rsa_components(n, e).map_err(|_| AuthError::JwkNotFound)?;
|
||||
|
||||
// 4. Setup validation rules
|
||||
let mut validation = Validation::new(Algorithm::RS256);
|
||||
|
||||
validation.set_issuer(&[ISSUER.as_str()]);
|
||||
|
||||
validation.validate_exp = true;
|
||||
validation.validate_aud = false;
|
||||
|
||||
// 5. Decode & verify
|
||||
let token_data = decode::<KeycloakClaims>(token, &decoding_key, &validation)
|
||||
.map_err(|_| AuthError::TokenValidationFailed)?;
|
||||
|
||||
Ok(token_data.claims)
|
||||
}
|
||||
|
||||
pub async fn authenticate_jwt(token: &str) -> Result<KeycloakClaims, AuthError> {
|
||||
let jwks = super::jwks::get_jwks()
|
||||
.await
|
||||
.map_err(|_| AuthError::JwksFetchFailed)?;
|
||||
|
||||
match validate_token(token, &jwks) {
|
||||
Ok(claims) => Ok(claims),
|
||||
|
||||
Err(_) => {
|
||||
// one retry with refresh
|
||||
let fresh = super::jwks::refresh_jwks()
|
||||
.await
|
||||
.map_err(|_| AuthError::JwksRefreshFailed)?;
|
||||
|
||||
validate_token(token, &fresh).map_err(|_| AuthError::InvalidToken)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user