elif-http 0.8.8

HTTP server core for the elif.rs LLM-friendly web framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! # Tracing Middleware
//!
//! Framework middleware for HTTP request tracing and observability using V2 system.
//! Replaces tower-http TraceLayer with framework-native implementation.

use std::time::Instant;
use tracing::{error, info, warn, Level, Span};
use uuid::Uuid;

use crate::{
    middleware::v2::{Middleware, Next, NextFuture},
    request::ElifRequest,
};

/// Configuration for tracing middleware
#[derive(Debug, Clone)]
pub struct TracingConfig {
    /// Whether to trace request bodies
    pub trace_bodies: bool,
    /// Whether to trace response bodies  
    pub trace_response_bodies: bool,
    /// Maximum body size to trace (in bytes)
    pub max_body_size: usize,
    /// Log level for requests
    pub level: Level,
    /// Whether to include sensitive headers in traces
    pub include_sensitive_headers: bool,
    /// Headers considered sensitive (will be redacted)
    pub sensitive_headers: Vec<String>,
}

impl Default for TracingConfig {
    fn default() -> Self {
        Self {
            trace_bodies: false,
            trace_response_bodies: false,
            max_body_size: 1024,
            level: Level::INFO,
            include_sensitive_headers: false,
            sensitive_headers: vec![
                "authorization".to_string(),
                "cookie".to_string(),
                "x-api-key".to_string(),
                "x-auth-token".to_string(),
            ],
        }
    }
}

impl TracingConfig {
    /// Enable body tracing
    pub fn with_body_tracing(mut self) -> Self {
        self.trace_bodies = true;
        self
    }

    /// Enable response body tracing
    pub fn with_response_body_tracing(mut self) -> Self {
        self.trace_response_bodies = true;
        self
    }

    /// Set maximum body size for tracing
    pub fn with_max_body_size(mut self, size: usize) -> Self {
        self.max_body_size = size;
        self
    }

    /// Set tracing level
    pub fn with_level(mut self, level: Level) -> Self {
        self.level = level;
        self
    }

    /// Include sensitive headers in traces (not recommended for production)
    pub fn with_sensitive_headers(mut self) -> Self {
        self.include_sensitive_headers = true;
        self
    }

    /// Add custom sensitive header
    pub fn add_sensitive_header(mut self, header: String) -> Self {
        self.sensitive_headers.push(header.to_lowercase());
        self
    }
}

/// Framework tracing middleware for HTTP requests
#[derive(Debug)]
pub struct TracingMiddleware {
    config: TracingConfig,
}

impl TracingMiddleware {
    /// Create new tracing middleware with default configuration
    pub fn new() -> Self {
        Self {
            config: TracingConfig::default(),
        }
    }

    /// Create tracing middleware with custom configuration
    pub fn with_config(config: TracingConfig) -> Self {
        Self { config }
    }

    /// Enable body tracing
    pub fn with_body_tracing(mut self) -> Self {
        self.config = self.config.with_body_tracing();
        self
    }

    /// Set tracing level
    pub fn with_level(mut self, level: Level) -> Self {
        self.config = self.config.with_level(level);
        self
    }

    #[cfg(test)]
    pub fn is_sensitive_header(&self, header: &str) -> bool {
        let header_lower = header.to_lowercase();
        self.config
            .sensitive_headers
            .iter()
            .any(|h| h == &header_lower)
    }
}

impl Default for TracingMiddleware {
    fn default() -> Self {
        Self::new()
    }
}

