litellm-rs 0.1.1

A high-performance AI Gateway written in Rust, providing OpenAI-compatible APIs with intelligent routing, load balancing, and enterprise features
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
//! HTTP middleware implementations
//!
//! This module provides various middleware for request processing.

#![allow(dead_code)]

use crate::auth::AuthMethod;
use crate::core::models::RequestContext;
use crate::server::AppState;
use actix_web::HttpMessage;
use std::sync::Arc;

use actix_web::dev::{Service, Transform, forward_ready};
use actix_web::{
    HttpRequest,
    dev::{ServiceRequest, ServiceResponse},
    http::header::HeaderValue,
    web,
};
use futures::future::{Ready, ready};
use std::future::Future;
use std::pin::Pin;

use std::time::Instant;
use tracing::{debug, info, warn};
use uuid::Uuid;

/// Request ID middleware for Actix-web
pub struct RequestIdMiddleware;

impl<S, B> Transform<S, ServiceRequest> for RequestIdMiddleware
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = actix_web::Error;
    type InitError = ();
    type Transform = RequestIdMiddlewareService<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(RequestIdMiddlewareService { service }))
    }
}

/// Service implementation for request ID middleware
pub struct RequestIdMiddlewareService<S> {
    service: S,
}

impl<S, B> Service<ServiceRequest> for RequestIdMiddlewareService<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = actix_web::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;

    forward_ready!(service);

    fn call(&self, mut req: ServiceRequest) -> Self::Future {
        let request_id = Uuid::new_v4().to_string();

        // Add request ID to headers
        req.headers_mut().insert(
            actix_web::http::header::HeaderName::from_static("x-request-id"),
            HeaderValue::from_str(&request_id)
                .unwrap_or_else(|_| HeaderValue::from_static("invalid")),
        );

        debug!("Processing request: {}", request_id);

        let fut = self.service.call(req);
        Box::pin(async move {
            let res = fut.await?;
            Ok(res)
        })
    }
}

/// Authentication middleware for Actix-web
pub struct AuthMiddleware;

impl<S, B> Transform<S, ServiceRequest> for AuthMiddleware
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = actix_web::Error;
    type InitError = ();
    type Transform = AuthMiddlewareService<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(AuthMiddlewareService { service }))
    }
}

/// Service implementation for authentication middleware
pub struct AuthMiddlewareService<S> {
    service: S,
}

impl<S, B> Service<ServiceRequest> for AuthMiddlewareService<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = actix_web::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;

    forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        let _start_time = Instant::now();
        let path = req.path().to_string();
        let _method = req.method().clone();

        // Skip authentication for public routes
        if is_public_route(&path) {
            debug!("Skipping authentication for public route: {}", path);
            let fut = self.service.call(req);
            return Box::pin(async move {
                let res = fut.await?;
                Ok(res)
            });
        }

        // Get app state
        let state = req.app_data::<web::Data<AppState>>().cloned();
        if state.is_none() {
            return Box::pin(async move {
                Err(actix_web::error::ErrorInternalServerError(
                    "App state not found",
                ))
            });
        }
        let state = state.unwrap();

        // Create request context
        let mut context = RequestContext::new();
        context.client_ip = req.connection_info().peer_addr().map(|s| s.to_string());
        context.user_agent = req
            .headers()
            .get("user-agent")
            .and_then(|h| h.to_str().ok())
            .map(|s| s.to_string());

        // Extract authentication method
        let auth_method = extract_auth_method(req.headers());

        let fut = self.service.call(req);
        Box::pin(async move {
            // Authenticate request
            match state.auth.authenticate(auth_method, context).await {
                Ok(auth_result) => {
                    if auth_result.success {
                        debug!("Authentication successful for {}", path);
                        let res = fut.await?;
                        Ok(res)
                    } else {
                        warn!(
                            "Authentication failed for {}: {:?}",
                            path, auth_result.error
                        );
                        Err(actix_web::error::ErrorUnauthorized("Authentication failed"))
                    }
                }
                Err(e) => {
                    warn!("Authentication error for {}: {}", path, e);
                    Err(actix_web::error::ErrorInternalServerError(
                        "Authentication error",
                    ))
                }
            }
        })
    }
}

