litellm-rs 0.6.0

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
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
//! Authentication middleware

use crate::auth::{AUTHENTICATION_SERVICE_UNAVAILABLE_MESSAGE, AuthMethod};
use crate::core::audit::middleware::record_authenticated_principal;
use crate::core::models::{ApiKey, user::types::User};
use crate::core::types::context::{RequestContext, SharedRequestContext};
use crate::server::middleware::auth_rate_limiter::get_auth_rate_limiter;
use crate::server::middleware::helpers::{
    extract_auth_method_with_api_key_header, is_public_route, middleware_gateway_error_response,
};
use crate::server::middleware::rate_limit::{
    AuthRateLimitReservation, RateLimitError, enforce_rate_limit_for_rejected_auth,
    reserve_rate_limit_for_auth_attempt,
};
use crate::server::routes::ai::{self, api_key_allows_endpoint, check_permission};
use crate::server::state::AppState;
use crate::utils::error::gateway_error::GatewayError;
use actix_web::body::EitherBody;
use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform, forward_ready};
use actix_web::{HttpMessage, HttpRequest, web};
use futures::future::{Ready, ready};
use std::collections::HashMap;
use std::future::Future;
use std::net::SocketAddr;
use std::pin::Pin;
use std::rc::Rc;
use std::sync::Arc;
use tracing::{debug, error, warn};

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

fn bypasses_header_auth(path: &str) -> bool {
    is_public_route(path) || path == "/auth/refresh"
}

impl<S, B> Transform<S, ServiceRequest> for AuthMiddleware
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<EitherBody<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: Rc::new(service),
        }))
    }
}

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

