litellm-rs 0.4.16

A high-performance AI Gateway written in Rust, providing OpenAI-compatible APIs with intelligent routing, load balancing, and enterprise features
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
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
//! OAuth middleware for protecting routes and extracting user information

use super::session::{OAuthSession, SessionStore};
use super::types::UserInfo;
use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform, forward_ready};
use actix_web::{Error, HttpMessage, HttpRequest, web};
use futures::future::{Ready, ok};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use tracing::{debug, warn};

/// OAuth middleware for protecting routes
///
/// This middleware validates OAuth sessions and extracts user information
/// from incoming requests. It can be configured to:
/// - Require authentication (reject unauthenticated requests)
/// - Allow anonymous access (pass through if no session)
/// - Apply role-based access control
#[derive(Clone)]
pub struct OAuthMiddleware {
    /// Session store for validating sessions
    session_store: Arc<dyn SessionStore>,

    /// Whether authentication is required
    require_auth: bool,

    /// Required roles (empty means any authenticated user)
    required_roles: Vec<String>,

    /// Routes to exclude from authentication
    exclude_paths: Vec<String>,
}

impl OAuthMiddleware {
    /// Create a new OAuth middleware that requires authentication
    pub fn new(session_store: Arc<dyn SessionStore>) -> Self {
        Self {
            session_store,
            require_auth: true,
            required_roles: Vec::new(),
            exclude_paths: Vec::new(),
        }
    }

    /// Create middleware that allows anonymous access
    pub fn optional(session_store: Arc<dyn SessionStore>) -> Self {
        Self {
            session_store,
            require_auth: false,
            required_roles: Vec::new(),
            exclude_paths: Vec::new(),
        }
    }

    /// Require specific roles
    pub fn with_roles(mut self, roles: Vec<String>) -> Self {
        self.required_roles = roles;
        self
    }

    /// Add a role requirement
    pub fn require_role(mut self, role: impl Into<String>) -> Self {
        self.required_roles.push(role.into());
        self
    }

    /// Exclude paths from authentication
    pub fn exclude_paths(mut self, paths: Vec<String>) -> Self {
        self.exclude_paths = paths;
        self
    }

    /// Add a path to exclude
    pub fn exclude_path(mut self, path: impl Into<String>) -> Self {
        self.exclude_paths.push(path.into());
        self
    }

    /// Check if a path should be excluded from authentication
    fn is_excluded(&self, path: &str) -> bool {
        self.exclude_paths.iter().any(|p| {
            if p.ends_with('*') {
                path.starts_with(p.trim_end_matches('*'))
            } else {
                path == p
            }
        })
    }
}

impl std::fmt::Debug for OAuthMiddleware {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OAuthMiddleware")
            .field("require_auth", &self.require_auth)
            .field("required_roles", &self.required_roles)
            .field("exclude_paths", &self.exclude_paths)
            .finish()
    }
}

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

    fn new_transform(&self, service: S) -> Self::Future {
        ok(OAuthMiddlewareService {
            service,
            session_store: self.session_store.clone(),
            require_auth: self.require_auth,
            required_roles: self.required_roles.clone(),
            exclude_paths: self.exclude_paths.clone(),
        })
    }
}

/// Service implementation for OAuth middleware
pub struct OAuthMiddlewareService<S> {
    service: S,
    session_store: Arc<dyn SessionStore>,
    require_auth: bool,
    required_roles: Vec<String>,
    exclude_paths: Vec<String>,
}

impl<S> OAuthMiddlewareService<S> {
    fn is_excluded(&self, path: &str) -> bool {
        self.exclude_paths.iter().any(|p| {
            if p.ends_with('*') {
                path.starts_with(p.trim_end_matches('*'))
            } else {
                path == p
            }
        })
    }
}