/// Extract request context from HTTP request (helper function)
pub fn get_request_context(req: &HttpRequest) -> Result<RequestContext, actix_web::Error> {
    let mut context = RequestContext::new();

    // Extract client IP
    context.client_ip = req.connection_info().peer_addr().map(|s| s.to_string());

    // Extract user agent
    context.user_agent = req
        .headers()
        .get("user-agent")
        .and_then(|h| h.to_str().ok())
        .map(|s| s.to_string());

    Ok(context)
}

/// Rate limiting middleware for Actix-web
pub struct RateLimitMiddleware;

impl<S, B> Transform<S, ServiceRequest> for RateLimitMiddleware
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = actix_web::Error;
    type InitError = ();
    type Transform = RateLimitMiddlewareService<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(RateLimitMiddlewareService { service }))
    }
}

/// Service implementation for rate limiting middleware
pub struct RateLimitMiddlewareService<S> {
    service: S,
}

impl<S, B> Service<ServiceRequest> for RateLimitMiddlewareService<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = actix_web::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;

    forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        let path = req.path().to_string();
        let client_ip = req
            .connection_info()
            .peer_addr()
            .unwrap_or("unknown")
            .to_string();

        // Skip rate limiting for health checks
        if path == "/health" || path == "/metrics" {
            let fut = self.service.call(req);
            return Box::pin(async move {
                let res = fut.await?;
                Ok(res)
            });
        }

        // TODO: Implement rate limiting logic
        // For now, just pass through
        debug!("Rate limiting check for {} from {}", path, client_ip);

        let fut = self.service.call(req);
        Box::pin(async move {
            let res = fut.await?;
            Ok(res)
        })
    }
}

/// Metrics collection middleware for Actix-web
pub struct MetricsMiddleware;

impl<S, B> Transform<S, ServiceRequest> for MetricsMiddleware
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = actix_web::Error;
    type InitError = ();
    type Transform = MetricsMiddlewareService<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(MetricsMiddlewareService { service }))
    }
}

/// Service implementation for metrics middleware
pub struct MetricsMiddlewareService<S> {
    service: S,
}

impl<S, B> Service<ServiceRequest> for MetricsMiddlewareService<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = actix_web::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;

    forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        let start_time = Instant::now();
        let method = req.method().clone();
        let path = req.path().to_string();
        let user_agent = req
            .headers()
            .get("user-agent")
            .and_then(|h| h.to_str().ok())
            .map(|s| s.to_string());
        let client_ip = req
            .connection_info()
            .peer_addr()
            .unwrap_or("unknown")
            .to_string();

        // Get request ID from headers
        let request_id = req
            .headers()
            .get("x-request-id")
            .and_then(|h| h.to_str().ok())
            .unwrap_or("unknown")
            .to_string();

        // Extract monitoring system before moving req
        let monitoring = req
            .extensions()
            .get::<Arc<crate::monitoring::MonitoringSystem>>()
            .cloned();

        let fut = self.service.call(req);
        Box::pin(async move {
            let res = fut.await?;

            // Calculate response time
            let response_time = start_time.elapsed();
            let status_code = res.status().as_u16();

            // Log request metrics
            info!(
                request_id = %request_id,
                method = %method,
                path = %path,
                status = status_code,
                duration_ms = response_time.as_millis(),
                client_ip = %client_ip,
                user_agent = ?user_agent,
                "Request completed"
            );

            // Send metrics to monitoring system
            if let Some(monitoring_system) = monitoring {
                let request_metrics = crate::server::RequestMetrics {
                    request_id: request_id.clone(),
                    method: method.to_string(),
                    path: path.clone(),
                    status_code: status_code,
                    response_time_ms: response_time.as_millis() as u64,
                    request_size: 0,  // Would need to capture from request body
                    response_size: 0, // Would need to capture from response body
                    user_agent: user_agent.clone(),
                    client_ip: Some(client_ip.clone()),
                    user_id: None,    // Would be extracted from auth context
                    api_key_id: None, // Would be extracted from auth context
                };

                // Send metrics asynchronously
                let monitoring_clone = monitoring_system.clone();
                let metrics_clone = request_metrics.clone();
                tokio::spawn(async move {
                    if let Err(e) = monitoring_clone
                        .record_request(
                            &metrics_clone.method,
                            &metrics_clone.path,
                            metrics_clone.status_code,
                            response_time,
                            metrics_clone.user_id,
                            metrics_clone.api_key_id,
                        )
                        .await
                    {
                        warn!("Failed to record request metrics: {}", e);
                    }
                });
            }

            Ok(res)
        })
    }
}

