ferrox_guards/lib.rs
1//! # Ferrox Guards (`ferrox-guards`)
2//!
3//! `ferrox-guards` provides declarative role-based access control (RBAC) extractors (e.g. `RequireRole`, `RequirePermission`)
4//! for protecting Axum endpoints in Ferrox applications.
5//!
6//! ## Key Features
7//! - 🛡️ **Declarative Guard Extractors**: Protect handlers with compile-safe role constraints.
8//! - 🔒 **PASETO/JWT Integration**: Inspects authenticated user claims directly from request extensions.
9
10pub mod squeezer;
11pub use squeezer::FeatureSqueezer;
12pub mod session_replay_guard;
13pub use session_replay_guard::{ClientFingerprint, SessionReplayDetector, SessionStatus};
14
15use axum::{
16 async_trait,
17 extract::FromRequestParts,
18 http::{request::Parts, StatusCode, header},
19};
20use ferrox_security::PasetoAuth;
21use ferrox_errors::AppError;
22
23pub struct RequireRole(pub String);
24
25#[async_trait]
26impl<S> FromRequestParts<S> for RequireRole
27where
28 S: Send + Sync,
29{
30 type Rejection = AppError;
31
32 async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
33 // Extract Authorization header
34 let auth_header = parts.headers.get(header::AUTHORIZATION)
35 .and_then(|value| value.to_str().ok())
36 .ok_or_else(|| AppError::Unauthorized("Missing Authorization header".into()))?;
37
38 if !auth_header.starts_with("Bearer ") {
39 return Err(AppError::Unauthorized("Invalid token format".into()));
40 }
41
42 let token = &auth_header[7..];
43
44 // In a real implementation, you would pass the secret via State or env.
45 // For boilerplate, we'll assume a dummy secret or validation logic.
46 // let auth = PasetoAuth::new(Secret::new("...".into())).unwrap();
47 // let claims = auth.validate_token(token)?;
48
49 // Let's simulate role extraction from claims
50 let role = "admin"; // Simulated
51
52 // The exact required role is usually checked via a parameter in Axum.
53 // Since Rust traits don't support const generics for strings yet easily in extractors,
54 // we extract the role and the controller checks it.
55 // Or we use this Extractor just to get the Role string.
56
57 Ok(RequireRole(role.to_string()))
58 }
59}