|
6 | 6 | #[cfg(feature = "http-api")]
|
7 | 7 | use axum::{extract::Request, http::StatusCode, middleware::Next, response::Response};
|
8 | 8 |
|
| 9 | +#[cfg(feature = "http-api")] |
| 10 | +use governor::{ |
| 11 | + clock::DefaultClock, |
| 12 | + state::{InMemoryState, NotKeyed}, |
| 13 | + Quota, RateLimiter, |
| 14 | +}; |
| 15 | + |
| 16 | +#[cfg(feature = "http-api")] |
| 17 | +use std::{net::IpAddr, num::NonZeroU32, sync::{Arc, OnceLock}}; |
| 18 | + |
| 19 | +#[cfg(feature = "http-api")] |
| 20 | +use dashmap::DashMap; |
| 21 | + |
9 | 22 | /// Authentication middleware for bearer token validation
|
10 | 23 | #[cfg(feature = "http-api")]
|
11 | 24 | pub async fn auth_middleware(request: Request, next: Next) -> Result<Response, StatusCode> {
|
@@ -40,38 +53,193 @@ pub async fn auth_middleware(request: Request, next: Next) -> Result<Response, S
|
40 | 53 | Ok(next.run(request).await)
|
41 | 54 | }
|
42 | 55 |
|
43 |
| -/// Rate limiting middleware (placeholder) |
| 56 | +/// Global rate limiter store for per-IP rate limiting |
| 57 | +#[cfg(feature = "http-api")] |
| 58 | +static RATE_LIMITERS: OnceLock<DashMap<IpAddr, Arc<RateLimiter<NotKeyed, InMemoryState, DefaultClock>>>> = OnceLock::new(); |
| 59 | + |
| 60 | +/// Get or create a rate limiter for a specific IP address |
| 61 | +#[cfg(feature = "http-api")] |
| 62 | +fn get_rate_limiter_for_ip(ip: IpAddr) -> Arc<RateLimiter<NotKeyed, InMemoryState, DefaultClock>> { |
| 63 | + let limiters = RATE_LIMITERS.get_or_init(DashMap::new); |
| 64 | + |
| 65 | + // Check if limiter exists, if not create one |
| 66 | + if let Some(limiter) = limiters.get(&ip) { |
| 67 | + Arc::clone(&limiter) |
| 68 | + } else { |
| 69 | + // Create a rate limiter: 100 requests per minute (roughly 1.67 requests per second) |
| 70 | + let quota = Quota::per_minute(NonZeroU32::new(100).unwrap()); |
| 71 | + let limiter = Arc::new(RateLimiter::direct(quota)); |
| 72 | + limiters.insert(ip, Arc::clone(&limiter)); |
| 73 | + limiter |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +/// Extract client IP address from request |
| 78 | +#[cfg(feature = "http-api")] |
| 79 | +fn extract_client_ip(request: &Request) -> IpAddr { |
| 80 | + // Try to get real IP from X-Forwarded-For header first (for proxy setups) |
| 81 | + if let Some(forwarded_for) = request.headers().get("x-forwarded-for") { |
| 82 | + if let Ok(forwarded_str) = forwarded_for.to_str() { |
| 83 | + // X-Forwarded-For can contain multiple IPs, take the first one |
| 84 | + if let Some(first_ip) = forwarded_str.split(',').next() { |
| 85 | + if let Ok(ip) = first_ip.trim().parse::<IpAddr>() { |
| 86 | + return ip; |
| 87 | + } |
| 88 | + } |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + // Try X-Real-IP header |
| 93 | + if let Some(real_ip) = request.headers().get("x-real-ip") { |
| 94 | + if let Ok(real_ip_str) = real_ip.to_str() { |
| 95 | + if let Ok(ip) = real_ip_str.parse::<IpAddr>() { |
| 96 | + return ip; |
| 97 | + } |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + // Fallback to connection info or default |
| 102 | + // In a real setup, you'd extract this from the connection info |
| 103 | + // For now, we'll use a default IP as fallback |
| 104 | + "127.0.0.1".parse().unwrap() |
| 105 | +} |
| 106 | + |
| 107 | +/// Rate limiting middleware using token bucket algorithm |
| 108 | +/// |
| 109 | +/// This middleware implements per-IP rate limiting with a token bucket algorithm. |
| 110 | +/// Each IP address gets 100 requests per minute (approximately 1.67 RPS). |
| 111 | +/// |
| 112 | +/// Rate limiters are stored in a global concurrent HashMap and are created |
| 113 | +/// on-demand for each unique IP address. |
44 | 114 | #[cfg(feature = "http-api")]
|
45 | 115 | pub async fn rate_limit_middleware(request: Request, next: Next) -> Result<Response, StatusCode> {
|
46 |
| - // TODO: Implement rate limiting logic |
47 |
| - // For now, just pass through all requests |
48 |
| - Ok(next.run(request).await) |
| 116 | + // Extract client IP address |
| 117 | + let client_ip = extract_client_ip(&request); |
| 118 | + |
| 119 | + // Get the rate limiter for this IP |
| 120 | + let rate_limiter = get_rate_limiter_for_ip(client_ip); |
| 121 | + |
| 122 | + // Check if the request is allowed |
| 123 | + match rate_limiter.check() { |
| 124 | + Ok(_) => { |
| 125 | + // Request is allowed, proceed |
| 126 | + Ok(next.run(request).await) |
| 127 | + } |
| 128 | + Err(_) => { |
| 129 | + // Rate limit exceeded |
| 130 | + tracing::warn!("Rate limit exceeded for IP: {}", client_ip); |
| 131 | + Err(StatusCode::TOO_MANY_REQUESTS) |
| 132 | + } |
| 133 | + } |
49 | 134 | }
|
50 | 135 |
|
51 |
| -/// Request logging middleware (placeholder) |
| 136 | +/// Enhanced request logging middleware with structured logging |
| 137 | +/// |
| 138 | +/// Logs comprehensive request details including: |
| 139 | +/// - HTTP method and URI |
| 140 | +/// - Response status code and processing latency |
| 141 | +/// - Client IP address and response body size |
| 142 | +/// - Uses structured logging with tracing spans for request grouping |
52 | 143 | #[cfg(feature = "http-api")]
|
53 | 144 | pub async fn logging_middleware(request: Request, next: Next) -> Result<Response, StatusCode> {
|
54 |
| - // TODO: Implement request logging |
55 |
| - // For now, just pass through all requests |
| 145 | + use std::time::Instant; |
| 146 | + |
| 147 | + // Extract request details |
56 | 148 | let method = request.method().clone();
|
57 | 149 | let uri = request.uri().clone();
|
58 |
| - |
59 |
| - tracing::debug!("Incoming request: {} {}", method, uri); |
60 |
| - |
| 150 | + let client_ip = extract_client_ip(&request); |
| 151 | + |
| 152 | + // Create a structured span for this request |
| 153 | + let span = tracing::info_span!( |
| 154 | + "http_request", |
| 155 | + method = %method, |
| 156 | + uri = %uri, |
| 157 | + client_ip = %client_ip, |
| 158 | + status_code = tracing::field::Empty, |
| 159 | + latency_ms = tracing::field::Empty, |
| 160 | + response_size = tracing::field::Empty, |
| 161 | + ); |
| 162 | + |
| 163 | + let _guard = span.enter(); |
| 164 | + |
| 165 | + // Record start time for latency calculation |
| 166 | + let start_time = Instant::now(); |
| 167 | + |
| 168 | + tracing::info!("Processing request"); |
| 169 | + |
| 170 | + // Process the request |
61 | 171 | let response = next.run(request).await;
|
62 |
| - |
63 |
| - tracing::debug!("Response status: {}", response.status()); |
64 |
| - |
| 172 | + |
| 173 | + // Calculate latency |
| 174 | + let latency = start_time.elapsed(); |
| 175 | + let latency_ms = latency.as_millis() as u64; |
| 176 | + |
| 177 | + // Extract response details |
| 178 | + let status_code = response.status(); |
| 179 | + |
| 180 | + // Try to extract response body size from Content-Length header |
| 181 | + let response_size = response |
| 182 | + .headers() |
| 183 | + .get("content-length") |
| 184 | + .and_then(|h| h.to_str().ok()) |
| 185 | + .and_then(|s| s.parse::<u64>().ok()) |
| 186 | + .unwrap_or(0); |
| 187 | + |
| 188 | + // Record additional fields in the span |
| 189 | + span.record("status_code", status_code.as_u16()); |
| 190 | + span.record("latency_ms", latency_ms); |
| 191 | + span.record("response_size", response_size); |
| 192 | + |
| 193 | + // Log completion with all details |
| 194 | + tracing::info!( |
| 195 | + status_code = status_code.as_u16(), |
| 196 | + latency_ms = latency_ms, |
| 197 | + response_size = response_size, |
| 198 | + "Request completed" |
| 199 | + ); |
| 200 | + |
65 | 201 | Ok(response)
|
66 | 202 | }
|
67 | 203 |
|
68 |
| -/// Security headers middleware (placeholder) |
| 204 | +/// Security headers middleware |
| 205 | +/// |
| 206 | +/// Adds essential security headers to all HTTP responses: |
| 207 | +/// - Strict-Transport-Security: Enforces HTTPS connections |
| 208 | +/// - X-Content-Type-Options: Prevents MIME type sniffing |
| 209 | +/// - X-Frame-Options: Prevents clickjacking attacks |
| 210 | +/// - Content-Security-Policy: Restricts resource loading |
69 | 211 | #[cfg(feature = "http-api")]
|
70 | 212 | pub async fn security_headers_middleware(
|
71 | 213 | request: Request,
|
72 | 214 | next: Next,
|
73 | 215 | ) -> Result<Response, StatusCode> {
|
74 |
| - // TODO: Add security headers |
75 |
| - // For now, just pass through all requests |
76 |
| - Ok(next.run(request).await) |
| 216 | + use axum::http::HeaderValue; |
| 217 | + |
| 218 | + // Process the request |
| 219 | + let mut response = next.run(request).await; |
| 220 | + |
| 221 | + // Add security headers to the response |
| 222 | + let headers = response.headers_mut(); |
| 223 | + |
| 224 | + headers.insert( |
| 225 | + "strict-transport-security", |
| 226 | + HeaderValue::from_static("max-age=63072000; includeSubDomains; preload") |
| 227 | + ); |
| 228 | + |
| 229 | + headers.insert( |
| 230 | + "x-content-type-options", |
| 231 | + HeaderValue::from_static("nosniff") |
| 232 | + ); |
| 233 | + |
| 234 | + headers.insert( |
| 235 | + "x-frame-options", |
| 236 | + HeaderValue::from_static("DENY") |
| 237 | + ); |
| 238 | + |
| 239 | + headers.insert( |
| 240 | + "content-security-policy", |
| 241 | + HeaderValue::from_static("default-src 'self'; frame-ancestors 'none'") |
| 242 | + ); |
| 243 | + |
| 244 | + Ok(response) |
77 | 245 | }
|
0 commit comments