/// CORS middleware for Actix-web (handled by actix-cors, but we can add custom logic here)
pub struct CorsMiddleware;

impl<S, B> Transform<S, ServiceRequest> for CorsMiddleware
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = actix_web::Error;
    type InitError = ();
    type Transform = CorsMiddlewareService<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(CorsMiddlewareService { service }))
    }
}

/// Service implementation for CORS middleware
pub struct CorsMiddlewareService<S> {
    service: S,
}

impl<S, B> Service<ServiceRequest> for CorsMiddlewareService<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = actix_web::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;

    forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        // Custom CORS logic can be added here if needed
        // For now, rely on actix-cors middleware
        let fut = self.service.call(req);
        Box::pin(async move {
            let res = fut.await?;
            Ok(res)
        })
    }
}

/// Security headers middleware for Actix-web
pub struct SecurityHeadersMiddleware;

impl<S, B> Transform<S, ServiceRequest> for SecurityHeadersMiddleware
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = actix_web::Error;
    type InitError = ();
    type Transform = SecurityHeadersMiddlewareService<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(SecurityHeadersMiddlewareService { service }))
    }
}

/// Service implementation for security headers middleware
pub struct SecurityHeadersMiddlewareService<S> {
    service: S,
}

impl<S, B> Service<ServiceRequest> for SecurityHeadersMiddlewareService<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = actix_web::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;

    forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        let fut = self.service.call(req);
        Box::pin(async move {
            let mut res = fut.await?;

            // Add security headers
            let headers = res.headers_mut();

            headers.insert(
                actix_web::http::header::HeaderName::from_static("x-content-type-options"),
                HeaderValue::from_static("nosniff"),
            );
            headers.insert(
                actix_web::http::header::HeaderName::from_static("x-frame-options"),
                HeaderValue::from_static("DENY"),
            );
            headers.insert(
                actix_web::http::header::HeaderName::from_static("x-xss-protection"),
                HeaderValue::from_static("1; mode=block"),
            );
            headers.insert(
                actix_web::http::header::HeaderName::from_static("strict-transport-security"),
                HeaderValue::from_static("max-age=31536000; includeSubDomains"),
            );
            headers.insert(
                actix_web::http::header::HeaderName::from_static("referrer-policy"),
                HeaderValue::from_static("strict-origin-when-cross-origin"),
            );

            Ok(res)
        })
    }
}

// TODO: Implement additional middleware as needed for actix-web

/// Extract authentication method from headers
fn extract_auth_method(headers: &actix_web::http::header::HeaderMap) -> AuthMethod {
    // Check Authorization header
    if let Some(auth_header) = headers.get("authorization") {
        if let Ok(auth_str) = auth_header.to_str() {
            if let Some(stripped) = auth_str.strip_prefix("Bearer ") {
                let token = stripped.to_string();
                return AuthMethod::Jwt(token);
            } else if let Some(stripped) = auth_str.strip_prefix("ApiKey ") {
                let key = stripped.to_string();
                return AuthMethod::ApiKey(key);
            } else if auth_str.starts_with("gw-") {
                // Direct API key
                return AuthMethod::ApiKey(auth_str.to_string());
            }
        }
    }

    // Check X-API-Key header
    if let Some(api_key_header) = headers.get("x-api-key") {
        if let Ok(key) = api_key_header.to_str() {
            return AuthMethod::ApiKey(key.to_string());
        }
    }

    // Check session cookie
    if let Some(cookie_header) = headers.get("cookie") {
        if let Ok(cookie_str) = cookie_header.to_str() {
            for cookie in cookie_str.split(';') {
                let cookie = cookie.trim();
                if let Some(stripped) = cookie.strip_prefix("session=") {
                    let session_id = stripped.to_string();
                    return AuthMethod::Session(session_id);
                }
            }
        }
    }

    AuthMethod::None
}

