Skip to main content

auth_framework/api/
middleware.rs

1//! API Middleware
2//!
3//! Authentication, authorization, rate limiting, and other middleware
4
5use crate::api::{ApiResponse, ApiState, extract_bearer_token, validate_api_token};
6use axum::{
7    extract::{Request, State},
8    middleware::Next,
9    response::{IntoResponse, Response},
10};
11#[cfg(feature = "enhanced-rbac")]
12use std::net::{IpAddr, SocketAddr};
13use std::time::{Duration, Instant};
14
15/// The client address of a request: the connection's peer, unless the peer is one of the
16/// `trusted_proxies`, in which case the client it forwarded for.
17///
18/// A peer that is not a trusted proxy IS the client: its headers are ignored. A trusted
19/// proxy is believed: the client is the rightmost `X-Forwarded-For` entry that is not itself
20/// a trusted proxy (the entries to its left were supplied by the client and are ignored),
21/// else the proxy's own address (`X-Real-IP` is not consulted: many proxies pass a
22/// client-supplied copy through). Every trusted proxy must APPEND to `X-Forwarded-For`
23/// rather than pass it through. Anything unparsable falls back to the peer.
24#[cfg(feature = "enhanced-rbac")]
25pub(crate) fn forwarded_client_ip(
26    peer: IpAddr,
27    headers: &axum::http::HeaderMap,
28    trusted_proxies: &[IpAddr],
29) -> IpAddr {
30    let peer = peer.to_canonical();
31    let is_trusted = |ip: &IpAddr| trusted_proxies.iter().any(|t| t.to_canonical() == *ip);
32    if !is_trusted(&peer) {
33        return peer;
34    }
35    // A header line that is not text cannot be read, so which entry is rightmost is unknown:
36    // believe nothing and keep the peer.
37    let mut entries: Vec<&str> = Vec::new();
38    for value in headers.get_all("x-forwarded-for") {
39        match value.to_str() {
40            Ok(text) => entries.extend(text.split(',').map(str::trim)),
41            Err(_) => return peer,
42        }
43    }
44    for entry in entries.iter().rev() {
45        match parse_forwarded_addr(entry) {
46            Some(ip) if is_trusted(&ip) => continue,
47            Some(ip) => return ip,
48            None => return peer,
49        }
50    }
51    peer
52}
53
54/// Parse one `X-Forwarded-For` entry: a bare address, `addr:port`, or `[v6]` / `[v6]:port`.
55#[cfg(feature = "enhanced-rbac")]
56fn parse_forwarded_addr(entry: &str) -> Option<IpAddr> {
57    if let Ok(ip) = entry.parse::<IpAddr>() {
58        return Some(ip.to_canonical());
59    }
60    if let Ok(sock) = entry.parse::<SocketAddr>() {
61        return Some(sock.ip().to_canonical());
62    }
63    entry
64        .strip_prefix('[')
65        .and_then(|rest| rest.strip_suffix(']'))
66        .and_then(|inner| inner.parse::<IpAddr>().ok())
67        .map(|ip| ip.to_canonical())
68}
69
70/// Authentication middleware
71#[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
72pub async fn auth_middleware(
73    State(state): State<ApiState>,
74    mut request: Request,
75    next: Next,
76) -> Result<Response, Response> {
77    // Skip auth for public endpoints
78    let path = request.uri().path();
79    if is_public_endpoint(path) {
80        return Ok(next.run(request).await);
81    }
82
83    // Extract token from headers
84    let headers = request.headers();
85    match extract_bearer_token(headers) {
86        Some(token) => {
87            // Validate token
88            match validate_api_token(&state.auth_framework, &token).await {
89                Ok(auth_token) => {
90                    // Add auth token to request extensions for use in handlers
91                    request.extensions_mut().insert(auth_token);
92                    Ok(next.run(request).await)
93                }
94                Err(_) => {
95                    let error_response = ApiResponse::<()>::unauthorized();
96                    Err(error_response.into_response())
97                }
98            }
99        }
100        None => {
101            let error_response = ApiResponse::<()>::unauthorized();
102            Err(error_response.into_response())
103        }
104    }
105}
106
107/// Admin authorization middleware
108#[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
109pub async fn admin_middleware(
110    State(_state): State<ApiState>,
111    request: Request,
112    next: Next,
113) -> Result<Response, Response> {
114    // Get auth token from extensions (should be set by auth_middleware)
115    match request.extensions().get::<crate::tokens::AuthToken>() {
116        Some(auth_token) => {
117            if auth_token.roles.contains(&"admin".to_string()) {
118                Ok(next.run(request).await)
119            } else {
120                let error_response = ApiResponse::<()>::forbidden();
121                Err(error_response.into_response())
122            }
123        }
124        None => {
125            // If no auth token, user is not authenticated
126            let error_response = ApiResponse::<()>::unauthorized();
127            Err(error_response.into_response())
128        }
129    }
130}
131
132/// Rate limiting middleware
133#[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
134pub async fn rate_limit_middleware(request: Request, next: Next) -> Result<Response, Response> {
135    // In a real implementation, use a distributed rate limiter like Redis
136    // For now, just add rate limit headers
137
138    let mut response = next.run(request).await;
139
140    // Add rate limit headers
141    let headers = response.headers_mut();
142    headers.insert("X-RateLimit-Limit", "100".parse().unwrap());
143    headers.insert("X-RateLimit-Remaining", "95".parse().unwrap());
144    headers.insert("X-RateLimit-Reset", "1692278400".parse().unwrap()); // Unix timestamp
145
146    Ok(response)
147}
148
149/// CORS middleware
150pub async fn cors_middleware(request: Request, next: Next) -> Response {
151    let response = next.run(request).await;
152
153    let mut response = response;
154    let headers = response.headers_mut();
155
156    headers.insert("Access-Control-Allow-Origin", "*".parse().unwrap());
157    headers.insert(
158        "Access-Control-Allow-Methods",
159        "GET, POST, PUT, DELETE, OPTIONS".parse().unwrap(),
160    );
161    headers.insert(
162        "Access-Control-Allow-Headers",
163        "Content-Type, Authorization".parse().unwrap(),
164    );
165    headers.insert("Access-Control-Max-Age", "3600".parse().unwrap());
166
167    response
168}
169
170/// Logging middleware
171pub async fn logging_middleware(request: Request, next: Next) -> Response {
172    let start = Instant::now();
173    let method = request.method().clone();
174    let uri = request.uri().clone();
175    let headers = request.headers().clone();
176
177    // Extract user agent and IP for logging
178    let user_agent = headers
179        .get("user-agent")
180        .and_then(|v| v.to_str().ok())
181        .unwrap_or("unknown");
182
183    let forwarded_for = headers
184        .get("x-forwarded-for")
185        .and_then(|v| v.to_str().ok())
186        .unwrap_or("unknown");
187
188    tracing::info!(
189        "Request started: {} {} from {} ({})",
190        method,
191        uri,
192        forwarded_for,
193        user_agent
194    );
195
196    let response = next.run(request).await;
197    let duration = start.elapsed();
198    let status = response.status();
199
200    tracing::info!(
201        "Request completed: {} {} {} in {:?}",
202        method,
203        uri,
204        status,
205        duration
206    );
207
208    response
209}
210
211/// Security headers middleware
212pub async fn security_headers_middleware(request: Request, next: Next) -> Response {
213    let response = next.run(request).await;
214
215    let mut response = response;
216    let headers = response.headers_mut();
217
218    // Security headers
219    headers.insert("X-Content-Type-Options", "nosniff".parse().unwrap());
220    headers.insert("X-Frame-Options", "DENY".parse().unwrap());
221    headers.insert("X-XSS-Protection", "1; mode=block".parse().unwrap());
222    headers.insert(
223        "Strict-Transport-Security",
224        "max-age=31536000; includeSubDomains".parse().unwrap(),
225    );
226    headers.insert(
227        "Referrer-Policy",
228        "strict-origin-when-cross-origin".parse().unwrap(),
229    );
230    headers.insert(
231        "Permissions-Policy",
232        "camera=(), microphone=(), geolocation=()".parse().unwrap(),
233    );
234
235    response
236}
237
238/// Request timeout middleware
239#[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
240pub async fn timeout_middleware(request: Request, next: Next) -> Result<Response, Response> {
241    // Set a 30-second timeout for all requests
242    match tokio::time::timeout(Duration::from_secs(30), next.run(request)).await {
243        Ok(response) => Ok(response),
244        Err(_) => {
245            let error_response =
246                ApiResponse::<()>::error("REQUEST_TIMEOUT", "Request timed out after 30 seconds");
247            Err(error_response.into_response())
248        }
249    }
250}
251
252/// Check if endpoint is public (doesn't require authentication)
253fn is_public_endpoint(path: &str) -> bool {
254    match path {
255        "/health" | "/health/detailed" | "/metrics" | "/readiness" | "/liveness" => true,
256        "/auth/login" | "/auth/refresh" | "/auth/providers" => true,
257        "/oauth/authorize" | "/oauth/token" | "/oauth/.well-known/openid_configuration" => true,
258        _ if path.starts_with("/oauth/.well-known/") => true,
259        _ => false,
260    }
261}
262
263/// Permission check helper
264pub fn check_permission(auth_token: &crate::tokens::AuthToken, required_permission: &str) -> bool {
265    auth_token.permissions.iter().any(|perm| {
266        perm == required_permission
267            || perm == "*"
268            || (perm.ends_with("*") && required_permission.starts_with(&perm[..perm.len() - 1]))
269    })
270}
271
272/// Role check helper
273pub fn check_role(auth_token: &crate::tokens::AuthToken, required_role: &str) -> bool {
274    auth_token.roles.contains(&required_role.to_string())
275        || auth_token.roles.contains(&"admin".to_string()) // Admin has all roles
276}