krab_core 0.6.0

Shared runtime for the Krab framework: config, HTTP, database, telemetry, resilience, signals, and protocol governance
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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
//! The HTTP surface of `krab_core` (feature `rest`), in one import path.
//!
//! [`apply_common_http_layers`] installs the standard middleware stack; this
//! module also re-exports the pieces it is built from — authentication
//! ([`AuthContext`], [`JwtProviderConfig`], ...), the [`ApiError`] envelope,
//! CORS and security headers, CSRF, protocol resolution, request-id
//! propagation ([`PropagationHeaders`]) and the health, readiness and metrics
//! handlers backed by [`RuntimeState`].

use std::time::Duration;

use axum::body::Body;
use axum::extract::State;
use axum::http::{HeaderName, HeaderValue, Request};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use axum::Router;
use tower::limit::ConcurrencyLimitLayer;
use tower_http::compression::CompressionLayer;
use tower_http::limit::RequestBodyLimitLayer;
use tower_http::timeout::TimeoutLayer;

use tracing::warn;

use crate::http_auth::{auth_middleware, service_auth_middleware};
pub use crate::http_auth::{
    authorize_with_jwt, authorize_with_jwt_cached, authorize_with_static_bearer,
    enforce_claim_policy, has_admin_entitlement, is_internal_service_path, jwt_algorithm_allowed,
    jwt_leeway_secs, load_jwt_providers, load_rotation_keys, load_route_policies, require_kid,
    roles_from_claims, scopes_from_claims, select_key, tenant_from_claims, tenant_from_path,
    validate_provider_claims, AuthContext, JwtClaims, JwtProviderConfig, JwtVerifierCache,
    RoutePolicy,
};
pub use crate::http_error::{ApiError, ErrorCategory};
pub use crate::http_headers::{
    cors_allow_headers_value, cors_allow_methods_value, cors_middleware,
    security_headers_middleware,
};
pub use crate::http_observability::PropagationHeaders;
use crate::http_observability::{metrics_middleware, request_id_middleware, tracing_middleware};
use crate::http_protocol::protocol_resolution_middleware;
pub use crate::http_protocol::{
    extract_protocol_preference, route_family_protocol, runtime_switch_header_rejected_by_default,
};
pub use crate::http_runtime::{
    health, metrics, metrics_prometheus, readiness, readiness_with_dependencies, DependencyStatus,
    HasReadinessDependencies, HasRuntimeState, MetricsPayload, ReadinessPayload, RuntimeState,
    StatusPayload,
};
pub use crate::http_security::{
    csrf_cookie_token, csrf_header_token, csrf_protection_enabled, csrf_protection_middleware,
    csrf_token_endpoint, extract_client_ip, is_unsafe_http_method,
};

pub(crate) fn current_window_epoch(window_secs: u64) -> u64 {
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let safe_window = window_secs.max(1);
    secs / safe_window
}

pub(crate) fn parse_csv_set(input: &str) -> Vec<String> {
    input
        .split(',')
        .map(|item| item.trim().to_string())
        .filter(|item| !item.is_empty())
        .collect()
}

/// Parse a `u64` env knob leniently but loudly: unset uses the default, a
/// malformed value warns and uses the default.
pub(crate) fn u64_env_lenient(name: &str, default: u64) -> u64 {
    match std::env::var(name) {
        Ok(raw) => match raw.trim().parse::<u64>() {
            Ok(value) => value,
            Err(_) => {
                warn!(
                    env_var = %name,
                    value = %raw,
                    default,
                    "env_value_invalid_using_default"
                );
                default
            }
        },
        Err(_) => default,
    }
}

/// What the concurrency limit does with requests it has no permit for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum OverloadMode {
    /// Wait for a permit. Excess requests are bounded by the request timeout.
    Queue,
    /// Fail fast with `503 Service Unavailable`.
    Shed,
}