/// Check if a route is public (doesn't require authentication)
fn is_public_route(path: &str) -> bool {
    const PUBLIC_ROUTES: &[&str] = &[
        "/health",
        "/metrics",
        "/auth/login",
        "/auth/register",
        "/auth/forgot-password",
        "/auth/reset-password",
        "/auth/verify-email",
        "/docs",
        "/openapi.json",
    ];

    PUBLIC_ROUTES.iter().any(|&route| path.starts_with(route))
}

/// Check if a route requires admin privileges
fn is_admin_route(path: &str) -> bool {
    const ADMIN_ROUTES: &[&str] = &["/admin", "/api/admin"];

    ADMIN_ROUTES.iter().any(|&route| path.starts_with(route))
}

/// Check if a route is for API access
fn is_api_route(path: &str) -> bool {
    const API_ROUTES: &[&str] = &[
        "/v1/chat/completions",
        "/v1/completions",
        "/v1/embeddings",
        "/v1/images",
        "/v1/audio",
        "/v1/models",
    ];

    API_ROUTES.iter().any(|&route| path.starts_with(route))
}

#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::http::header::{HeaderMap, HeaderName, HeaderValue};

    #[test]
    fn test_extract_auth_method_bearer() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("authorization"),
            HeaderValue::from_static("Bearer token123"),
        );

        let auth_method = extract_auth_method(&headers);
        assert!(matches!(auth_method, AuthMethod::Jwt(token) if token == "token123"));
    }

    #[test]
    fn test_extract_auth_method_api_key() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("authorization"),
            HeaderValue::from_static("ApiKey key123"),
        );

        let auth_method = extract_auth_method(&headers);
        assert!(matches!(auth_method, AuthMethod::ApiKey(key) if key == "key123"));
    }

    #[test]
    fn test_extract_auth_method_x_api_key() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("x-api-key"),
            HeaderValue::from_static("key123"),
        );

        let auth_method = extract_auth_method(&headers);
        assert!(matches!(auth_method, AuthMethod::ApiKey(key) if key == "key123"));
    }

    #[test]
    fn test_extract_auth_method_session() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("cookie"),
            HeaderValue::from_static("session=sess123; other=value"),
        );

        let auth_method = extract_auth_method(&headers);
        assert!(matches!(auth_method, AuthMethod::Session(session) if session == "sess123"));
    }

    #[test]
    fn test_extract_auth_method_none() {
        let headers = HeaderMap::new();
        let auth_method = extract_auth_method(&headers);
        assert!(matches!(auth_method, AuthMethod::None));
    }

    #[test]
    fn test_is_public_route() {
        assert!(is_public_route("/health"));
        assert!(is_public_route("/auth/login"));
        assert!(is_public_route("/metrics"));
        assert!(!is_public_route("/api/users"));
        assert!(!is_public_route("/v1/chat/completions"));
    }

    #[test]
    fn test_is_admin_route() {
        assert!(is_admin_route("/admin/users"));
        assert!(is_admin_route("/api/admin/config"));
        assert!(!is_admin_route("/api/users"));
        assert!(!is_admin_route("/health"));
    }

    #[test]
    fn test_is_api_route() {
        assert!(is_api_route("/v1/chat/completions"));
        assert!(is_api_route("/v1/embeddings"));
        assert!(is_api_route("/v1/models"));
        assert!(!is_api_route("/api/users"));
        assert!(!is_api_route("/health"));
    }
}