impl<S, B> Service<ServiceRequest> for AuthMiddlewareService<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<EitherBody<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 service = Rc::clone(&self.service);

        Box::pin(async move {
            // Check public route with &str reference before any mutable borrows,
            // avoiding a per-request String allocation for the path.
            let is_public = bypasses_header_auth(req.path());

            let app_state = match req.app_data::<web::Data<AppState>>().cloned() {
                Some(state) => state,
                None => {
                    return Err(actix_web::error::ErrorInternalServerError(
                        "Missing application state",
                    ));
                }
            };
            let cfg = app_state.config.load();
            let enable_jwt = cfg.auth().enable_jwt;
            let enable_api_key = cfg.auth().enable_api_key;
            let api_key_header = cfg.auth().api_key_header.clone();
            let rate_limit_enabled = cfg.gateway.rate_limit.enabled;
            let rate_limit_rpm = cfg.gateway.rate_limit.effective_rpm();
            let trusted_proxies = cfg.server().trusted_proxies.clone();

            let context = build_request_context(&mut req);
            let auth_method =
                extract_auth_method_with_api_key_header(req.headers(), api_key_header.as_str());
            let client_id = get_client_identifier(&req, &auth_method);
            let rate_limiter = get_auth_rate_limiter();

            if is_public {
                insert_request_context(&mut req, context);
                return service
                    .call(req)
                    .await
                    .map(ServiceResponse::map_into_left_body);
            }

            let auth_enabled = enable_jwt || enable_api_key;
            if !auth_enabled {
                // Fail closed: both auth methods are disabled. Only allow the
                // request through when anonymous access was explicitly opted
                // into. AuthConfig::validate() already rejects this combination,
                // but guard here as defense in depth in case validation was
                // bypassed.
                if !cfg.auth().allow_anonymous {
                    error!(
                        "All authentication methods are disabled and allow_anonymous is false; \
                         rejecting request to non-public route. Enable JWT or API key auth, or \
                         set allow_anonymous: true (development only)."
                    );
                    return Ok(unauthorized_response(
                        req,
                        "Authentication is not configured",
                    ));
                }
                insert_request_context(&mut req, context);
                return service
                    .call(req)
                    .await
                    .map(ServiceResponse::map_into_left_body);
            }

            if let Err(wait_seconds) = rate_limiter.check_allowed(&client_id) {
                if let Err(error) = enforce_gateway_rate_limit_for_auth_rejection(
                    &req,
                    rate_limit_enabled,
                    rate_limit_rpm,
                    &trusted_proxies,
                )
                .await
                {
                    return Ok(rate_limit_response(req, error));
                }
                return Ok(failed_attempt_rate_limit_response(req, wait_seconds));
            }

            let auth_method = match auth_method {
                AuthMethod::Jwt(_) if !enable_jwt => {
                    rate_limiter.record_failure(&client_id);
                    if let Err(error) = enforce_gateway_rate_limit_for_auth_rejection(
                        &req,
                        rate_limit_enabled,
                        rate_limit_rpm,
                        &trusted_proxies,
                    )
                    .await
                    {
                        return Ok(rate_limit_response(req, error));
                    }
                    return Ok(unauthorized_response(req, "JWT authentication disabled"));
                }
                AuthMethod::ApiKey(_) if !enable_api_key => {
                    rate_limiter.record_failure(&client_id);
                    if let Err(error) = enforce_gateway_rate_limit_for_auth_rejection(
                        &req,
                        rate_limit_enabled,
                        rate_limit_rpm,
                        &trusted_proxies,
                    )
                    .await
                    {
                        return Ok(rate_limit_response(req, error));
                    }
                    return Ok(unauthorized_response(
                        req,
                        "API key authentication disabled",
                    ));
                }
                other => other,
            };

            if matches!(auth_method, AuthMethod::None) {
                rate_limiter.record_failure(&client_id);
                if let Err(error) = enforce_gateway_rate_limit_for_auth_rejection(
                    &req,
                    rate_limit_enabled,
                    rate_limit_rpm,
                    &trusted_proxies,
                )
                .await
                {
                    return Ok(rate_limit_response(req, error));
                }
                return Ok(unauthorized_response(req, "Missing authentication"));
            }

            let mut auth_rate_limit_reservation = if requires_auth_verification(&auth_method) {
                match reserve_gateway_rate_limit_before_auth(
                    &req,
                    rate_limit_enabled,
                    rate_limit_rpm,
                    &trusted_proxies,
                )
                .await
                {
                    Ok(reservation) => Some(reservation),
                    Err(error) => return Ok(rate_limit_response(req, error)),
                }
            } else {
                None
            };

            match app_state.auth.authenticate(auth_method, context).await {
                Ok(result) if result.success => {
                    if let Some(reservation) = auth_rate_limit_reservation.take() {
                        reservation.release().await;
                    }
                    rate_limiter.record_success(&client_id);
                    debug!("Authentication succeeded");

                    // Attach the authenticated principal before authorization
                    // checks so audit middleware can attribute 403 responses.
                    record_authenticated_principal(&req, &result.context);
                    insert_request_context(&mut req, result.context);
                    match api_key_allows_endpoint(result.api_key.as_ref(), req.path()) {
                        Ok(true) => {}
                        Ok(false) => {
                            warn!("Authenticated API key is not permitted to access this endpoint");
                            return Ok(forbidden_response(
                                req,
                                "API key is not permitted for this endpoint",
                            ));
                        }
                        Err(error) => {
                            warn!("Authenticated API key policy is invalid: {}", error);
                            return Ok(authentication_unavailable_response(req));
                        }
                    }
                    if let Some(operation) = ai::operation_for_path(req.path())
                        && !check_permission(
                            result.user.as_ref(),
                            result.api_key.as_ref(),
                            operation,
                        )
                    {
                        warn!(
                            "Authenticated caller is not permitted to access AI operation '{}'",
                            operation
                        );
                        return Ok(forbidden_response(
                            req,
                            "API key is not permitted for this operation",
                        ));
                    }

                    if let Some(user) = result.user {
                        req.extensions_mut().insert::<User>(user);
                    }
                    if let Some(api_key) = result.api_key {
                        req.extensions_mut().insert::<ApiKey>(api_key);
                    }

                    service
                        .call(req)
                        .await
                        .map(ServiceResponse::map_into_left_body)
                }
                Ok(result) => {
                    rate_limiter.record_failure(&client_id);
                    warn!(
                        "Authentication failed: {}",
                        result
                            .error
                            .clone()
                            .unwrap_or_else(|| "unauthorized".to_string())
                    );
                    if auth_rate_limit_reservation.is_none()
                        && let Err(error) = enforce_gateway_rate_limit_for_auth_rejection(
                            &req,
                            rate_limit_enabled,
                            rate_limit_rpm,
                            &trusted_proxies,
                        )
                        .await
                    {
                        return Ok(rate_limit_response(req, error));
                    }
                    Ok(unauthorized_response(
                        req,
                        result.error.unwrap_or_else(|| "Unauthorized".to_string()),
                    ))
                }
                Err(err) => {
                    if let Some(reservation) = auth_rate_limit_reservation.take() {
                        reservation.release().await;
                    }
                    error!(error = %err, "Authentication infrastructure failure");
                    Ok(authentication_unavailable_response(req))
                }
            }
        })
    }
}