impl<S, B> Service<ServiceRequest> for OAuthMiddlewareService<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = 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();

        // Check if path is excluded
        if self.is_excluded(&path) {
            return Box::pin(self.service.call(req));
        }

        // Extract session ID from request
        let session_id = extract_session_id(&req);

        let session_store = self.session_store.clone();
        let require_auth = self.require_auth;
        let required_roles = self.required_roles.clone();
        let fut = self.service.call(req);

        Box::pin(async move {
            match session_id {
                Some(sid) => {
                    // Validate session
                    match session_store.get(&sid).await {
                        Ok(Some(session)) => {
                            // Check role requirements
                            if !required_roles.is_empty() {
                                let has_role = session
                                    .role
                                    .as_ref()
                                    .map(|r| required_roles.contains(r))
                                    .unwrap_or(false);

                                if !has_role {
                                    warn!(
                                        "User {} lacks required role for path {}",
                                        session.user_info.email, path
                                    );
                                    return Err(actix_web::error::ErrorForbidden(
                                        "Insufficient permissions",
                                    ));
                                }
                            }

                            debug!(
                                "OAuth session validated for user: {}",
                                session.user_info.email
                            );

                            // Session is valid, proceed with request
                            fut.await
                        }
                        Ok(None) => {
                            if require_auth {
                                warn!("Invalid or expired session: {}", sid);
                                Err(actix_web::error::ErrorUnauthorized("Invalid session"))
                            } else {
                                fut.await
                            }
                        }
                        Err(e) => {
                            warn!("Session lookup error: {:?}", e);
                            if require_auth {
                                Err(actix_web::error::ErrorInternalServerError(
                                    "Session validation failed",
                                ))
                            } else {
                                fut.await
                            }
                        }
                    }
                }
                None => {
                    if require_auth {
                        debug!("No session provided for protected route: {}", path);
                        Err(actix_web::error::ErrorUnauthorized(
                            "Authentication required",
                        ))
                    } else {
                        fut.await
                    }
                }
            }
        })
    }
}

/// Extract session ID from request headers
fn extract_session_id(req: &ServiceRequest) -> Option<String> {
    // Try X-Session-ID header first
    if let Some(sid) = req
        .headers()
        .get("X-Session-ID")
        .and_then(|h| h.to_str().ok())
    {
        return Some(sid.to_string());
    }

    // Try Authorization header with Bearer token
    if let Some(auth) = req
        .headers()
        .get("Authorization")
        .and_then(|h| h.to_str().ok())
        && let Some(token) = auth.strip_prefix("Bearer ")
    {
        return Some(token.to_string());
    }

    // Try cookie
    if let Some(cookie) = req.cookie("session_id") {
        return Some(cookie.value().to_string());
    }

    None
}

/// Extension trait for extracting OAuth user from request
pub trait OAuthUserExt {
    /// Get the authenticated OAuth user, if any
    fn oauth_user(&self) -> Option<UserInfo>;

    /// Get the OAuth session, if any
    fn oauth_session(&self) -> Option<OAuthSession>;
}

impl OAuthUserExt for HttpRequest {
    fn oauth_user(&self) -> Option<UserInfo> {
        self.extensions().get::<UserInfo>().cloned()
    }

    fn oauth_session(&self) -> Option<OAuthSession> {
        self.extensions().get::<OAuthSession>().cloned()
    }
}

/// Request guard for requiring OAuth authentication
pub struct OAuthUser(pub UserInfo);

impl OAuthUser {
    /// Get the user info
    pub fn user(&self) -> &UserInfo {
        &self.0
    }

    /// Get the user ID
    pub fn id(&self) -> &str {
        &self.0.id
    }

    /// Get the user email
    pub fn email(&self) -> &str {
        &self.0.email
    }

    /// Get the provider
    pub fn provider(&self) -> &str {
        &self.0.provider
    }
}

impl std::ops::Deref for OAuthUser {
    type Target = UserInfo;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// Extractor for OAuth user from request
impl actix_web::FromRequest for OAuthUser {
    type Error = actix_web::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self, Self::Error>>>>;

    fn from_request(req: &HttpRequest, _payload: &mut actix_web::dev::Payload) -> Self::Future {
        let session_id = req
            .headers()
            .get("X-Session-ID")
            .and_then(|h| h.to_str().ok())
            .map(String::from)
            .or_else(|| {
                req.headers()
                    .get("Authorization")
                    .and_then(|h| h.to_str().ok())
                    .and_then(|h| h.strip_prefix("Bearer "))
                    .map(String::from)
            })
            .or_else(|| req.cookie("session_id").map(|c| c.value().to_string()));

        let oauth_state = req
            .app_data::<web::Data<super::handlers::OAuthState>>()
            .cloned();

        Box::pin(async move {
            let session_id =
                session_id.ok_or_else(|| actix_web::error::ErrorUnauthorized("Missing session"))?;

            let oauth = oauth_state.ok_or_else(|| {
                actix_web::error::ErrorInternalServerError("OAuth not configured")
            })?;

            let session = oauth
                .session_store
                .get(&session_id)
                .await
                .map_err(|e| {
                    actix_web::error::ErrorInternalServerError(format!(
                        "Session lookup failed: {:?}",
                        e
                    ))
                })?
                .ok_or_else(|| actix_web::error::ErrorUnauthorized("Invalid session"))?;

            Ok(OAuthUser(session.user_info))
        })
    }
}

/// Extractor for optional OAuth user
pub struct OptionalOAuthUser(pub Option<UserInfo>);

impl OptionalOAuthUser {
    /// Get the user info if present
    pub fn user(&self) -> Option<&UserInfo> {
        self.0.as_ref()
    }