/// Read `KRAB_HTTP_OVERLOAD_MODE`, trimming and reporting anything unknown.
///
/// The value used to be lowercased and compared raw, so `"shed "` — or a typo
/// — selected `queue` in silence. That is the worst shape for this particular
/// knob: a service configured to shed keeps queueing, and nothing says so
/// until the load the setting exists for actually arrives.
pub(crate) fn overload_mode_from_env() -> OverloadMode {
    let Ok(raw) = std::env::var("KRAB_HTTP_OVERLOAD_MODE") else {
        return OverloadMode::Queue;
    };
    match raw.trim().to_ascii_lowercase().as_str() {
        "" | "queue" => OverloadMode::Queue,
        "shed" => OverloadMode::Shed,
        _ => {
            warn!(
                env_var = "KRAB_HTTP_OVERLOAD_MODE",
                value = %raw,
                default = "queue",
                "env_value_invalid_using_default"
            );
            OverloadMode::Queue
        }
    }
}

/// Wraps `router` in Krab's standard middleware stack.
///
/// From outermost to innermost: metrics, request id (`x-request-id`, a fresh
/// UUID when missing or malformed), tracing, CORS, the per-client-IP rate
/// limit, authentication, protocol resolution, CSRF, internal-service scope
/// checks (`/internal`, `/api/internal`), a 2 MiB request-body limit,
/// response compression, the `x-krab-api-version` header and the security
/// headers; then the request timeout and concurrency limit around the
/// handlers themselves.
///
/// Read from the environment when this is called:
/// `KRAB_HTTP_REQUEST_TIMEOUT_SECS` (default 30; `0` disables, and a timed-out
/// request is answered `408`), `KRAB_HTTP_MAX_CONCURRENCY` (default 1024; `0`
/// disables) and `KRAB_HTTP_OVERLOAD_MODE` (`queue`, the default, waits for a
/// permit; `shed` answers `503 SERVICE_OVERLOADED` immediately). Malformed
/// values log a warning and use the default. The other layers take their
/// settings from `state`'s [`RuntimeState`], except CSRF, which reads its
/// switches from the environment per request (see
/// [`csrf_protection_enabled`]).
pub fn apply_common_http_layers<S>(router: Router<S>, state: S) -> Router<S>
where
    S: Clone + Send + Sync + 'static + HasRuntimeState,
{
    // Layer ordering note: axum/tower layers wrap bottom-up, so the LAST
    // `.layer(..)` in this chain is the OUTERMOST middleware and runs FIRST
    // for a request. Ordering constraints that matter:
    //
    // - `auth_middleware` must run BEFORE `service_auth_middleware` and
    //   `protocol_resolution_middleware` on the request path: both read the
    //   `AuthContext` extension that auth inserts. Protocol resolution used
    //   to be outermost, which meant it never saw an AuthContext and tenant
    //   protocol policy keyed off the client-supplied tenant header.
    // - `metrics_middleware` / `tracing_middleware` stay OUTSIDE auth so
    //   auth rejections are still counted; they learn the resolved protocol
    //   from the response extension that protocol resolution mirrors back.
    // - The timeout and concurrency layers are the FIRST layers, i.e. the
    //   INNERMOST: their generated responses (408 / queued shed) flow back
    //   out through the security-headers layer and the rest of the stack.
    let request_timeout_secs = u64_env_lenient("KRAB_HTTP_REQUEST_TIMEOUT_SECS", 30);
    let max_concurrency = u64_env_lenient("KRAB_HTTP_MAX_CONCURRENCY", 1024);
    let overload_mode = overload_mode_from_env();

    let mut router = router;
    if max_concurrency > 0 {
        if overload_mode == OverloadMode::Shed {
            let shed_layer = tower::ServiceBuilder::new()
                .layer(axum::error_handling::HandleErrorLayer::new(
                    |err: tower::BoxError| async move {
                        if err.is::<tower::load_shed::error::Overloaded>() {
                            // 503, not 429: the caller did nothing wrong, the
                            // service ran out of capacity. `.env.example`,
                            // `docs/reference/environment.md` and the
                            // changelog all describe shed mode as
                            // `503 Service Unavailable`, and load balancer and
                            // alert policies key off that difference.
                            ApiError::new(
                                ErrorCategory::Unavailable,
                                "SERVICE_OVERLOADED",
                                "Service concurrency limit reached; request dropped by load shedder",
                            )
                            .into_response()
                        } else {
                            ApiError::new(
                                ErrorCategory::Internal,
                                "INTERNAL_SERVER_ERROR",
                                "Unhandled server error",
                            )
                            .into_response()
                        }
                    },
                ))
                .layer(tower::load_shed::LoadShedLayer::new())
                .layer(ConcurrencyLimitLayer::new(max_concurrency as usize));

            router = router.layer(shed_layer);
        } else {
            router = router.layer(ConcurrencyLimitLayer::new(max_concurrency as usize));
        }
    }
    if request_timeout_secs > 0 {
        // Outside the concurrency limit so time spent waiting for a permit
        // counts against the deadline. tower-http's TimeoutLayer maps the
        // elapsed deadline to a 408 response, keeping the service infallible.
        router = router.layer(TimeoutLayer::with_status_code(
            axum::http::StatusCode::REQUEST_TIMEOUT,
            Duration::from_secs(request_timeout_secs),
        ));
    }

    router
        .layer(middleware::from_fn(security_headers_middleware))
        .layer(middleware::from_fn(api_version_header_middleware))
        .layer(CompressionLayer::new())
        .layer(RequestBodyLimitLayer::new(1024 * 1024 * 2))
        .layer(middleware::from_fn_with_state(
            state.clone(),
            service_auth_middleware::<S>,
        ))
        .layer(middleware::from_fn_with_state(
            state.clone(),
            csrf_protection_middleware::<S>,
        ))
        .layer(middleware::from_fn_with_state(
            state.clone(),
            protocol_resolution_middleware::<S>,
        ))
        .layer(middleware::from_fn_with_state(
            state.clone(),
            auth_middleware::<S>,
        ))
        .layer(middleware::from_fn_with_state(
            state.clone(),
            global_rate_limit_middleware::<S>,
        ))
        .layer(middleware::from_fn_with_state(
            state.clone(),
            cors_middleware::<S>,
        ))
        .layer(middleware::from_fn_with_state(
            state.clone(),
            tracing_middleware::<S>,
        ))
        .layer(middleware::from_fn_with_state(
            state.clone(),
            request_id_middleware::<S>,
        ))
        .layer(middleware::from_fn_with_state(
            state,
            metrics_middleware::<S>,
        ))
}