async fn enforce_gateway_rate_limit_for_auth_rejection(
    req: &ServiceRequest,
    enabled: bool,
    requests_per_minute: u32,
    trusted_proxies: &[String],
) -> Result<(), RateLimitError> {
    if !enabled {
        return Ok(());
    }

    enforce_rate_limit_for_rejected_auth(req, requests_per_minute, trusted_proxies).await
}

async fn reserve_gateway_rate_limit_before_auth(
    req: &ServiceRequest,
    enabled: bool,
    requests_per_minute: u32,
    trusted_proxies: &[String],
) -> Result<AuthRateLimitReservation, RateLimitError> {
    if !enabled {
        return Ok(AuthRateLimitReservation::noop());
    }

    reserve_rate_limit_for_auth_attempt(req, requests_per_minute, trusted_proxies).await
}

fn requires_auth_verification(auth_method: &AuthMethod) -> bool {
    matches!(
        auth_method,
        AuthMethod::Jwt(_) | AuthMethod::ApiKey(_) | AuthMethod::Session(_)
    )
}

fn unauthorized_response<B>(
    req: ServiceRequest,
    message: impl Into<String>,
) -> ServiceResponse<EitherBody<B>> {
    let message = message.into();
    middleware_gateway_error_response(
        req,
        actix_web::error::ErrorUnauthorized(message.clone()),
        GatewayError::Auth(message),
    )
}

fn forbidden_response<B>(
    req: ServiceRequest,
    message: impl Into<String>,
) -> ServiceResponse<EitherBody<B>> {
    let message = message.into();
    middleware_gateway_error_response(
        req,
        actix_web::error::ErrorForbidden(message.clone()),
        GatewayError::Forbidden(message),
    )
}

fn authentication_unavailable_response<B>(req: ServiceRequest) -> ServiceResponse<EitherBody<B>> {
    if ai::is_openai_compatible_path(req.path()) {
        return req
            .into_response(ai::openai_internal_error_response(
                AUTHENTICATION_SERVICE_UNAVAILABLE_MESSAGE,
            ))
            .map_into_right_body();
    }

    req.error_response(actix_web::error::ErrorInternalServerError(
        AUTHENTICATION_SERVICE_UNAVAILABLE_MESSAGE,
    ))
    .map_into_right_body()
}

fn rate_limit_response<B>(
    req: ServiceRequest,
    error: RateLimitError,
) -> ServiceResponse<EitherBody<B>> {
    let gateway_error = error.gateway_error();
    middleware_gateway_error_response(req, actix_web::Error::from(error), gateway_error)
}

fn failed_attempt_rate_limit_response<B>(
    req: ServiceRequest,
    wait_seconds: u64,
) -> ServiceResponse<EitherBody<B>> {
    let message = format!(
        "Too many failed attempts. Try again in {} seconds",
        wait_seconds
    );
    middleware_gateway_error_response(
        req,
        actix_web::error::ErrorTooManyRequests(message.clone()),
        GatewayError::RateLimit {
            message,
            retry_after: Some(wait_seconds),
            rpm_limit: None,
            tpm_limit: None,
        },
    )
}

/// Extract request context from request
pub fn get_request_context(req: &HttpRequest) -> Result<SharedRequestContext, actix_web::Error> {
    if let Some(context) = req.extensions().get::<SharedRequestContext>() {
        return Ok(Arc::clone(context));
    }

    req.extensions()
        .get::<RequestContext>()
        .map(|context| Arc::new(context.clone()))
        .ok_or_else(|| actix_web::error::ErrorInternalServerError("Missing request context"))
}

fn insert_request_context(req: &mut ServiceRequest, context: RequestContext) {
    req.extensions_mut()
        .insert::<SharedRequestContext>(Arc::new(context));
}

/// Extract a client identifier for rate limiting
fn get_client_identifier(req: &ServiceRequest, auth_method: &AuthMethod) -> String {
    let ip = req
        .connection_info()
        .peer_addr()
        .map(parse_peer_ip)
        .unwrap_or_else(|| "unknown".to_string());

    match auth_method {
        AuthMethod::ApiKey(key) => format!("{}:api_key:{}", ip, hash_credential(key)),
        AuthMethod::Jwt(token) => format!("{}:jwt:{}", ip, hash_credential(token)),
        // Session cookies are untrusted until authentication succeeds, so keep
        // failed session attempts in one stable per-IP lockout bucket.
        AuthMethod::Session(_) => format!("ip:{}", ip),
        AuthMethod::None => format!("ip:{}", ip),
    }
}