    /// Check if user is authenticated
    pub fn is_authenticated(&self) -> bool {
        self.0.is_some()
    }
}

impl std::ops::Deref for OptionalOAuthUser {
    type Target = Option<UserInfo>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl actix_web::FromRequest for OptionalOAuthUser {
    type Error = actix_web::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self, Self::Error>>>>;

    fn from_request(req: &HttpRequest, _payload: &mut actix_web::dev::Payload) -> Self::Future {
        let session_id = req
            .headers()
            .get("X-Session-ID")
            .and_then(|h| h.to_str().ok())
            .map(String::from)
            .or_else(|| {
                req.headers()
                    .get("Authorization")
                    .and_then(|h| h.to_str().ok())
                    .and_then(|h| h.strip_prefix("Bearer "))
                    .map(String::from)
            })
            .or_else(|| req.cookie("session_id").map(|c| c.value().to_string()));

        let oauth_state = req
            .app_data::<web::Data<super::handlers::OAuthState>>()
            .cloned();

        Box::pin(async move {
            let Some(session_id) = session_id else {
                return Ok(OptionalOAuthUser(None));
            };

            let Some(oauth) = oauth_state else {
                return Ok(OptionalOAuthUser(None));
            };

            match oauth.session_store.get(&session_id).await {
                Ok(Some(session)) => Ok(OptionalOAuthUser(Some(session.user_info))),
                Ok(None) => Ok(OptionalOAuthUser(None)),
                Err(_) => Ok(OptionalOAuthUser(None)),
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::auth::oauth::session::InMemorySessionStore;

    #[test]
    fn test_middleware_creation() {
        let store = Arc::new(InMemorySessionStore::new());
        let middleware = OAuthMiddleware::new(store.clone());

        assert!(middleware.require_auth);
        assert!(middleware.required_roles.is_empty());
        assert!(middleware.exclude_paths.is_empty());
    }

    #[test]
    fn test_middleware_optional() {
        let store = Arc::new(InMemorySessionStore::new());
        let middleware = OAuthMiddleware::optional(store);

        assert!(!middleware.require_auth);
    }

    #[test]
    fn test_middleware_with_roles() {
        let store = Arc::new(InMemorySessionStore::new());
        let middleware = OAuthMiddleware::new(store)
            .require_role("admin")
            .require_role("superuser");

        assert_eq!(middleware.required_roles.len(), 2);
        assert!(middleware.required_roles.contains(&"admin".to_string()));
    }

    #[test]
    fn test_middleware_exclude_paths() {
        let store = Arc::new(InMemorySessionStore::new());
        let middleware = OAuthMiddleware::new(store)
            .exclude_path("/health")
            .exclude_path("/public/*");

        assert!(middleware.is_excluded("/health"));
        assert!(middleware.is_excluded("/public/page"));
        assert!(middleware.is_excluded("/public/nested/page"));
        assert!(!middleware.is_excluded("/api/private"));
    }

    #[test]
    fn test_middleware_debug() {
        let store = Arc::new(InMemorySessionStore::new());
        let middleware = OAuthMiddleware::new(store)
            .require_role("admin")
            .exclude_path("/health");

        let debug_str = format!("{:?}", middleware);
        assert!(debug_str.contains("OAuthMiddleware"));
        assert!(debug_str.contains("require_auth"));
        assert!(debug_str.contains("admin"));
    }

    #[test]
    fn test_oauth_user_extractor() {
        let user = OAuthUser(UserInfo::new("123", "test@example.com", "google"));

        assert_eq!(user.id(), "123");
        assert_eq!(user.email(), "test@example.com");
        assert_eq!(user.provider(), "google");
    }

    #[test]
    fn test_optional_oauth_user() {
        let with_user = OptionalOAuthUser(Some(UserInfo::new("123", "test@example.com", "google")));
        let without_user = OptionalOAuthUser(None);

        assert!(with_user.is_authenticated());
        assert!(with_user.user().is_some());

        assert!(!without_user.is_authenticated());
        assert!(without_user.user().is_none());
    }

    #[test]
    fn test_oauth_user_deref() {
        let user = OAuthUser(UserInfo::new("123", "test@example.com", "google"));

        // Should be able to access UserInfo fields through deref
        assert_eq!(user.email, "test@example.com");
        assert_eq!(user.provider, "google");
    }
}