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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
//! Authentication endpoints
//!
//! This module provides authentication-related API endpoints.

#![allow(dead_code)]

use crate::auth::jwt::TokenPair;
use crate::core::models::User;
use crate::server::AppState;
use crate::server::routes::ApiResponse;
use crate::utils::validation::DataValidator;
use actix_web::http::header::HeaderMap;
use actix_web::{HttpRequest, HttpResponse, Result as ActixResult, web};
use serde::{Deserialize, Serialize};
use tracing::{debug, error, info, warn};

/// Configure authentication routes
pub fn configure_routes(cfg: &mut web::ServiceConfig) {
    cfg.service(
        web::scope("/auth")
            .route("/register", web::post().to(register))
            .route("/login", web::post().to(login))
            .route("/logout", web::post().to(logout))
            .route("/refresh", web::post().to(refresh_token))
            .route("/forgot-password", web::post().to(forgot_password))
            .route("/reset-password", web::post().to(reset_password))
            .route("/verify-email", web::post().to(verify_email))
            .route("/change-password", web::post().to(change_password))
            .route("/me", web::post().to(get_current_user)),
    );
}

/// User registration request
#[derive(Debug, Deserialize)]
struct RegisterRequest {
    username: String,
    email: String,
    password: String,
    full_name: Option<String>,
}

/// User login request
#[derive(Debug, Deserialize)]
struct LoginRequest {
    username: String,
    password: String,
}

/// Password change request
#[derive(Debug, Deserialize)]
struct ChangePasswordRequest {
    current_password: String,
    new_password: String,
}

/// Forgot password request
#[derive(Debug, Deserialize)]
struct ForgotPasswordRequest {
    email: String,
}

/// Reset password request
#[derive(Debug, Deserialize)]
struct ResetPasswordRequest {
    token: String,
    new_password: String,
}

/// Email verification request
#[derive(Debug, Deserialize)]
struct VerifyEmailRequest {
    token: String,
}

/// Refresh token request
#[derive(Debug, Deserialize)]
struct RefreshTokenRequest {
    refresh_token: String,
}

/// Authentication response
#[derive(Debug, Serialize)]
struct AuthResponse {
    user: UserResponse,
    tokens: TokenPair,
}

/// User response (without sensitive data)
#[derive(Debug, Serialize)]
struct UserResponse {
    id: uuid::Uuid,
    username: String,
    email: String,
    display_name: Option<String>,
    role: String,
    email_verified: bool,
    created_at: chrono::DateTime<chrono::Utc>,
}

/// Registration response
#[derive(Debug, Serialize)]
struct RegisterResponse {
    user_id: uuid::Uuid,
    username: String,
    email: String,
    message: String,
}

/// Login response
#[derive(Debug, Serialize)]
struct LoginResponse {
    access_token: String,
    refresh_token: String,
    token_type: String,
    expires_in: u64,
    user: UserInfo,
}

/// User info for login response
#[derive(Debug, Serialize)]
struct UserInfo {
    id: uuid::Uuid,
    username: String,
    email: String,
    full_name: Option<String>,
    role: String,
    email_verified: bool,
}

/// Refresh token response
#[derive(Debug, Serialize)]
struct RefreshTokenResponse {
    access_token: String,
    token_type: String,
    expires_in: u64,
}

impl From<User> for UserResponse {
    fn from(user: User) -> Self {
        Self {
            id: user.id(),
            username: user.username.clone(),
            email: user.email.clone(),
            display_name: user.display_name.clone(),
            role: format!("{:?}", user.role),
            email_verified: user.email_verified,
            created_at: user.metadata.created_at,
        }
    }
}