fn parse_peer_ip(peer: &str) -> String {
    peer.parse::<SocketAddr>()
        .map(|addr| addr.ip().to_string())
        .unwrap_or_else(|_| peer.to_string())
}

fn hash_credential(credential: &str) -> String {
    use sha2::{Digest, Sha256};
    format!("{:x}", Sha256::digest(credential.as_bytes()))
}

fn build_request_context(req: &mut ServiceRequest) -> RequestContext {
    let mut context = RequestContext::new();

    // Use the request ID set by RequestIdMiddleware when present; otherwise keep
    // the UUID that RequestContext::new() already generated so that AuthMiddleware
    // remains self-sufficient when used without RequestIdMiddleware in the stack.
    if let Some(id) = req
        .headers()
        .get("x-request-id")
        .and_then(|value| value.to_str().ok())
        .filter(|s| !s.is_empty())
    {
        context.request_id = id.to_string();
    }

    context.user_agent = req
        .headers()
        .get("user-agent")
        .and_then(|value| value.to_str().ok())
        .map(str::to_string);
    context.client_ip = req.connection_info().peer_addr().map(|ip| ip.to_string());

    let mut headers = HashMap::new();
    for (name, value) in req.headers().iter() {
        if name.as_str().eq_ignore_ascii_case("authorization")
            || name.as_str().eq_ignore_ascii_case("x-api-key")
        {
            continue;
        }
        if let Ok(value) = value.to_str() {
            headers.insert(name.as_str().to_string(), value.to_string());
        }
    }
    context.headers = headers;

    context
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::server::middleware::helpers::extract_auth_method_with_api_key_header;
    use actix_web::test::TestRequest;

    fn client_id_for_header(
        header_name: &'static str,
        header_value: &'static str,
        api_key_header: &str,
    ) -> String {
        let req = TestRequest::default()
            .peer_addr("203.0.113.55:1000".parse().unwrap())
            .insert_header((header_name, header_value))
            .to_srv_request();
        let auth_method = extract_auth_method_with_api_key_header(req.headers(), api_key_header);
        get_client_identifier(&req, &auth_method)
    }

    #[test]
    fn client_identifier_normalizes_api_key_transports() {
        let configured = client_id_for_header("x-litellm-key", "gw-same-key", "x-litellm-key");
        let fallback = client_id_for_header("x-api-key", "gw-same-key", "x-litellm-key");
        let authorization_scheme =
            client_id_for_header("authorization", "ApiKey gw-same-key", "x-litellm-key");
        let authorization_raw =
            client_id_for_header("authorization", "gw-same-key", "x-litellm-key");

        assert_eq!(configured, fallback);
        assert_eq!(configured, authorization_scheme);
        assert_eq!(configured, authorization_raw);
    }

    #[test]
    fn client_identifier_distinguishes_different_credentials() {
        let first = client_id_for_header("x-api-key", "gw-first-key", "x-api-key");
        let second = client_id_for_header("x-api-key", "gw-second-key", "x-api-key");

        assert_ne!(first, second);
    }

    #[test]
    fn client_identifier_ignores_peer_port() {
        let req_a = TestRequest::default()
            .peer_addr("203.0.113.60:1000".parse().unwrap())
            .insert_header(("x-api-key", "gw-same-key"))
            .to_srv_request();
        let req_b = TestRequest::default()
            .peer_addr("203.0.113.60:2000".parse().unwrap())
            .insert_header(("x-api-key", "gw-same-key"))
            .to_srv_request();
        let auth_a = extract_auth_method_with_api_key_header(req_a.headers(), "x-api-key");
        let auth_b = extract_auth_method_with_api_key_header(req_b.headers(), "x-api-key");

        assert_eq!(
            get_client_identifier(&req_a, &auth_a),
            get_client_identifier(&req_b, &auth_b)
        );
    }

    #[test]
    fn client_identifier_falls_back_to_ip_without_auth() {
        let req = TestRequest::default()
            .peer_addr("203.0.113.70:1000".parse().unwrap())
            .to_srv_request();

        assert_eq!(
            get_client_identifier(&req, &AuthMethod::None),
            "ip:203.0.113.70"
        );
    }

    #[test]
    fn client_identifier_keeps_session_failures_in_ip_bucket() {
        let req_a = TestRequest::default()
            .peer_addr("203.0.113.80:1000".parse().unwrap())
            .insert_header(("cookie", "session=session-a"))
            .to_srv_request();
        let req_b = TestRequest::default()
            .peer_addr("203.0.113.80:1000".parse().unwrap())
            .insert_header(("cookie", "session=session-b"))
            .to_srv_request();
        let auth_a = extract_auth_method_with_api_key_header(req_a.headers(), "x-api-key");
        let auth_b = extract_auth_method_with_api_key_header(req_b.headers(), "x-api-key");

        assert_eq!(
            get_client_identifier(&req_a, &auth_a),
            get_client_identifier(&req_b, &auth_b)
        );
        assert_eq!(get_client_identifier(&req_a, &auth_a), "ip:203.0.113.80");
    }

    #[test]
    fn auth_verification_precheck_only_applies_to_present_credentials() {
        assert!(requires_auth_verification(&AuthMethod::Jwt(
            "jwt-token".to_string()
        )));
        assert!(requires_auth_verification(&AuthMethod::ApiKey(
            "api-key".to_string()
        )));
        assert!(requires_auth_verification(&AuthMethod::Session(
            "session-id".to_string()
        )));
        assert!(!requires_auth_verification(&AuthMethod::None));
    }

    #[test]
    fn insert_request_context_stores_shared_extension_handle() {
        let api_key_id = uuid::Uuid::new_v4();
        let mut req = TestRequest::default().to_srv_request();

        insert_request_context(&mut req, RequestContext::new().with_api_key(api_key_id));

        let extensions = req.extensions();
        let stored = extensions
            .get::<SharedRequestContext>()
            .expect("request context should be stored as a shared handle");
        assert_eq!(stored.api_key_id(), Some(api_key_id));
        assert!(extensions.get::<RequestContext>().is_none());
    }

    #[test]
    fn forbidden_response_retains_authenticated_principal_context() {
        let user_id = uuid::Uuid::new_v4();
        let api_key_id = uuid::Uuid::new_v4();
        let team_id = uuid::Uuid::new_v4();
        let mut req = TestRequest::default().to_srv_request();
        insert_request_context(
            &mut req,
            RequestContext::new()
                .with_user(user_id, Some(team_id))
                .with_api_key(api_key_id),
        );

        let response = forbidden_response::<actix_web::body::BoxBody>(req, "denied");
        let extensions = response.request().extensions();
        let context = extensions
            .get::<SharedRequestContext>()
            .expect("authenticated context should survive a 403 response");

        assert_eq!(
            context.user_id.as_deref(),
            Some(user_id.to_string().as_str())
        );
        assert_eq!(context.api_key_id(), Some(api_key_id));
        assert_eq!(context.team_id(), Some(team_id));
    }

    #[test]
    fn build_request_context_excludes_sensitive_auth_headers() {
        let mut req = TestRequest::default()
            .insert_header(("authorization", "Bearer secret"))
            .insert_header(("x-api-key", "sk-secret"))
            .insert_header(("x-request-id", "req-123"))
            .insert_header(("x-observable", "kept"))
            .to_srv_request();

        let context = build_request_context(&mut req);

        assert_eq!(context.request_id, "req-123");
        assert_eq!(
            context.headers.get("x-observable").map(String::as_str),
            Some("kept")
        );
        assert!(!context.headers.contains_key("authorization"));
        assert!(!context.headers.contains_key("x-api-key"));
    }

    #[actix_web::test]
    async fn authentication_unavailable_response_is_generic_server_error() {
        let req = TestRequest::with_uri("/v1/chat/completions").to_srv_request();
        let response = authentication_unavailable_response::<actix_web::body::BoxBody>(req);

        assert_eq!(
            response.status(),
            actix_web::http::StatusCode::INTERNAL_SERVER_ERROR
        );
        let body = actix_web::body::to_bytes(response.into_body())
            .await
            .expect("generic authentication error body should render");
        let body: serde_json::Value = serde_json::from_slice(&body)
            .expect("generic authentication error body should be valid JSON");
        assert_eq!(
            body["error"]["message"],
            AUTHENTICATION_SERVICE_UNAVAILABLE_MESSAGE
        );
        let body = body.to_string();
        for internal_detail in [
            "Storage error",
            "Database error",
            "Redis error",
            "Connection closed",
        ] {
            assert!(!body.contains(internal_detail));
        }
    }
}