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};
6use crate::distributed::rate_limiting::RateLimitResult;
7use axum::{
8    extract::{ConnectInfo, Request},
9    http::StatusCode,
10    middleware::Next,
11    response::{IntoResponse, Response},
12};
13use std::net::{IpAddr, SocketAddr};
14use std::time::{Duration, Instant};
15
16/// Sanitize a header value for safe inclusion in log output.
17/// Strips control characters (except space) and truncates to 200 chars
18/// to prevent log injection and log flooding.
19fn sanitize_header_for_log(value: &str) -> String {
20    value
21        .chars()
22        .filter(|c| !c.is_control() || *c == ' ')
23        .take(200)
24        .collect()
25}
26
27/// The address to rate-limit a request under.
28///
29/// A peer that is not a trusted proxy IS the client: its headers are ignored. A trusted
30/// proxy is believed: the client is the rightmost `X-Forwarded-For` entry that is not itself
31/// a trusted proxy (the entries to its left were supplied by the client and are ignored),
32/// else the proxy's own address (`X-Real-IP` is not consulted: many proxies pass a
33/// client-supplied copy through). Every trusted proxy must APPEND to `X-Forwarded-For`
34/// rather than pass it through. Anything unparsable falls back to the peer.
35pub(crate) fn forwarded_client_ip(
36    peer: IpAddr,
37    headers: &axum::http::HeaderMap,
38    trusted_proxies: &[IpAddr],
39) -> IpAddr {
40    let peer = peer.to_canonical();
41    let is_trusted = |ip: &IpAddr| trusted_proxies.iter().any(|t| t.to_canonical() == *ip);
42    if !is_trusted(&peer) {
43        return peer;
44    }
45    let entries: Vec<&str> = headers
46        .get_all("x-forwarded-for")
47        .iter()
48        .filter_map(|v| v.to_str().ok())
49        .flat_map(|v| v.split(','))
50        .map(str::trim)
51        .collect();
52    for entry in entries.iter().rev() {
53        match parse_forwarded_addr(entry) {
54            Some(ip) if is_trusted(&ip) => continue,
55            Some(ip) => return ip,
56            None => return peer,
57        }
58    }
59    peer
60}
61
62/// The rate-limit bucket for an address. IPv6 clients are bucketed by their /64 (the size of
63/// a single end-user allocation), so one client cannot mint a bucket per address.
64fn rate_limit_key(ip: IpAddr) -> String {
65    match ip {
66        IpAddr::V4(v4) => v4.to_string(),
67        IpAddr::V6(v6) => {
68            let o = v6.octets();
69            let prefix = std::net::Ipv6Addr::from([
70                o[0], o[1], o[2], o[3], o[4], o[5], o[6], o[7], 0, 0, 0, 0, 0, 0, 0, 0,
71            ]);
72            format!("{prefix}/64")
73        }
74    }
75}
76
77/// Parse one `X-Forwarded-For` entry: a bare address, `addr:port`, or `[v6]` / `[v6]:port`.
78fn parse_forwarded_addr(entry: &str) -> Option<IpAddr> {
79    if let Ok(ip) = entry.parse::<IpAddr>() {
80        return Some(ip.to_canonical());
81    }
82    if let Ok(sock) = entry.parse::<SocketAddr>() {
83        return Some(sock.ip().to_canonical());
84    }
85    entry
86        .strip_prefix('[')
87        .and_then(|rest| rest.strip_suffix(']'))
88        .and_then(|inner| inner.parse::<IpAddr>().ok())
89        .map(|ip| ip.to_canonical())
90}
91
92/// Rate limiting middleware backed by [`crate::distributed::rate_limiting::DistributedRateLimiter`].
93///
94/// Uses the connection's peer address (see [`forwarded_client_ip`]) as the rate-limiting key.  Returns **429 Too Many Requests** when the limit
95/// is exceeded and adds standard `X-RateLimit-*` response headers on every response.
96// Boxing the Err variant would require `Box<Response>` to implement Axum's
97// `IntoResponse`, which it does not by default; both arms are already the
98// same `Response` type this middleware pattern requires.
99#[allow(clippy::result_large_err)]
100pub async fn rate_limit_middleware_with_state(
101    state: ApiState,
102    request: Request,
103    next: Next,
104) -> Result<Response, Response> {
105    // The client is identified by the connection's peer address. `X-Forwarded-For` is
106    // client-controlled, so it is believed only when the peer is a configured trusted proxy.
107    let peer = request
108        .extensions()
109        .get::<ConnectInfo<SocketAddr>>()
110        .map(|info| info.0.ip());
111    let client_key = match peer {
112        Some(peer) => rate_limit_key(forwarded_client_ip(
113            peer,
114            request.headers(),
115            &state.trusted_proxies,
116        )),
117        None => {
118            static WARNED: std::sync::atomic::AtomicBool =
119                std::sync::atomic::AtomicBool::new(false);
120            if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) {
121                tracing::warn!(
122                    "Rate limiter: requests carry no peer address, so all of them share one \
123                     bucket. Serve the router with \
124                     `into_make_service_with_connect_info::<SocketAddr>()`."
125                );
126            }
127            "unidentified".to_string()
128        }
129    };
130
131    match state.rate_limiter.check_rate_limit(&client_key).await {
132        Ok(RateLimitResult::Allowed {
133            remaining,
134            reset_at,
135        }) => {
136            let mut response = next.run(request).await;
137            let headers = response.headers_mut();
138            let reset_secs = reset_at
139                .checked_duration_since(Instant::now())
140                .unwrap_or(Duration::ZERO)
141                .as_secs();
142            if let Ok(v) = remaining.to_string().parse() {
143                headers.insert("X-RateLimit-Remaining", v);
144            }
145            if let Ok(v) = reset_secs.to_string().parse() {
146                headers.insert("X-RateLimit-Reset", v);
147            }
148            Ok(response)
149        }
150        Ok(RateLimitResult::Denied { retry_after, .. }) => {
151            tracing::warn!(client = %client_key, "Rate limit exceeded");
152            let mut response = ApiResponse::<()>::error(
153                "RATE_LIMIT_EXCEEDED",
154                "Too many requests — please retry after the indicated delay",
155            )
156            .into_response();
157            *response.status_mut() = StatusCode::TOO_MANY_REQUESTS;
158            let headers = response.headers_mut();
159            if let Ok(v) = retry_after.as_secs().to_string().parse() {
160                headers.insert("Retry-After", v);
161            }
162            Err(response)
163        }
164        Ok(RateLimitResult::Blocked { unblock_at, reason }) => {
165            tracing::warn!(client = %client_key, reason = %reason, "Client is blocked");
166            let mut response = ApiResponse::<()>::error(
167                "CLIENT_BLOCKED",
168                "Access temporarily blocked due to repeated rate limit violations",
169            )
170            .into_response();
171            *response.status_mut() = StatusCode::TOO_MANY_REQUESTS;
172            let unblock_secs = unblock_at
173                .checked_duration_since(Instant::now())
174                .unwrap_or(Duration::ZERO)
175                .as_secs();
176            if let Ok(v) = unblock_secs.to_string().parse() {
177                let headers = response.headers_mut();
178                headers.insert("Retry-After", v);
179            }
180            Err(response)
181        }
182        Err(e) => {
183            tracing::error!(error = %e, "Rate limiter error — rejecting request");
184            let mut response = ApiResponse::<()>::error(
185                "RATE_LIMIT_UNAVAILABLE",
186                "Rate limiting is temporarily unavailable; request rejected to protect the service",
187            )
188            .into_response();
189            *response.status_mut() = StatusCode::SERVICE_UNAVAILABLE;
190            Err(response)
191        }
192    }
193}
194
195// cors_middleware was removed: it set `Access-Control-Allow-Origin: *` which is
196// inappropriate for an authentication service.  Use tower-http's `CorsLayer`
197// with a configured `AllowOrigin` list instead.
198
199/// Log every incoming HTTP request with method, URI, client IP, and user-agent.
200///
201/// Elapsed time is logged on the response path.
202///
203/// # Example
204/// ```rust,ignore
205/// let app = Router::new()
206///     .layer(axum::middleware::from_fn(logging_middleware));
207/// ```
208pub async fn logging_middleware(request: Request, next: Next) -> Response {
209    let start = Instant::now();
210    let method = request.method().clone();
211    let uri = request.uri().clone();
212    let headers = request.headers().clone();
213
214    // Extract user agent and IP for logging, sanitized to prevent log injection
215    let user_agent = headers
216        .get("user-agent")
217        .and_then(|v| v.to_str().ok())
218        .unwrap_or("unknown");
219    let user_agent = sanitize_header_for_log(user_agent);
220
221    let forwarded_for = headers
222        .get("x-forwarded-for")
223        .and_then(|v| v.to_str().ok())
224        .unwrap_or("unknown");
225    let forwarded_for = sanitize_header_for_log(forwarded_for);
226
227    tracing::info!(
228        "Request started: {} {} from {} ({})",
229        method,
230        uri,
231        forwarded_for,
232        user_agent
233    );
234
235    let response = next.run(request).await;
236    let duration = start.elapsed();
237    let status = response.status();
238
239    tracing::info!(
240        "Request completed: {} {} {} in {:?}",
241        method,
242        uri,
243        status,
244        duration
245    );
246
247    response
248}
249
250/// Security headers middleware
251pub async fn security_headers_middleware(request: Request, next: Next) -> Response {
252    let response = next.run(request).await;
253
254    let mut response = response;
255    let headers = response.headers_mut();
256
257    // Security headers — all values are well-known static strings so from_static is safe.
258    headers.insert(
259        "X-Content-Type-Options",
260        axum::http::HeaderValue::from_static("nosniff"),
261    );
262    headers.insert(
263        "X-Frame-Options",
264        axum::http::HeaderValue::from_static("DENY"),
265    );
266    headers.insert(
267        "X-XSS-Protection",
268        axum::http::HeaderValue::from_static("1; mode=block"),
269    );
270    headers.insert(
271        "Strict-Transport-Security",
272        axum::http::HeaderValue::from_static("max-age=31536000; includeSubDomains"),
273    );
274    headers.insert(
275        "Referrer-Policy",
276        axum::http::HeaderValue::from_static("strict-origin-when-cross-origin"),
277    );
278    headers.insert(
279        "Permissions-Policy",
280        axum::http::HeaderValue::from_static("camera=(), microphone=(), geolocation=()"),
281    );
282    headers.insert(
283        "Content-Security-Policy",
284        axum::http::HeaderValue::from_static("default-src 'none'; frame-ancestors 'none'"),
285    );
286
287    response
288}
289
290/// Request timeout middleware
291// See the allow rationale on `rate_limit_middleware_with_state` above.
292#[allow(clippy::result_large_err)]
293pub async fn timeout_middleware(request: Request, next: Next) -> Result<Response, Response> {
294    // Set a 30-second timeout for all requests
295    match tokio::time::timeout(Duration::from_secs(30), next.run(request)).await {
296        Ok(response) => Ok(response),
297        Err(_) => {
298            let error_response =
299                ApiResponse::<()>::error("REQUEST_TIMEOUT", "Request timed out after 30 seconds");
300            Err(error_response.into_response())
301        }
302    }
303}
304
305/// Check whether `auth_token` carries the given permission.
306///
307/// Supports exact matches, a wildcard `"*"`, and prefix wildcards such as
308/// `"read:*"` (matches `"read:users"`, `"read:settings"`, etc.).
309///
310/// # Example
311/// ```rust,ignore
312/// if check_permission(&token, "users:write") {
313///     // allow the operation
314/// }
315/// ```
316pub fn check_permission(auth_token: &crate::tokens::AuthToken, required_permission: &str) -> bool {
317    auth_token.permissions.iter().any(|perm| {
318        perm == required_permission
319            || perm == "*"
320            || (perm.ends_with("*") && required_permission.starts_with(&perm[..perm.len() - 1]))
321    })
322}
323
324/// Check whether `auth_token` carries the given role.
325///
326/// The `"admin"` role implicitly matches every role.
327///
328/// # Example
329/// ```rust,ignore
330/// if check_role(&token, "moderator") {
331///     // allow moderation actions
332/// }
333/// ```
334pub fn check_role(auth_token: &crate::tokens::AuthToken, required_role: &str) -> bool {
335    auth_token.roles.contains(required_role) || auth_token.roles.contains("admin") // Admin has all roles
336}
337
338#[cfg(test)]
339mod tests {
340    use super::*;
341    use crate::tokens::{AuthToken, TokenMetadata};
342
343    fn make_token(permissions: Vec<&str>, roles: Vec<&str>) -> AuthToken {
344        AuthToken {
345            token_id: "tid".into(),
346            user_id: "uid".into(),
347            access_token: "at".into(),
348            token_type: Some("Bearer".into()),
349            subject: Some("uid".into()),
350            issuer: Some("iss".into()),
351            refresh_token: None,
352            issued_at: chrono::Utc::now(),
353            expires_at: chrono::Utc::now(),
354            scopes: vec![].into(),
355            auth_method: "jwt".into(),
356            client_id: None,
357            user_profile: None,
358            permissions: permissions
359                .into_iter()
360                .map(String::from)
361                .collect::<Vec<_>>()
362                .into(),
363            roles: roles
364                .into_iter()
365                .map(String::from)
366                .collect::<Vec<_>>()
367                .into(),
368            metadata: TokenMetadata::default(),
369        }
370    }
371
372    // ── check_permission ────────────────────────────────────────────────
373
374    #[test]
375    fn test_check_permission_exact_match() {
376        let token = make_token(vec!["users:read"], vec![]);
377        assert!(check_permission(&token, "users:read"));
378    }
379
380    #[test]
381    fn test_check_permission_no_match() {
382        let token = make_token(vec!["users:read"], vec![]);
383        assert!(!check_permission(&token, "users:write"));
384    }
385
386    #[test]
387    fn test_check_permission_wildcard_all() {
388        let token = make_token(vec!["*"], vec![]);
389        assert!(check_permission(&token, "anything:at:all"));
390    }
391
392    #[test]
393    fn test_check_permission_wildcard_prefix() {
394        let token = make_token(vec!["users:*"], vec![]);
395        assert!(check_permission(&token, "users:read"));
396        assert!(check_permission(&token, "users:write"));
397        assert!(!check_permission(&token, "admin:read"));
398    }
399
400    #[test]
401    fn test_check_permission_empty() {
402        let token = make_token(vec![], vec![]);
403        assert!(!check_permission(&token, "anything"));
404    }
405
406    // ── check_role ──────────────────────────────────────────────────────
407
408    #[test]
409    fn test_check_role_exact_match() {
410        let token = make_token(vec![], vec!["editor"]);
411        assert!(check_role(&token, "editor"));
412    }
413
414    #[test]
415    fn test_check_role_no_match() {
416        let token = make_token(vec![], vec!["editor"]);
417        assert!(!check_role(&token, "moderator"));
418    }
419
420    #[test]
421    fn test_check_role_admin_has_all_roles() {
422        let token = make_token(vec![], vec!["admin"]);
423        assert!(check_role(&token, "anything"));
424        assert!(check_role(&token, "editor"));
425    }
426
427    #[test]
428    fn test_check_role_empty() {
429        let token = make_token(vec![], vec![]);
430        assert!(!check_role(&token, "user"));
431    }
432
433    fn ip(s: &str) -> IpAddr {
434        s.parse().unwrap()
435    }
436
437    fn headers(pairs: &[(&str, &str)]) -> axum::http::HeaderMap {
438        let mut h = axum::http::HeaderMap::new();
439        for (k, v) in pairs {
440            h.append(
441                axum::http::HeaderName::from_bytes(k.as_bytes()).unwrap(),
442                v.parse().unwrap(),
443            );
444        }
445        h
446    }
447
448    #[test]
449    fn ipv6_clients_share_a_bucket_per_slash_64() {
450        assert_eq!(rate_limit_key(ip("203.0.113.7")), "203.0.113.7");
451        let a = rate_limit_key(ip("2001:db8:1:2:aaaa:bbbb:cccc:dddd"));
452        let b = rate_limit_key(ip("2001:db8:1:2::1"));
453        let c = rate_limit_key(ip("2001:db8:1:3::1"));
454        assert_eq!(a, b, "same /64");
455        assert_ne!(a, c, "different /64");
456    }
457
458    #[test]
459    fn forwarded_for_is_ignored_unless_the_peer_is_trusted() {
460        let h = headers(&[("x-forwarded-for", "1.2.3.4"), ("x-real-ip", "5.6.7.8")]);
461        assert_eq!(forwarded_client_ip(ip("9.9.9.9"), &h, &[]), ip("9.9.9.9"));
462        assert_eq!(
463            forwarded_client_ip(ip("9.9.9.9"), &h, &[ip("10.0.0.1")]),
464            ip("9.9.9.9")
465        );
466    }
467
468    #[test]
469    fn a_trusted_proxy_is_believed_from_the_right() {
470        let proxies = [ip("10.0.0.1"), ip("10.0.0.2")];
471        // client-supplied "6.6.6.6", then what the proxies appended
472        let h = headers(&[("x-forwarded-for", "6.6.6.6, 203.0.113.7, 10.0.0.2")]);
473        assert_eq!(
474            forwarded_client_ip(ip("10.0.0.1"), &h, &proxies),
475            ip("203.0.113.7")
476        );
477        // several header lines are one list
478        let h = headers(&[
479            ("x-forwarded-for", "6.6.6.6"),
480            ("x-forwarded-for", "203.0.113.7"),
481        ]);
482        assert_eq!(
483            forwarded_client_ip(ip("10.0.0.1"), &h, &proxies),
484            ip("203.0.113.7")
485        );
486        // an IPv4-mapped IPv6 peer is the same proxy
487        assert_eq!(
488            forwarded_client_ip(ip("::ffff:10.0.0.1"), &h, &proxies),
489            ip("203.0.113.7")
490        );
491    }
492
493    #[test]
494    fn unusable_forwarding_headers_fall_back_to_the_proxy_or_real_ip() {
495        let proxies = [ip("10.0.0.1")];
496        let h = headers(&[("x-forwarded-for", "203.0.113.7, garbage")]);
497        assert_eq!(
498            forwarded_client_ip(ip("10.0.0.1"), &h, &proxies),
499            ip("10.0.0.1")
500        );
501        assert_eq!(
502            forwarded_client_ip(ip("10.0.0.1"), &headers(&[]), &proxies),
503            ip("10.0.0.1")
504        );
505        // X-Real-IP is never consulted, with or without X-Forwarded-For
506        let h = headers(&[("x-real-ip", "198.51.100.4")]);
507        assert_eq!(
508            forwarded_client_ip(ip("10.0.0.1"), &h, &proxies),
509            ip("10.0.0.1")
510        );
511        let h = headers(&[
512            ("x-forwarded-for", "203.0.113.7"),
513            ("x-real-ip", "198.51.100.4"),
514        ]);
515        assert_eq!(
516            forwarded_client_ip(ip("10.0.0.1"), &h, &proxies),
517            ip("203.0.113.7")
518        );
519        // a chain made only of trusted proxies identifies the last proxy
520        let h = headers(&[("x-forwarded-for", "10.0.0.2, 10.0.0.1")]);
521        assert_eq!(
522            forwarded_client_ip(ip("10.0.0.1"), &h, &[ip("10.0.0.1"), ip("10.0.0.2")]),
523            ip("10.0.0.1")
524        );
525    }
526
527    #[test]
528    fn forwarded_entries_with_ports_and_brackets_are_understood() {
529        let proxies = [ip("10.0.0.1")];
530        for (entry, want) in [
531            ("203.0.113.7:51234", "203.0.113.7"),
532            ("[2001:db8::7]", "2001:db8::7"),
533            ("[2001:db8::7]:443", "2001:db8::7"),
534            ("::ffff:203.0.113.7", "203.0.113.7"),
535        ] {
536            let h = headers(&[("x-forwarded-for", entry)]);
537            assert_eq!(
538                forwarded_client_ip(ip("10.0.0.1"), &h, &proxies),
539                ip(want),
540                "{entry}"
541            );
542        }
543    }
544}