/// User registration endpoint
async fn register(
    state: web::Data<AppState>,
    request: web::Json<RegisterRequest>,
) -> ActixResult<HttpResponse> {
    info!("User registration attempt: {}", request.username);

    // Validate input
    if let Err(e) = DataValidator::validate_username(&request.username) {
        return Ok(
            HttpResponse::BadRequest().json(ApiResponse::<()>::error_for_type(e.to_string()))
        );
    }

    if let Err(e) = crate::utils::config::ConfigValidator::validate_email(&request.email) {
        return Ok(
            HttpResponse::BadRequest().json(ApiResponse::<()>::error_for_type(e.to_string()))
        );
    }

    if let Err(e) = DataValidator::validate_password(&request.password) {
        return Ok(
            HttpResponse::BadRequest().json(ApiResponse::<()>::error_for_type(e.to_string()))
        );
    }

    // Check if user already exists
    match state
        .storage
        .database
        .find_user_by_username(&request.username)
        .await
    {
        Ok(Some(_)) => {
            return Ok(HttpResponse::BadRequest().json(ApiResponse::<()>::error(
                "Username already exists".to_string(),
            )));
        }
        Ok(None) => {} // Continue with registration
        Err(e) => {
            error!("Failed to check existing user: {}", e);
            return Ok(HttpResponse::InternalServerError()
                .json(ApiResponse::<()>::error("Database error".to_string())));
        }
    }

    // Check if email already exists
    match state
        .storage
        .database
        .find_user_by_email(&request.email)
        .await
    {
        Ok(Some(_)) => {
            return Ok(HttpResponse::BadRequest()
                .json(ApiResponse::<()>::error("Email already exists".to_string())));
        }
        Ok(None) => {} // Continue with registration
        Err(e) => {
            error!("Failed to check existing email: {}", e);
            return Ok(HttpResponse::InternalServerError()
                .json(ApiResponse::<()>::error("Database error".to_string())));
        }
    }

    // Hash password
    let password_hash = match crate::utils::crypto::hash_password(&request.password) {
        Ok(hash) => hash,
        Err(e) => {
            error!("Failed to hash password: {}", e);
            return Ok(
                HttpResponse::InternalServerError().json(ApiResponse::<()>::error(
                    "Password hashing failed".to_string(),
                )),
            );
        }
    };

    // Create user
    let user = crate::core::models::user::User::new(
        request.username.clone(),
        request.email.clone(),
        password_hash,
    );

    // Store user in database
    match state.storage.database.create_user(&user).await {
        Ok(created_user) => {
            info!("User registered successfully: {}", created_user.username);

            let response = RegisterResponse {
                user_id: created_user.id(),
                username: created_user.username,
                email: created_user.email,
                message: "Registration successful. Please verify your email.".to_string(),
            };

            Ok(HttpResponse::Created().json(ApiResponse::success(response)))
        }
        Err(e) => {
            error!("Failed to create user: {}", e);
            Ok(HttpResponse::InternalServerError()
                .json(ApiResponse::<()>::error("User creation failed".to_string())))
        }
    }
}

/// User login endpoint
async fn login(
    state: web::Data<AppState>,
    request: web::Json<LoginRequest>,
) -> ActixResult<HttpResponse> {
    info!("User login attempt: {}", request.username);

    // Find user by username
    let user = match state
        .storage
        .database
        .find_user_by_username(&request.username)
        .await
    {
        Ok(Some(user)) => user,
        Ok(None) => {
            warn!("Login attempt with invalid username: {}", request.username);
            return Ok(HttpResponse::Unauthorized()
                .json(ApiResponse::<()>::error("Invalid credentials".to_string())));
        }
        Err(e) => {
            error!("Database error during login: {}", e);
            return Ok(HttpResponse::InternalServerError()
                .json(ApiResponse::<()>::error("Database error".to_string())));
        }
    };

    // Check if user is active
    if !user.is_active() {
        warn!("Login attempt for inactive user: {}", request.username);
        return Ok(HttpResponse::Forbidden()
            .json(ApiResponse::<()>::error("Account is disabled".to_string())));
    }

    // Verify password
    let password_valid =
        match crate::utils::crypto::verify_password(&request.password, &user.password_hash) {
            Ok(valid) => valid,
            Err(e) => {
                error!("Password verification error: {}", e);
                return Ok(HttpResponse::InternalServerError()
                    .json(ApiResponse::<()>::error("Authentication error".to_string())));
            }
        };

    if !password_valid {
        warn!(
            "Login attempt with invalid password for user: {}",
            request.username
        );
        return Ok(HttpResponse::Unauthorized()
            .json(ApiResponse::<()>::error("Invalid credentials".to_string())));
    }

    // Update last login time
    if let Err(e) = state
        .storage
        .database
        .update_user_last_login(user.id())
        .await
    {
        warn!("Failed to update last login time: {}", e);
    }

    // Generate JWT tokens
    let access_token = match state
        .auth
        .jwt()
        .create_access_token(user.id(), user.role.to_string(), vec![], None, None)
        .await
    {
        Ok(token) => token,
        Err(e) => {
            error!("Failed to generate access token: {}", e);
            return Ok(
                HttpResponse::InternalServerError().json(ApiResponse::<()>::error(
                    "Token generation failed".to_string(),
                )),
            );
        }
    };

    let refresh_token = match state.auth.jwt().create_refresh_token(user.id(), None).await {
        Ok(token) => token,
        Err(e) => {
            error!("Failed to generate refresh token: {}", e);
            return Ok(
                HttpResponse::InternalServerError().json(ApiResponse::<()>::error(
                    "Token generation failed".to_string(),
                )),
            );
        }
    };

    info!("User logged in successfully: {}", user.username);

    let response = LoginResponse {
        access_token,
        refresh_token,
        token_type: "Bearer".to_string(),
        expires_in: 3600, // 1 hour
        user: UserInfo {
            id: user.id(),
            username: user.username,
            email: user.email,
            full_name: user.display_name,
            role: user.role.to_string(),
            email_verified: user.email_verified,
        },
    };

    Ok(HttpResponse::Ok().json(ApiResponse::success(response)))
}

