Skip to main content

auth_framework/authorization_enhanced/
middleware.rs

1//! Enhanced authorization middleware using role-system v1.0
2//!
3//! This module provides comprehensive authorization middleware for Axum,
4//! replacing the basic role checking with enterprise-grade RBAC.
5
6use crate::api::{ApiResponse, ApiState};
7use crate::tokens::AuthToken;
8use axum::{
9    extract::{Request, State},
10    middleware::Next,
11    response::{IntoResponse, Response},
12};
13use std::collections::HashMap;
14use tracing::{debug, info, warn};
15
16/// Enhanced RBAC middleware using role-system v1.0
17#[allow(clippy::result_large_err)] // the Err type is part of the existing public signature; boxing it would change the API of a release line
18pub async fn rbac_middleware(
19    State(state): State<ApiState>,
20    request: Request,
21    next: Next,
22) -> Result<Response, Response> {
23    // Skip auth for public endpoints
24    let path = request.uri().path();
25    if is_public_endpoint(path) {
26        return Ok(next.run(request).await);
27    }
28
29    // Get auth token from extensions (should be set by auth_middleware)
30    let auth_token = match request.extensions().get::<AuthToken>() {
31        Some(token) => token.clone(),
32        None => {
33            let error_response = ApiResponse::<()>::unauthorized();
34            return Err(error_response.into_response());
35        }
36    };
37
38    // Build request context for conditional permissions
39    let context = build_request_context(&request, &auth_token);
40
41    // Check authorization using role-system
42    let authorized = match check_authorization(&state, &auth_token, &request, &context).await {
43        Ok(granted) => granted,
44        Err(e) => {
45            warn!("Authorization check failed: {}", e);
46            let error_response = ApiResponse::<()>::forbidden();
47            return Err(error_response.into_response());
48        }
49    };
50
51    if authorized {
52        debug!(
53            "Authorization granted for user '{}' on {}",
54            auth_token.user_id, path
55        );
56        Ok(next.run(request).await)
57    } else {
58        info!(
59            "Authorization denied for user '{}' on {}",
60            auth_token.user_id, path
61        );
62        let error_response = ApiResponse::<()>::forbidden();
63        Err(error_response.into_response())
64    }
65}
66
67/// Conditional permission middleware for time/location-based access
68#[allow(clippy::result_large_err)] // the Err type is part of the existing public signature; boxing it would change the API of a release line
69pub async fn conditional_permission_middleware(
70    State(state): State<ApiState>,
71    request: Request,
72    next: Next,
73) -> Result<Response, Response> {
74    let path = request.uri().path();
75
76    // Apply conditional permissions for sensitive endpoints
77    if is_sensitive_endpoint(path) {
78        let auth_token = match request.extensions().get::<AuthToken>() {
79            Some(token) => token,
80            None => {
81                let error_response = ApiResponse::<()>::unauthorized();
82                return Err(error_response.into_response());
83            }
84        };
85
86        let context = build_conditional_context(&request);
87
88        // Check conditional permissions
89        let has_conditional_access: bool = state
90            .authorization_service
91            .check_permission(&auth_token.user_id, "access", path, Some(&context))
92            .await
93            .unwrap_or_default();
94
95        if !has_conditional_access {
96            info!(
97                "Conditional access denied for user '{}' on {}",
98                auth_token.user_id, path
99            );
100            let error_response = ApiResponse::<()>::error(
101                "CONDITIONAL_ACCESS_DENIED",
102                "Access denied due to conditional permissions (time, location, etc.)",
103            );
104            return Err(error_response.into_response());
105        }
106    }
107
108    Ok(next.run(request).await)
109}
110
111/// Role elevation middleware for administrative actions
112#[allow(clippy::result_large_err)] // the Err type is part of the existing public signature; boxing it would change the API of a release line
113pub async fn role_elevation_middleware(
114    State(state): State<ApiState>,
115    request: Request,
116    next: Next,
117) -> Result<Response, Response> {
118    let path = request.uri().path();
119
120    // Check if this endpoint requires elevated permissions
121    if requires_role_elevation(path) {
122        let auth_token = match request.extensions().get::<AuthToken>() {
123            Some(token) => token,
124            None => {
125                let error_response = ApiResponse::<()>::unauthorized();
126                return Err(error_response.into_response());
127            }
128        };
129
130        // Check if user has elevated permissions
131        let has_elevated_access: bool = state
132            .authorization_service
133            .check_permission(&auth_token.user_id, "elevated", "admin", None)
134            .await
135            .unwrap_or_default();
136
137        if !has_elevated_access {
138            info!(
139                "Elevated access required for user '{}' on {}",
140                auth_token.user_id, path
141            );
142            let error_response = ApiResponse::<()>::error(
143                "ELEVATION_REQUIRED",
144                "This action requires elevated permissions. Please request temporary role elevation.",
145            );
146            return Err(error_response.into_response());
147        }
148    }
149
150    Ok(next.run(request).await)
151}
152
153/// Check authorization using the enhanced authorization service
154async fn check_authorization(
155    state: &ApiState,
156    auth_token: &AuthToken,
157    request: &Request,
158    context: &HashMap<String, String>,
159) -> Result<bool, Box<dyn std::error::Error + Send + Sync>> {
160    let method = request.method().as_str();
161    let path = request.uri().path();
162
163    // Use the enhanced authorization service
164    state
165        .authorization_service
166        .check_api_permission(&auth_token.user_id, method, path, context)
167        .await
168        .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)
169}
170
171/// Build request context for conditional permissions
172fn build_request_context(request: &Request, auth_token: &AuthToken) -> HashMap<String, String> {
173    let mut context = HashMap::new();
174
175    // Add user context
176    context.insert("user_id".to_string(), auth_token.user_id.clone());
177    context.insert("roles".to_string(), auth_token.roles.join(","));
178
179    // Add request metadata
180    if let Some(user_agent) = request.headers().get("user-agent")
181        && let Ok(ua_str) = user_agent.to_str()
182    {
183        context.insert("user_agent".to_string(), ua_str.to_string());
184    }
185
186    // Add IP address: the connection's peer. A client-supplied X-Forwarded-For is never
187    // copied into the context (use `ContextBuilder::with_trusted_proxies` behind a proxy).
188    if let Some(connect_info) = request
189        .extensions()
190        .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
191    {
192        // No proxy list on this path: `forwarded_client_ip` canonicalises the peer
193        // (IPv4-mapped IPv6 becomes IPv4) and ignores every header.
194        let client = crate::api::middleware::forwarded_client_ip(
195            connect_info.0.ip(),
196            request.headers(),
197            &[],
198        );
199        context.insert("ip_address".to_string(), client.to_string());
200    }
201
202    // Add time-based context
203    let current_hour = chrono::Utc::now().format("%H").to_string();
204    let hour: u32 = current_hour.parse().unwrap_or(0);
205
206    if (9..=17).contains(&hour) {
207        context.insert("time".to_string(), "business_hours".to_string());
208    } else {
209        context.insert("time".to_string(), "after_hours".to_string());
210    }
211
212    // Add day of week
213    let day_of_week = chrono::Utc::now().format("%u").to_string(); // 1-7, Monday = 1
214    let weekday: u32 = day_of_week.parse().unwrap_or(1);
215
216    if (1..=5).contains(&weekday) {
217        context.insert("day_type".to_string(), "weekday".to_string());
218    } else {
219        context.insert("day_type".to_string(), "weekend".to_string());
220    }
221
222    context
223}
224
225/// Build conditional context for sensitive operations
226fn build_conditional_context(request: &Request) -> HashMap<String, String> {
227    let mut context = HashMap::new();
228
229    // Check for VPN indicators
230    if let Some(via) = request.headers().get("via")
231        && let Ok(via_str) = via.to_str()
232        && (via_str.contains("vpn") || via_str.contains("proxy"))
233    {
234        context.insert("connection_type".to_string(), "vpn".to_string());
235    }
236
237    // Check for mobile device
238    if let Some(user_agent) = request.headers().get("user-agent")
239        && let Ok(ua_str) = user_agent.to_str()
240    {
241        if ua_str.contains("Mobile") || ua_str.contains("Android") || ua_str.contains("iPhone") {
242            context.insert("device_type".to_string(), "mobile".to_string());
243        } else {
244            context.insert("device_type".to_string(), "desktop".to_string());
245        }
246    }
247
248    // Add security level based on endpoint sensitivity
249    let path = request.uri().path();
250    if path.contains("/admin/") {
251        context.insert("security_level".to_string(), "high".to_string());
252    } else if path.contains("/api/") {
253        context.insert("security_level".to_string(), "medium".to_string());
254    } else {
255        context.insert("security_level".to_string(), "low".to_string());
256    }
257
258    context
259}
260
261/// Check if endpoint is public (doesn't require authentication)
262fn is_public_endpoint(path: &str) -> bool {
263    match path {
264        "/health" | "/health/detailed" | "/metrics" | "/readiness" | "/liveness" => true,
265        "/auth/login" | "/auth/refresh" | "/auth/providers" => true,
266        "/oauth/authorize" | "/oauth/token" | "/oauth/.well-known/openid_configuration" => true,
267        _ if path.starts_with("/oauth/.well-known/") => true,
268        _ => false,
269    }
270}
271
272/// Check if endpoint contains sensitive data
273fn is_sensitive_endpoint(path: &str) -> bool {
274    match path {
275        _ if path.starts_with("/admin/") => true,
276        _ if path.contains("/secrets/") => true,
277        _ if path.contains("/config/") => true,
278        _ if path.contains("/keys/") => true,
279        "/auth/logout" => true, // Logout should have conditional access
280        _ => false,
281    }
282}
283
284/// Check if endpoint requires role elevation
285fn requires_role_elevation(path: &str) -> bool {
286    match path {
287        _ if path.starts_with("/admin/users/delete") => true,
288        _ if path.starts_with("/admin/system/") => true,
289        _ if path.contains("/sudo/") => true,
290        _ if path.contains("/elevate/") => true,
291        _ => false,
292    }
293}
294
295/// Permission requirement middleware factory
296pub fn require_permission(
297    action: &str,
298    resource: &str,
299) -> impl Fn(
300    Request,
301    Next,
302) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Response, Response>> + Send>>
303+ Clone {
304    let action = action.to_string();
305    let resource = resource.to_string();
306
307    move |request: Request, next: Next| {
308        let action = action.clone();
309        let resource = resource.clone();
310        Box::pin(async move {
311            let auth_token = match request.extensions().get::<AuthToken>() {
312                Some(token) => token,
313                None => {
314                    let error_response = ApiResponse::<()>::unauthorized();
315                    return Err(error_response.into_response());
316                }
317            };
318
319            // For this implementation, we'd need access to the authorization service
320            // This would typically be passed through the request state
321            // For now, we'll do a basic permission check using the auth token
322            if check_token_permission(auth_token, &action, &resource) {
323                Ok(next.run(request).await)
324            } else {
325                let error_response = ApiResponse::<()>::forbidden();
326                Err(error_response.into_response())
327            }
328        })
329    }
330}
331
332/// Basic permission check using auth token (fallback)
333fn check_token_permission(auth_token: &AuthToken, action: &str, resource: &str) -> bool {
334    // Check for admin role (has all permissions)
335    if auth_token.roles.contains(&"admin".to_string()) {
336        return true;
337    }
338
339    // Check explicit permissions
340    let required_permission = format!("{}:{}", action, resource);
341    auth_token.permissions.iter().any(|perm| {
342        perm == &required_permission
343            || perm == "*"
344            || (perm.ends_with("*") && required_permission.starts_with(&perm[..perm.len() - 1]))
345    })
346}
347
348#[cfg(test)]
349mod tests {
350    use super::*;
351
352    fn request_from(peer: Option<&str>, xff: Option<&str>) -> Request {
353        let mut b = axum::http::Request::builder().uri("/api/things");
354        if let Some(xff) = xff {
355            b = b.header("x-forwarded-for", xff);
356        }
357        let mut req = b.body(axum::body::Body::empty()).unwrap();
358        if let Some(peer) = peer {
359            let peer: std::net::SocketAddr = format!("{peer}:40000").parse().unwrap();
360            req.extensions_mut()
361                .insert(axum::extract::ConnectInfo(peer));
362        }
363        req
364    }
365
366    #[test]
367    fn the_context_ip_is_the_peer_not_a_forwarded_header() {
368        let token = AuthToken::new("u", "t", std::time::Duration::from_secs(60), "test");
369
370        let spoofed = request_from(Some("198.51.100.9"), Some("10.0.0.5"));
371        let ctx = build_request_context(&spoofed, &token);
372        assert_eq!(ctx["ip_address"], "198.51.100.9");
373
374        // no peer address: no ip at all, whatever the header says
375        let none = request_from(None, Some("10.0.0.5"));
376        assert!(!build_request_context(&none, &token).contains_key("ip_address"));
377    }
378
379    #[test]
380    fn an_ipv4_mapped_peer_is_reported_as_ipv4() {
381        let token = AuthToken::new("u", "t", std::time::Duration::from_secs(60), "test");
382        let mut req = request_from(None, None);
383        let peer: std::net::SocketAddr = "[::ffff:198.51.100.9]:40000".parse().unwrap();
384        req.extensions_mut()
385            .insert(axum::extract::ConnectInfo(peer));
386        assert_eq!(
387            build_request_context(&req, &token)["ip_address"],
388            "198.51.100.9"
389        );
390    }
391
392    #[test]
393    fn test_public_endpoint_detection() {
394        assert!(is_public_endpoint("/health"));
395        assert!(is_public_endpoint("/auth/login"));
396        assert!(is_public_endpoint(
397            "/oauth/.well-known/openid_configuration"
398        ));
399        assert!(!is_public_endpoint("/api/users"));
400        assert!(!is_public_endpoint("/admin/roles"));
401    }
402
403    #[test]
404    fn test_sensitive_endpoint_detection() {
405        assert!(is_sensitive_endpoint("/admin/users"));
406        assert!(is_sensitive_endpoint("/api/secrets/vault"));
407        assert!(is_sensitive_endpoint("/auth/logout"));
408        assert!(!is_sensitive_endpoint("/api/health"));
409        assert!(!is_sensitive_endpoint("/public/info"));
410    }
411
412    #[test]
413    fn test_elevation_requirement() {
414        assert!(requires_role_elevation("/admin/users/delete/123"));
415        assert!(requires_role_elevation("/admin/system/shutdown"));
416        assert!(requires_role_elevation("/api/sudo/execute"));
417        assert!(!requires_role_elevation("/admin/users"));
418        assert!(!requires_role_elevation("/api/profile"));
419    }
420
421    #[test]
422    fn test_context_building() {
423        // This would require setting up a mock request, which is complex
424        // In a real test, we'd create a proper test request and verify context
425        let context: HashMap<String, String> = HashMap::new();
426        assert!(context.is_empty()); // Placeholder test
427    }
428}