async fn api_version_header_middleware(req: Request<Body>, next: Next) -> Response {
    let mut response = next.run(req).await;
    response.headers_mut().insert(
        HeaderName::from_static("x-krab-api-version"),
        HeaderValue::from_static("1"),
    );
    response
}

async fn global_rate_limit_middleware<S>(
    State(state): State<S>,
    req: Request<Body>,
    next: Next,
) -> Response
where
    S: Clone + Send + Sync + 'static + HasRuntimeState,
{
    let (client_ip, capacity, refill_per_second, fail_open) = {
        let runtime = state.runtime_state();
        (
            extract_client_ip(&req, runtime.trust_proxy_headers),
            runtime.rate_limit_capacity,
            runtime.rate_limit_refill_per_sec,
            runtime.rate_limit_fail_open,
        )
    };

    let window_secs = ((capacity / refill_per_second.max(1.0)).ceil() as u64).clamp(1, 300);
    let window_epoch = current_window_epoch(window_secs);
    let key = format!("rate:ip:{}:{}", client_ip, window_epoch);

    let allowed = match state
        .runtime_state()
        .store
        .incr_with_ttl(&key, 1, Duration::from_secs(window_secs + 2))
        .await
    {
        Ok(count) => (count as f64) <= capacity,
        Err(err) => {
            if fail_open {
                warn!(error = %err, key = %key, mode = "open", "rate_limit_store_error_policy_applied");
                true
            } else {
                warn!(error = %err, key = %key, mode = "closed", "rate_limit_store_error_policy_applied");
                false
            }
        }
    };

    if !allowed {
        warn!(
            client_ip = %client_ip,
            capacity,
            refill_per_second,
            // A fixed-window counter per client IP: `capacity` requests per
            // `capacity / refill_per_second` seconds. It was logged as a
            // token bucket, which it has never been — bursts at a window
            // boundary can reach twice `capacity`.
            limiter = "global_per_ip_fixed_window",
            "global_ip_rate_limiter_triggered"
        );
        return ApiError::new(
            ErrorCategory::RateLimited,
            "TOO_MANY_REQUESTS",
            "global per-ip rate limit exceeded",
        )
        .into_response();
    }

    next.run(req).await
}