/// User logout endpoint
async fn logout(state: web::Data<AppState>, req: HttpRequest) -> ActixResult<HttpResponse> {
    info!("User logout");

    // Extract session token from headers or cookies
    if let Some(session_token) = extract_session_token(req.headers()) {
        if let Err(e) = state.auth.logout(&session_token).await {
            warn!("Failed to logout user: {}", e);
        }
    }

    Ok(HttpResponse::Ok().json(ApiResponse::success(())))
}

/// Refresh token endpoint
async fn refresh_token(
    state: web::Data<AppState>,
    request: web::Json<RefreshTokenRequest>,
) -> ActixResult<HttpResponse> {
    debug!("Token refresh request");

    // Verify refresh token
    match state
        .auth
        .jwt()
        .verify_refresh_token(&request.refresh_token)
        .await
    {
        Ok(user_id) => {
            // Find user to get current role
            let user = match state.storage.database.find_user_by_id(user_id).await {
                Ok(Some(user)) => user,
                Ok(None) => {
                    warn!("Refresh token for non-existent user: {}", user_id);
                    return Ok(HttpResponse::Unauthorized()
                        .json(ApiResponse::<()>::error("Invalid token".to_string())));
                }
                Err(e) => {
                    error!("Database error during token refresh: {}", e);
                    return Ok(HttpResponse::InternalServerError()
                        .json(ApiResponse::<()>::error("Database error".to_string())));
                }
            };

            // Generate new token pair
            let user_permissions = state
                .auth
                .rbac()
                .get_user_permissions(&user)
                .await
                .unwrap_or_default();

            match state
                .auth
                .jwt()
                .create_token_pair(
                    user.id(),
                    format!("{:?}", user.role),
                    user_permissions,
                    None,
                    None,
                )
                .await
            {
                Ok(tokens) => {
                    debug!("Token refreshed successfully for user: {}", user.username);
                    Ok(HttpResponse::Ok().json(ApiResponse::success(tokens)))
                }
                Err(e) => {
                    error!("Failed to generate new tokens: {}", e);
                    Ok(
                        HttpResponse::InternalServerError().json(ApiResponse::<()>::error(
                            "Internal server error".to_string(),
                        )),
                    )
                }
            }
        }
        Err(e) => {
            warn!("Invalid refresh token: {}", e);
            Ok(
                HttpResponse::BadRequest().json(ApiResponse::<()>::error_for_type(
                    "Invalid refresh token".to_string(),
                )),
            )
        }
    }
}

/// Forgot password endpoint
async fn forgot_password(
    state: web::Data<AppState>,
    request: web::Json<ForgotPasswordRequest>,
) -> ActixResult<HttpResponse> {
    info!("Password reset request for email: {}", request.email);

    // Generate reset token
    match state.auth.request_password_reset(&request.email).await {
        Ok(_reset_token) => {
            // TODO: Send email with reset token
            info!("Password reset token generated for: {}", request.email);
            Ok(HttpResponse::Ok().json(ApiResponse::success(())))
        }
        Err(e) => {
            // Don't reveal if email exists or not
            warn!("Password reset request failed: {}", e);
            Ok(HttpResponse::Ok().json(ApiResponse::success(())))
        }
    }
}

/// Reset password endpoint
async fn reset_password(
    state: web::Data<AppState>,
    request: web::Json<ResetPasswordRequest>,
) -> ActixResult<HttpResponse> {
    info!("Password reset with token");

    // Validate new password
    if let Err(e) = DataValidator::validate_password(&request.new_password) {
        return Ok(HttpResponse::Ok().json(ApiResponse::<()>::error_for_type(e.to_string())));
    }

    // Reset password
    match state
        .auth
        .reset_password(&request.token, &request.new_password)
        .await
    {
        Ok(()) => {
            info!("Password reset successfully");
            Ok(HttpResponse::Ok().json(ApiResponse::success(())))
        }
        Err(e) => {
            warn!("Password reset failed: {}", e);
            Ok(HttpResponse::Ok().json(ApiResponse::<()>::error_for_type(
                "Invalid or expired reset token".to_string(),
            )))
        }
    }
}