impl Middleware for TracingMiddleware {
    fn handle(&self, request: ElifRequest, next: Next) -> NextFuture<'static> {
        let config = self.config.clone();
        Box::pin(async move {
            let start_time = Instant::now();
            let request_id = Uuid::new_v4();

            // Create tracing span for this request
            let span = match config.level {
                Level::ERROR => tracing::error_span!(
                    "http_request",
                    method = %request.method,
                    uri = %request.uri,
                    request_id = %request_id,
                    remote_addr = tracing::field::Empty,
                ),
                Level::WARN => tracing::warn_span!(
                    "http_request",
                    method = %request.method,
                    uri = %request.uri,
                    request_id = %request_id,
                    remote_addr = tracing::field::Empty,
                ),
                Level::INFO => tracing::info_span!(
                    "http_request",
                    method = %request.method,
                    uri = %request.uri,
                    request_id = %request_id,
                    remote_addr = tracing::field::Empty,
                ),
                Level::DEBUG => tracing::debug_span!(
                    "http_request",
                    method = %request.method,
                    uri = %request.uri,
                    request_id = %request_id,
                    remote_addr = tracing::field::Empty,
                ),
                Level::TRACE => tracing::trace_span!(
                    "http_request",
                    method = %request.method,
                    uri = %request.uri,
                    request_id = %request_id,
                    remote_addr = tracing::field::Empty,
                ),
            };

            // Enter the span for this request
            let _enter = span.enter();

            // Log request details based on level
            match config.level {
                Level::ERROR => error!(
                    "HTTP Request: {} {} (ID: {})",
                    request.method, request.uri, request_id
                ),
                Level::WARN => warn!(
                    "HTTP Request: {} {} (ID: {})",
                    request.method, request.uri, request_id
                ),
                Level::INFO => info!(
                    "HTTP Request: {} {} (ID: {})",
                    request.method, request.uri, request_id
                ),
                Level::DEBUG => {
                    let headers = {
                        let mut header_strings = Vec::new();

                        for name in request.headers.keys() {
                            let name_str = name.as_str();
                            if let Some(value) = request.headers.get_str(name_str) {
                                let value_str = if config.include_sensitive_headers {
                                    value.to_str().unwrap_or("[INVALID_UTF8]")
                                } else {
                                    let name_lower = name_str.to_lowercase();
                                    if config.sensitive_headers.iter().any(|h| h == &name_lower) {
                                        "[REDACTED]"
                                    } else {
                                        value.to_str().unwrap_or("[INVALID_UTF8]")
                                    }
                                };
                                header_strings.push(format!("{}={}", name_str, value_str));
                            }
                        }

                        header_strings.join(", ")
                    };
                    tracing::debug!(
                        "HTTP Request: {} {} (ID: {}) - Headers: {}",
                        request.method,
                        request.uri,
                        request_id,
                        headers
                    );
                }
                Level::TRACE => {
                    let headers = {
                        let mut header_strings = Vec::new();

                        for name in request.headers.keys() {
                            let name_str = name.as_str();
                            if let Some(value) = request.headers.get_str(name_str) {
                                let value_str = if config.include_sensitive_headers {
                                    value.to_str().unwrap_or("[INVALID_UTF8]")
                                } else {
                                    let name_lower = name_str.to_lowercase();
                                    if config.sensitive_headers.iter().any(|h| h == &name_lower) {
                                        "[REDACTED]"
                                    } else {
                                        value.to_str().unwrap_or("[INVALID_UTF8]")
                                    }
                                };
                                header_strings.push(format!("{}={}", name_str, value_str));
                            }
                        }

                        header_strings.join(", ")
                    };
                    tracing::trace!(
                        "HTTP Request: {} {} (ID: {}) - Headers: {} - Body tracing: {}",
                        request.method,
                        request.uri,
                        request_id,
                        headers,
                        config.trace_bodies
                    );
                }
            }

            // Continue to next middleware/handler
            let response = next.run(request).await;

            // Calculate duration and log response
            let duration = start_time.elapsed();
            let status = response.status_code();

            match config.level {
                Level::ERROR if status.is_server_error() => {
                    error!(
                        "HTTP Response: {:?} (Server Error) - Duration: {:?} (ID: {})",
                        status, duration, request_id
                    );
                }
                Level::WARN if status.is_client_error() => {
                    warn!(
                        "HTTP Response: {:?} (Client Error) - Duration: {:?} (ID: {})",
                        status, duration, request_id
                    );
                }
                Level::INFO => {
                    info!(
                        "HTTP Response: {:?} - Duration: {:?} (ID: {})",
                        status, duration, request_id
                    );
                }
                Level::DEBUG => {
                    let headers = {
                        let mut header_strings = Vec::new();

                        for (name, value) in response.headers().iter() {
                            let name_str = name.as_str();
                            let value_str = if config.include_sensitive_headers {
                                value.to_str().unwrap_or("[INVALID_UTF8]")
                            } else {
                                let name_lower = name_str.to_lowercase();
                                if config.sensitive_headers.iter().any(|h| h == &name_lower) {
                                    "[REDACTED]"
                                } else {
                                    value.to_str().unwrap_or("[INVALID_UTF8]")
                                }
                            };
                            header_strings.push(format!("{}={}", name_str, value_str));
                        }

                        header_strings.join(", ")
                    };
                    tracing::debug!(
                        "HTTP Response: {:?} - Duration: {:?} - Headers: {} (ID: {})",
                        status,
                        duration,
                        headers,
                        request_id
                    );
                }
                Level::TRACE => {
                    let headers = {
                        let mut header_strings = Vec::new();

                        for (name, value) in response.headers().iter() {
                            let name_str = name.as_str();
                            let value_str = if config.include_sensitive_headers {
                                value.to_str().unwrap_or("[INVALID_UTF8]")
                            } else {
                                let name_lower = name_str.to_lowercase();
                                if config.sensitive_headers.iter().any(|h| h == &name_lower) {
                                    "[REDACTED]"
                                } else {
                                    value.to_str().unwrap_or("[INVALID_UTF8]")
                                }
                            };
                            header_strings.push(format!("{}={}", name_str, value_str));
                        }

                        header_strings.join(", ")
                    };
                    tracing::trace!(
                        "HTTP Response: {:?} - Duration: {:?} - Headers: {} - Body tracing: {} (ID: {})",
                        status,
                        duration,
                        headers,
                        config.trace_response_bodies,
                        request_id
                    );
                }
                _ => {} // Skip logging for other combinations
            }

            response
        })
    }

    fn name(&self) -> &'static str {
        "TracingMiddleware"
    }
}