pub(crate) fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
    let max_len = left.len().max(right.len());
    let mut diff: usize = left.len() ^ right.len();

    for i in 0..max_len {
        let l = left.get(i).copied().unwrap_or(0);
        let r = right.get(i).copied().unwrap_or(0);
        diff |= (l ^ r) as usize;
    }

    diff == 0
}

pub(crate) fn bool_env(name: &str, default: bool) -> bool {
    std::env::var(name)
        .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
        .unwrap_or(default)
}

pub(crate) fn is_admin_api_path(path: &str) -> bool {
    let mut parts = path.split('/').filter(|p| !p.is_empty());
    if parts.next() != Some("api") {
        return false;
    }

    match parts.next() {
        Some("admin") => true,
        Some(version)
            if version.starts_with('v') && version[1..].chars().all(|c| c.is_ascii_digit()) =>
        {
            parts.next() == Some("admin")
        }
        _ => false,
    }
}

/// Returns the value to use for `Access-Control-Allow-Origin`, or `None` if the request
/// origin is not whitelisted.
pub(crate) fn compute_cors_origin<'a>(
    request_origin: &'a str,
    allowed: &[String],
    allow_any_origin: bool,
) -> Option<&'a str> {
    if request_origin.is_empty() {
        return None;
    }
    if allow_any_origin && allowed.is_empty() {
        return Some("*");
    }
    if allowed.iter().any(|origin| origin == "*") {
        return Some("*");
    }
    if allowed.iter().any(|origin| origin == request_origin) {
        return Some(request_origin);
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use axum::extract::State;
    use axum::http::{Method, Request, StatusCode};
    use axum::Json;

    #[test]
    fn scope_claim_string_is_split() {
        let claims = JwtClaims {
            sub: Some("u1".to_string()),
            iss: Some("issuer".to_string()),
            aud: None,
            exp: None,
            jti: None,
            token_use: None,
            tid: None,
            tenant_id: None,
            scope: Some("users.read users.write".to_string()),
            scp: None,
            roles: None,
            role: None,
            extra: Default::default(),
        };

        let scopes = scopes_from_claims(&claims);
        assert_eq!(
            scopes,
            vec!["users.read".to_string(), "users.write".to_string()]
        );
    }

    #[test]
    fn role_claim_falls_back_to_single_role() {
        let claims = JwtClaims {
            sub: Some("u1".to_string()),
            iss: Some("issuer".to_string()),
            aud: None,
            exp: None,
            jti: None,
            token_use: None,
            tid: None,
            tenant_id: None,
            scope: None,
            scp: None,
            roles: None,
            role: Some("admin".to_string()),
            extra: Default::default(),
        };

        let roles = roles_from_claims(&claims);
        assert_eq!(roles, vec!["admin".to_string()]);
    }

    #[test]
    fn tenant_path_extraction_works() {
        assert_eq!(tenant_from_path("/api/tenants/t1/users"), Some("t1"));
        assert_eq!(tenant_from_path("/api/users/me"), None);
    }

    #[test]
    fn tenant_claim_falls_back_to_tid() {
        let claims = JwtClaims {
            sub: Some("u1".to_string()),
            iss: Some("issuer".to_string()),
            aud: None,
            exp: None,
            jti: None,
            token_use: None,
            tid: Some("tenant-a".to_string()),
            tenant_id: None,
            scope: None,
            scp: None,
            roles: None,
            role: None,
            extra: Default::default(),
        };

        assert_eq!(tenant_from_claims(&claims).as_deref(), Some("tenant-a"));
    }

    #[derive(Clone)]
    struct TestState {
        runtime: RuntimeState,
        dependencies: Vec<DependencyStatus>,
    }

    impl HasRuntimeState for TestState {
        fn runtime_state(&self) -> &RuntimeState {
            &self.runtime
        }
    }

    impl HasReadinessDependencies for TestState {
        fn readiness_dependencies(&self) -> Vec<DependencyStatus> {
            self.dependencies.clone()
        }
    }

    #[tokio::test]
    async fn readiness_non_critical_failure_is_degraded_but_available() {
        let state = TestState {
            runtime: RuntimeState::new(),
            dependencies: vec![DependencyStatus {
                name: "cache",
                ready: false,
                critical: false,
                latency_ms: Some(250),
                detail: Some("cache-timeout".to_string()),
            }],
        };

        let (status, Json(payload)) = readiness_with_dependencies::<TestState>(State(state)).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(payload.status, "degraded");
    }

    #[test]
    fn cors_allow_headers_is_strict_allowlist() {
        assert_eq!(
            cors_allow_headers_value(),
            "authorization,content-type,x-request-id,x-trace-id"
        );
    }

    #[test]
    fn cors_allow_methods_is_reduced_surface() {
        assert_eq!(cors_allow_methods_value(), "GET,POST,OPTIONS");
    }

    #[test]
    fn csrf_cookie_token_extraction_works() {
        let mut headers = axum::http::HeaderMap::new();
        headers.insert(
            axum::http::header::COOKIE,
            axum::http::HeaderValue::from_static("foo=1; krab_csrf_token=abc123; bar=2"),
        );

        assert_eq!(csrf_cookie_token(&headers).as_deref(), Some("abc123"));
    }

    #[test]
    fn csrf_header_token_extraction_works() {
        let mut headers = axum::http::HeaderMap::new();
        headers.insert(
            axum::http::HeaderName::from_static("x-csrf-token"),
            axum::http::HeaderValue::from_static("abc123"),
        );

        assert_eq!(csrf_header_token(&headers).as_deref(), Some("abc123"));
    }

    /// The middleware extraction functions and the shared wire-contract
    /// constants in `crate::csrf` must agree. The wasm client half of
    /// `#[server]` only ever uses the constants, so this pins the server half
    /// to the same names — they cannot drift apart again.
    #[test]
    fn csrf_middleware_names_match_shared_constants() {
        let mut headers = axum::http::HeaderMap::new();
        headers.insert(
            axum::http::header::COOKIE,
            axum::http::HeaderValue::from_str(&format!(
                "{}=tok-from-cookie",
                crate::csrf::CSRF_COOKIE_NAME
            ))
            .expect("cookie header should build"),
        );
        headers.insert(
            axum::http::HeaderName::from_bytes(crate::csrf::CSRF_HEADER_NAME.as_bytes())
                .expect("header name should build"),
            axum::http::HeaderValue::from_static("tok-from-header"),
        );

        assert_eq!(
            csrf_cookie_token(&headers).as_deref(),
            Some("tok-from-cookie")
        );
        assert_eq!(
            csrf_header_token(&headers).as_deref(),
            Some("tok-from-header")
        );
    }

    /// The token endpoint must expose the token in its JSON body under the
    /// shared field name and set the shared cookie name — with `HttpOnly`, the
    /// body is the only channel through which a browser client can learn the
    /// token.
    #[tokio::test]
    async fn csrf_token_endpoint_body_and_cookie_use_shared_names() {
        let response = csrf_token_endpoint().await;

        let set_cookie = response
            .headers()
            .get(axum::http::header::SET_COOKIE)
            .expect("endpoint must set the CSRF cookie")
            .to_str()
            .expect("cookie should be ascii")
            .to_string();
        assert!(
            set_cookie.starts_with(&format!("{}=", crate::csrf::CSRF_COOKIE_NAME)),
            "cookie {set_cookie:?} does not use the shared cookie name"
        );
        assert!(set_cookie.contains("HttpOnly"));

        let body = axum::body::to_bytes(response.into_body(), 64 * 1024)
            .await
            .expect("body should read");
        let parsed: serde_json::Value = serde_json::from_slice(&body).expect("body should be JSON");
        let token = parsed
            .get(crate::csrf::CSRF_TOKEN_JSON_FIELD)
            .and_then(|v| v.as_str())
            .expect("body must carry the token under the shared field name");
        assert!(
            set_cookie.contains(token),
            "cookie and body must carry the same token"
        );
    }

    #[test]
    fn extract_client_ip_falls_back_to_connect_info_when_proxy_headers_untrusted() {
        let mut req = Request::builder()
            .header("x-forwarded-for", "203.0.113.10, 10.0.0.2")
            .header("x-real-ip", "203.0.113.11")
            .body(Body::empty())
            .expect("request should build");
        req.extensions_mut()
            .insert(axum::extract::connect_info::ConnectInfo(
                "198.51.100.20:443"
                    .parse::<std::net::SocketAddr>()
                    .expect("socket addr should parse"),
            ));

        assert_eq!(extract_client_ip(&req, false), "198.51.100.20");
    }

    /// With proxy headers trusted, the RIGHTMOST x-forwarded-for entry wins
    /// (default `KRAB_TRUSTED_PROXY_HOPS=1`): only the entries appended by
    /// our own proxies are trustworthy, and the leftmost values are
    /// client-controlled — taking the leftmost let any client spoof its IP
    /// past the rate limiter.
    #[test]
    #[serial_test::serial]
    fn extract_client_ip_prefers_rightmost_forwarded_value_when_trusted() {
        std::env::remove_var("KRAB_TRUSTED_PROXY_HOPS");
        let req = Request::builder()
            .header("x-forwarded-for", "203.0.113.10, 10.0.0.2")
            .header("x-real-ip", "203.0.113.11")
            .body(Body::empty())
            .expect("request should build");

        assert_eq!(extract_client_ip(&req, true), "10.0.0.2");
    }

    #[test]
    #[serial_test::serial]
    fn extract_client_ip_skips_configured_trusted_hops_from_the_right() {
        std::env::set_var("KRAB_TRUSTED_PROXY_HOPS", "2");
        let req = Request::builder()
            .header("x-forwarded-for", "203.0.113.10, 198.51.100.7, 10.0.0.2")
            .body(Body::empty())
            .expect("request should build");

        let ip = extract_client_ip(&req, true);
        std::env::remove_var("KRAB_TRUSTED_PROXY_HOPS");

        assert_eq!(ip, "198.51.100.7");
    }

    /// A candidate that does not parse as an IP address must not be used as a
    /// rate-limit key; the extraction falls through to x-real-ip, then
    /// ConnectInfo.
    #[test]
    #[serial_test::serial]
    fn extract_client_ip_garbage_forwarded_entry_falls_back() {
        std::env::remove_var("KRAB_TRUSTED_PROXY_HOPS");
        let mut req = Request::builder()
            .header("x-forwarded-for", "203.0.113.10, not-an-ip")
            .header("x-real-ip", "203.0.113.11")
            .body(Body::empty())
            .expect("request should build");
        req.extensions_mut()
            .insert(axum::extract::connect_info::ConnectInfo(
                "198.51.100.20:443"
                    .parse::<std::net::SocketAddr>()
                    .expect("socket addr should parse"),
            ));

        assert_eq!(extract_client_ip(&req, true), "203.0.113.11");

        let mut req_no_real_ip = Request::builder()
            .header("x-forwarded-for", "garbage")
            .body(Body::empty())
            .expect("request should build");
        req_no_real_ip
            .extensions_mut()
            .insert(axum::extract::connect_info::ConnectInfo(
                "198.51.100.20:443"
                    .parse::<std::net::SocketAddr>()
                    .expect("socket addr should parse"),
            ));

        assert_eq!(extract_client_ip(&req_no_real_ip, true), "198.51.100.20");
    }

    #[test]
    fn extract_client_ip_falls_back_to_real_ip_when_forwarded_missing() {
        let req = Request::builder()
            .header("x-real-ip", "203.0.113.11")
            .body(Body::empty())
            .expect("request should build");

        assert_eq!(extract_client_ip(&req, true), "203.0.113.11");
    }

    #[test]
    fn extract_client_ip_returns_unknown_without_headers_or_connect_info() {
        let req = Request::builder()
            .body(Body::empty())
            .expect("request should build");

        assert_eq!(extract_client_ip(&req, false), "unknown");
    }

    #[test]
    fn unsafe_method_detection_is_strict() {
        assert!(is_unsafe_http_method(&Method::POST));
        assert!(is_unsafe_http_method(&Method::PUT));
        assert!(is_unsafe_http_method(&Method::PATCH));
        assert!(is_unsafe_http_method(&Method::DELETE));
        assert!(!is_unsafe_http_method(&Method::GET));
        assert!(!is_unsafe_http_method(&Method::HEAD));
        assert!(!is_unsafe_http_method(&Method::OPTIONS));
    }

    #[test]
    fn constant_time_eq_requires_exact_match() {
        assert!(constant_time_eq(b"Bearer abc", b"Bearer abc"));
        assert!(!constant_time_eq(b"Bearer abc", b"Bearer abd"));
        assert!(!constant_time_eq(b"Bearer abc", b"Bearer abcx"));
    }
}