/// Email verification endpoint
async fn verify_email(
    state: web::Data<AppState>,
    request: web::Json<VerifyEmailRequest>,
) -> ActixResult<HttpResponse> {
    info!("Email verification with token");

    // Verify email token
    match state
        .auth
        .jwt()
        .verify_email_verification_token(&request.token)
        .await
    {
        Ok(user_id) => {
            // Mark email as verified
            match state.storage.db().verify_user_email(user_id).await {
                Ok(()) => {
                    info!("Email verified successfully for user: {}", user_id);
                    Ok(HttpResponse::Ok().json(ApiResponse::success(())))
                }
                Err(e) => {
                    error!("Failed to verify email: {}", e);
                    Ok(
                        HttpResponse::InternalServerError().json(ApiResponse::<()>::error(
                            "Internal server error".to_string(),
                        )),
                    )
                }
            }
        }
        Err(e) => {
            warn!("Invalid email verification token: {}", e);
            Ok(HttpResponse::Ok().json(ApiResponse::<()>::error_for_type(
                "Invalid or expired verification token".to_string(),
            )))
        }
    }
}

/// Change password endpoint
async fn change_password(
    state: web::Data<AppState>,
    req: HttpRequest,
    request: web::Json<ChangePasswordRequest>,
) -> ActixResult<HttpResponse> {
    info!("Password change request");

    // Get authenticated user
    let user = match get_authenticated_user(req.headers()) {
        Some(user) => user,
        None => {
            return Ok(HttpResponse::Unauthorized()
                .json(ApiResponse::<()>::error("Unauthorized".to_string())));
        }
    };

    // Validate new password
    if let Err(e) = DataValidator::validate_password(&request.new_password) {
        return Ok(HttpResponse::Ok().json(ApiResponse::<()>::error_for_type(e.to_string())));
    }

    // Change password
    match state
        .auth
        .change_password(user.id(), &request.current_password, &request.new_password)
        .await
    {
        Ok(()) => {
            info!("Password changed successfully for user: {}", user.username);
            Ok(HttpResponse::Ok().json(ApiResponse::success(())))
        }
        Err(e) => {
            warn!("Password change failed: {}", e);
            Ok(HttpResponse::Ok().json(ApiResponse::<()>::error_for_type(e.to_string())))
        }
    }
}

/// Get current user endpoint
async fn get_current_user(req: HttpRequest) -> ActixResult<HttpResponse> {
    debug!("Get current user request");

    // Get authenticated user
    let user = match get_authenticated_user(req.headers()) {
        Some(user) => user,
        None => {
            return Ok(HttpResponse::Unauthorized()
                .json(ApiResponse::<()>::error("Unauthorized".to_string())));
        }
    };

    Ok(HttpResponse::Ok().json(ApiResponse::success(user)))
}

/// Extract session token from headers
fn extract_session_token(headers: &HeaderMap) -> Option<String> {
    // 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("Session ") {
                return Some(stripped.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=") {
                    return Some(stripped.to_string());
                }
            }
        }
    }

    None
}

/// Get authenticated user from request extensions
fn get_authenticated_user(_headers: &HeaderMap) -> Option<User> {
    // In a real implementation, this would extract the user from request extensions
    // that were set by the authentication middleware
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_register_request_validation() {
        let request = RegisterRequest {
            username: "testuser".to_string(),
            email: "test@example.com".to_string(),
            password: "SecurePass123!".to_string(),
            full_name: Some("Test User".to_string()),
        };

        assert_eq!(request.username, "testuser");
        assert_eq!(request.email, "test@example.com");
        assert!(request.full_name.is_some());
    }

    #[test]
    fn test_user_response_conversion() {
        // This would require a real User instance in a full test
        // For now, just test the structure
        let user_response = UserResponse {
            id: uuid::Uuid::new_v4(),
            username: "testuser".to_string(),
            email: "test@example.com".to_string(),
            display_name: Some("Test User".to_string()),
            role: "User".to_string(),
            email_verified: false,
            created_at: chrono::Utc::now(),
        };

        assert_eq!(user_response.username, "testuser");
        assert!(!user_response.email_verified);
    }

    #[test]
    fn test_extract_session_token() {
        use actix_web::http::header::{HeaderName, HeaderValue};

        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("cookie"),
            HeaderValue::from_static("session=abc123; other=value"),
        );

        let token = extract_session_token(&headers);
        assert_eq!(token, Some("abc123".to_string()));

        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("authorization"),
            HeaderValue::from_static("Session xyz789"),
        );

        let token = extract_session_token(&headers);
        assert_eq!(token, Some("xyz789".to_string()));
    }
}