/// Request metadata for tracing context
#[derive(Debug, Clone)]
pub struct RequestMetadata {
    pub request_id: Uuid,
    pub start_time: Instant,
    pub span: Span,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::middleware::v2::MiddlewarePipelineV2;
    use crate::request::{ElifMethod, ElifRequest};
    use crate::response::{ElifHeaderMap, ElifResponse, ElifStatusCode};

    #[tokio::test]
    async fn test_tracing_middleware_v2() {
        let middleware = TracingMiddleware::new();
        let pipeline = MiddlewarePipelineV2::new().add(middleware);

        let mut headers = ElifHeaderMap::new();
        headers.insert(
            "content-type".parse().unwrap(),
            "application/json".parse().unwrap(),
        );
        headers.insert(
            "authorization".parse().unwrap(),
            "Bearer secret".parse().unwrap(),
        );

        let request = ElifRequest::new(ElifMethod::GET, "/test".parse().unwrap(), headers);

        let response = pipeline
            .execute(request, |_req| {
                Box::pin(async move { ElifResponse::ok().text("Success") })
            })
            .await;

        assert_eq!(response.status_code(), ElifStatusCode::OK);
    }

    #[tokio::test]
    async fn test_tracing_config_customization() {
        let config = TracingConfig::default()
            .with_body_tracing()
            .with_level(Level::DEBUG)
            .with_max_body_size(2048)
            .add_sensitive_header("x-custom-secret".to_string());

        let middleware = TracingMiddleware::with_config(config);
        assert!(middleware.config.trace_bodies);
        assert_eq!(middleware.config.level, Level::DEBUG);
        assert_eq!(middleware.config.max_body_size, 2048);
        assert!(middleware
            .config
            .sensitive_headers
            .contains(&"x-custom-secret".to_string()));
    }

    #[tokio::test]
    async fn test_sensitive_header_detection() {
        let middleware = TracingMiddleware::new();

        assert!(middleware.is_sensitive_header("Authorization"));
        assert!(middleware.is_sensitive_header("COOKIE"));
        assert!(middleware.is_sensitive_header("x-api-key"));
        assert!(!middleware.is_sensitive_header("content-type"));
        assert!(!middleware.is_sensitive_header("accept"));
    }

    #[tokio::test]
    async fn test_tracing_middleware_name() {
        let middleware = TracingMiddleware::new();
        assert_eq!(middleware.name(), "TracingMiddleware");
    }
}