krab_core 0.4.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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
#[cfg(test)]
#[allow(clippy::await_holding_lock)]
mod tests {
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use axum::Router;
    use jsonwebtoken::{encode, EncodingKey, Header};
    use serde_json::{json, Value};
    use serial_test::serial;
    use std::sync::{Mutex, OnceLock};
    use std::time::Duration;
    use tower::ServiceExt;

    use crate::http::{apply_common_http_layers, RuntimeState};

    #[derive(Clone)]
    struct TestState {
        runtime: RuntimeState,
    }

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

    static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();

    fn env_lock() -> std::sync::MutexGuard<'static, ()> {
        match ENV_LOCK.get_or_init(|| Mutex::new(())).lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        }
    }

    fn reset_auth_env() {
        for key in [
            "KRAB_ENVIRONMENT",
            "KRAB_REDIS_URL",
            "KRAB_AUTH_MODE",
            "KRAB_JWT_SECRET",
            "KRAB_JWT_SECRET_FILE",
            "KRAB_JWT_KEYS_JSON",
            "KRAB_JWT_KEYS_JSON_FILE",
            "KRAB_JWT_PROVIDERS_JSON",
            "KRAB_JWT_PROVIDERS_JSON_FILE",
            "KRAB_OIDC_ISSUER",
            "KRAB_OIDC_AUDIENCE",
            "KRAB_JWT_ALLOWED_ALGS",
            "KRAB_AUTH_REQUIRED_SCOPES",
            "KRAB_AUTH_REQUIRED_ROLES",
            "KRAB_AUTH_REQUIRED_CLAIMS_JSON",
            "KRAB_AUTH_ROUTE_POLICIES_JSON",
            "KRAB_AUTH_REQUIRE_TENANT_CLAIM",
            "KRAB_AUTH_REQUIRE_TENANT_MATCH",
            "KRAB_JWT_REQUIRE_KID",
            "KRAB_AUTH_OPEN_PATHS",
            "KRAB_TRUST_PROXY_HEADERS",
            "KRAB_TRUSTED_PROXY_HOPS",
            "KRAB_RATE_LIMIT_CAPACITY",
            "KRAB_RATE_LIMIT_REFILL_PER_SEC",
            "KRAB_RATE_LIMIT_FAIL_OPEN",
            "KRAB_HTTP_REQUEST_TIMEOUT_SECS",
            "KRAB_HTTP_MAX_CONCURRENCY",
            "KRAB_PROTOCOL_TENANT_HINT_UNTRUSTED",
        ] {
            std::env::remove_var(key);
        }

        // Keep auth-focused tests deterministic by preventing global request
        // limiter interference when many tests run in one process.
        std::env::set_var("KRAB_ENVIRONMENT", "dev");
        std::env::set_var("KRAB_RATE_LIMIT_CAPACITY", "100000");
        std::env::set_var("KRAB_RATE_LIMIT_REFILL_PER_SEC", "100000");
        std::env::set_var("KRAB_RATE_LIMIT_FAIL_OPEN", "true");
        std::env::set_var("KRAB_TRUST_PROXY_HEADERS", "true");
    }

    fn test_app_with_state(state: TestState) -> Router {
        let app = Router::new()
            .route("/protected", axum::routing::get(|| async { "ok" }))
            .route("/api/admin/audit", axum::routing::get(|| async { "admin" }))
            .route(
                "/api/tenants/{tenant_id}/users",
                axum::routing::get(|| async { "tenant" }),
            );

        apply_common_http_layers(app, state.clone()).with_state(state)
    }

    fn test_app() -> Router {
        test_app_with_state(TestState {
            runtime: RuntimeState::new(),
        })
    }

    fn test_app_and_state() -> (Router, TestState) {
        let state = TestState {
            runtime: RuntimeState::new(),
        };
        (test_app_with_state(state.clone()), state)
    }

    fn generate_token(claims: Value) -> String {
        let key = b"secret";
        encode(&Header::default(), &claims, &EncodingKey::from_secret(key)).unwrap()
    }

    fn generate_token_with_kid(kid: &str, claims: Value, secret: &[u8]) -> String {
        let header = Header {
            kid: Some(kid.to_string()),
            ..Default::default()
        };
        encode(&header, &claims, &EncodingKey::from_secret(secret)).unwrap()
    }

    #[tokio::test]
    #[serial]
    async fn test_expired_token() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");

        let app = test_app();
        let claims = json!({
            "sub": "user",
            "exp": 1000000000 // Past timestamp
        });
        let token = generate_token(claims);

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.1")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    #[serial]
    async fn test_wrong_issuer() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");
        std::env::set_var("KRAB_OIDC_ISSUER", "correct-issuer");

        let app = test_app();
        let claims = json!({
            "sub": "user",
            "iss": "wrong-issuer",
            "exp": 9999999999i64
        });
        let token = generate_token(claims);

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.2")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    #[serial]
    async fn test_wrong_audience() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");
        std::env::set_var("KRAB_OIDC_AUDIENCE", "correct-aud");

        let app = test_app();
        let claims = json!({
            "sub": "user",
            "aud": "wrong-aud",
            "exp": 9999999999i64
        });
        let token = generate_token(claims);

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.3")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    #[serial]
    async fn test_missing_required_scope() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");
        std::env::set_var("KRAB_AUTH_REQUIRED_SCOPES", "read:data");

        let app = test_app();
        let claims = json!({
            "sub": "user",
            "scope": "other:scope",
            "exp": 9999999999i64
        });
        let token = generate_token(claims);

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.4")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    #[serial]
    async fn test_revoked_key() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        // We set keys JSON where 'kid1' is valid but we sign with 'kid2' which is not in the set
        std::env::set_var("KRAB_JWT_KEYS_JSON", r#"{"kid1": "secret1"}"#);

        let app = test_app();

        let claims = json!({
            "sub": "user",
            "exp": 9999999999i64
        });

        // Sign with a secret that corresponds to kid2, but kid2 is not in the trusted set
        let token = encode(
            &Header::default(),
            &claims,
            &EncodingKey::from_secret(b"secret2"),
        )
        .unwrap();

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.5")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        // Should fail because kid2 is not found in loaded keys (effectively revoked/unknown)
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    #[serial]
    async fn test_multi_provider_jwks_selection() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var(
            "KRAB_JWT_PROVIDERS_JSON",
            r#"[
                {"name":"provider-a","issuer":"iss-a","audience":"aud-a","keys":{"kid-a":"secret-a"}},
                {"name":"provider-b","issuer":"iss-b","audience":"aud-b","keys":{"kid-b":"secret-b"}}
            ]"#,
        );

        let app = test_app();
        let claims = json!({
            "sub": "user",
            "iss": "iss-b",
            "aud": "aud-b",
            "exp": 9999999999i64
        });
        let token = generate_token_with_kid("kid-b", claims, b"secret-b");

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.6")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    #[serial]
    async fn test_tenant_path_mismatch_is_denied() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");
        std::env::set_var("KRAB_AUTH_REQUIRE_TENANT_MATCH", "true");

        let app = test_app();
        let claims = json!({
            "sub": "user",
            "tenant_id": "tenant-a",
            "exp": 9999999999i64
        });
        let token = generate_token(claims);

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/api/tenants/tenant-b/users")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.7")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    #[serial]
    async fn test_shared_jwt_validation_reads_secret_file() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");

        let secret_path = std::env::current_dir()
            .expect("current dir should resolve")
            .join(format!(
                "krab_test_jwt_secret_{}_{}.txt",
                std::process::id(),
                1
            ));
        std::fs::write(&secret_path, "secret\n").expect("secret file should be written");
        std::env::set_var(
            "KRAB_JWT_SECRET_FILE",
            secret_path.to_string_lossy().to_string(),
        );

        let app = test_app();
        let token = generate_token(json!({
            "sub": "user",
            "exp": 9999999999i64
        }));

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.9")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);

        std::env::remove_var("KRAB_JWT_SECRET_FILE");
        let _ = std::fs::remove_file(secret_path);
    }

    #[tokio::test]
    #[serial]
    async fn test_refresh_token_is_rejected_for_route_auth() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");

        let app = test_app();
        let token = generate_token(json!({
            "sub": "user",
            "token_use": "refresh",
            "jti": "refresh-jti",
            "exp": 9999999999i64
        }));

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.10")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    #[serial]
    async fn test_revoked_access_token_is_rejected() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");

        let (app, state) = test_app_and_state();
        state
            .runtime
            .store
            .set("auth:revoked:access-jti", "1", Duration::from_secs(60))
            .await
            .expect("revocation marker should be stored");

        let token = generate_token(json!({
            "sub": "user",
            "token_use": "access",
            "jti": "access-jti",
            "exp": 9999999999i64
        }));

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.11")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    #[serial]
    async fn test_hs256_is_allowed_in_non_dev_when_explicitly_allowlisted() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_ENVIRONMENT", "prod");
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");
        std::env::set_var("KRAB_JWT_ALLOWED_ALGS", "HS256");

        let app = test_app();
        let token = generate_token(json!({
            "sub": "user",
            "exp": 9999999999i64
        }));

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.12")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    #[serial]
    async fn test_route_policy_requires_composed_scope() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");
        std::env::set_var(
            "KRAB_AUTH_ROUTE_POLICIES_JSON",
            r#"[{"prefix":"/api/admin","all_scopes":["audit.read"]}]"#,
        );

        let app = test_app();
        let claims = json!({
            "sub": "user",
            "scope": "users.read",
            "exp": 9999999999i64
        });
        let token = generate_token(claims);

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/api/admin/audit")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.8")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    /// A typo in `KRAB_AUTH_ROUTE_POLICIES_JSON` used to parse to an empty
    /// policy set — every configured restriction silently vanished, fail-open.
    /// A configured-but-unparseable policy set must reject the request.
    #[tokio::test]
    #[serial]
    async fn test_malformed_route_policy_json_fails_closed() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");
        std::env::set_var(
            "KRAB_AUTH_ROUTE_POLICIES_JSON",
            // Trailing comma makes this invalid JSON. The prefix deliberately
            // does not match the request path: the parse failure alone must
            // reject, before any prefix filtering.
            r#"[{"prefix":"/api/reports","all_scopes":["audit.read"],}]"#,
        );

        let app = test_app();
        let claims = json!({
            "sub": "user",
            "scope": "audit.read",
            "exp": 9999999999i64
        });
        let token = generate_token(claims);

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.8")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    /// `service_auth_middleware` reads the `AuthContext` extension that
    /// `auth_middleware` inserts. The layers used to run in the wrong order
    /// (scope check before auth), so a request with a perfectly valid token
    /// carrying the service scope still got 403 on every `/internal` route.
    /// This drives a request through the full `apply_common_http_layers`
    /// stack, not a hand-assembled router, so the real ordering is what is
    /// under test.
    #[tokio::test]
    #[serial]
    async fn test_internal_route_reachable_with_service_scope() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");

        let state = TestState {
            runtime: RuntimeState::new(),
        };
        let app = apply_common_http_layers(
            Router::new().route(
                "/internal/replicate",
                axum::routing::get(|| async { "internal-ok" }),
            ),
            state.clone(),
        )
        .with_state(state.clone());

        let scope = state.runtime.service_auth_scope.clone();
        let token = generate_token(json!({
            "sub": "service-caller",
            "scope": scope,
            "exp": 9999999999i64
        }));

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/internal/replicate")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.30")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(
            response.status(),
            StatusCode::OK,
            "a valid token carrying the service scope must reach /internal routes"
        );
    }

    /// The service-scope gate must still hold: a token that authenticates but
    /// lacks the service scope is 403 on `/internal` routes.
    #[tokio::test]
    #[serial]
    async fn test_internal_route_forbidden_without_service_scope() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");

        let state = TestState {
            runtime: RuntimeState::new(),
        };
        let app = apply_common_http_layers(
            Router::new().route(
                "/internal/replicate",
                axum::routing::get(|| async { "internal-ok" }),
            ),
            state.clone(),
        )
        .with_state(state);

        let token = generate_token(json!({
            "sub": "user",
            "scope": "users.read",
            "exp": 9999999999i64
        }));

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/internal/replicate")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.31")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    /// An allowlist mixing HMAC with asymmetric families is the algorithm
    /// confusion footgun; the request path must fail closed rather than
    /// verify anything under it.
    #[tokio::test]
    #[serial]
    async fn test_mixed_algorithm_family_allowlist_fails_closed() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");
        std::env::set_var("KRAB_JWT_ALLOWED_ALGS", "HS256,RS256");

        let app = test_app();
        let token = generate_token(json!({
            "sub": "user",
            "exp": 9999999999i64
        }));

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.40")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
    }

    /// `/metrics` sits on the default open-path list for backward
    /// compatibility, but operators must be able to close it:
    /// `KRAB_AUTH_OPEN_PATHS` replaces the whole list when set.
    #[tokio::test]
    #[serial]
    async fn test_open_paths_env_can_close_metrics() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");
        std::env::set_var("KRAB_AUTH_OPEN_PATHS", "/health,/ready");

        let app = test_app();
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/metrics")
                    .header("x-forwarded-for", "10.10.0.50")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(
            response.status(),
            StatusCode::UNAUTHORIZED,
            "with an explicit open-path list omitting it, /metrics must require auth"
        );
    }

    fn multi_protocol_config() -> crate::protocol::ProtocolConfig {
        crate::protocol::ProtocolConfig {
            exposure_mode: crate::protocol::ExposureMode::Multi,
            enabled_protocols: vec![
                crate::protocol::ProtocolKind::Rest,
                crate::protocol::ProtocolKind::Graphql,
                crate::protocol::ProtocolKind::Rpc,
            ],
            default_protocol: crate::protocol::ProtocolKind::Rest,
            topology: crate::protocol::DeploymentTopology::SingleService,
            policy: crate::protocol::ProtocolPolicy::default(),
            allow_runtime_switch_header: false,
        }
    }

    /// A route family whose protocol is disabled used to pass through the
    /// protocol middleware unresolved, exposing the disabled surface. It must
    /// now be rejected with PROTOCOL_NOT_SUPPORTED.
    #[tokio::test]
    #[serial]
    async fn test_disabled_route_family_is_rejected() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");

        let config = crate::protocol::ProtocolConfig {
            exposure_mode: crate::protocol::ExposureMode::Single,
            enabled_protocols: vec![crate::protocol::ProtocolKind::Rest],
            default_protocol: crate::protocol::ProtocolKind::Rest,
            topology: crate::protocol::DeploymentTopology::SingleService,
            policy: crate::protocol::ProtocolPolicy::default(),
            allow_runtime_switch_header: false,
        };
        let state = TestState {
            runtime: RuntimeState::new().with_protocol_config(config),
        };
        let app = apply_common_http_layers(
            Router::new().route("/api/v1/graphql", axum::routing::post(|| async { "gql" })),
            state.clone(),
        )
        .with_state(state);

        let token = generate_token(json!({
            "sub": "user",
            "exp": 9999999999i64
        }));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/api/v1/graphql")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.60")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(
            response.status(),
            StatusCode::BAD_REQUEST,
            "a disabled route family must be rejected, not passed through"
        );
        let body = axum::body::to_bytes(response.into_body(), 64 * 1024)
            .await
            .unwrap();
        let parsed: Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(
            parsed.get("code").and_then(|v| v.as_str()),
            Some("PROTOCOL_NOT_SUPPORTED")
        );
    }

    /// Protocol resolution now runs INSIDE auth (it needs AuthContext for
    /// tenant policy), while metrics stays outside auth. Metrics must still
    /// label requests with the resolved protocol, learned from the response
    /// extension the protocol middleware mirrors back.
    #[tokio::test]
    #[serial]
    async fn test_metrics_label_resolved_protocol_after_reorder() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");

        let state = TestState {
            runtime: RuntimeState::new().with_protocol_config(multi_protocol_config()),
        };
        let app = apply_common_http_layers(
            Router::new().route("/api/v1/graphql", axum::routing::post(|| async { "gql" })),
            state.clone(),
        )
        .with_state(state.clone());

        let token = generate_token(json!({
            "sub": "user",
            "exp": 9999999999i64
        }));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/api/v1/graphql")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.61")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            response
                .headers()
                .get("x-krab-protocol")
                .and_then(|v| v.to_str().ok()),
            Some("graphql")
        );
        // Index 1 is graphql; index 3 is "unknown", which is where the count
        // would land if metrics could no longer see the resolved protocol.
        assert_eq!(
            state.runtime.protocol_request_totals[1].load(std::sync::atomic::Ordering::Relaxed),
            1,
            "metrics must label the request as graphql"
        );
        assert_eq!(
            state.runtime.protocol_request_totals[3].load(std::sync::atomic::Ordering::Relaxed),
            0,
            "the request must not be counted as protocol=unknown"
        );
    }

    /// The 429 from the global rate limiter must carry the new
    /// `rate_limited` wire category.
    #[tokio::test]
    #[serial]
    async fn test_rate_limited_response_body_category() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");
        std::env::set_var("KRAB_RATE_LIMIT_CAPACITY", "1");
        std::env::set_var("KRAB_RATE_LIMIT_REFILL_PER_SEC", "1");

        let app = test_app();

        // Capacity 1 and a 1-second window: of three back-to-back requests
        // from the same IP, at least two share a window, so at least one is
        // rate limited even if a window boundary is crossed mid-test.
        let mut limited_body = None;
        for _ in 0..3 {
            let response = app
                .clone()
                .oneshot(
                    Request::builder()
                        .uri("/health")
                        .header("x-forwarded-for", "10.10.9.9")
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();
            if response.status() == StatusCode::TOO_MANY_REQUESTS {
                let body = axum::body::to_bytes(response.into_body(), 64 * 1024)
                    .await
                    .unwrap();
                limited_body = Some(body);
                break;
            }
        }

        let body = limited_body.expect("one of three requests must be rate limited");
        let parsed: Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(
            parsed.get("category").and_then(|v| v.as_str()),
            Some("rate_limited")
        );
        assert_eq!(
            parsed.get("code").and_then(|v| v.as_str()),
            Some("TOO_MANY_REQUESTS")
        );
    }

    /// A handler that overruns `KRAB_HTTP_REQUEST_TIMEOUT_SECS` must produce
    /// a timeout status, and the shed response must still pass through the
    /// security-headers layer.
    #[tokio::test]
    #[serial]
    async fn test_request_timeout_produces_408_with_security_headers() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");
        std::env::set_var("KRAB_AUTH_OPEN_PATHS", "/slow");
        std::env::set_var("KRAB_HTTP_REQUEST_TIMEOUT_SECS", "1");

        let state = TestState {
            runtime: RuntimeState::new(),
        };
        let app = apply_common_http_layers(
            Router::new().route(
                "/slow",
                axum::routing::get(|| async {
                    tokio::time::sleep(Duration::from_secs(5)).await;
                    "too-late"
                }),
            ),
            state.clone(),
        )
        .with_state(state);

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/slow")
                    .header("x-forwarded-for", "10.10.0.62")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::REQUEST_TIMEOUT);
        assert_eq!(
            response
                .headers()
                .get("x-content-type-options")
                .and_then(|v| v.to_str().ok()),
            Some("nosniff"),
            "timeout responses must still pass through the security-headers layer"
        );
    }

    /// With `KRAB_HTTP_MAX_CONCURRENCY=1`, two concurrent requests to a slow
    /// handler are serialized by the concurrency limit.
    #[tokio::test]
    #[serial]
    async fn test_concurrency_limit_serializes_requests() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");
        std::env::set_var("KRAB_AUTH_OPEN_PATHS", "/slow");
        std::env::set_var("KRAB_HTTP_MAX_CONCURRENCY", "1");

        let state = TestState {
            runtime: RuntimeState::new(),
        };
        let app = apply_common_http_layers(
            Router::new().route(
                "/slow",
                axum::routing::get(|| async {
                    tokio::time::sleep(Duration::from_millis(300)).await;
                    "done"
                }),
            ),
            state.clone(),
        )
        .with_state(state);

        let request = |ip: &'static str| {
            let app = app.clone();
            async move {
                app.oneshot(
                    Request::builder()
                        .uri("/slow")
                        .header("x-forwarded-for", ip)
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap()
            }
        };

        let started = std::time::Instant::now();
        let (first, second) = tokio::join!(request("10.10.0.63"), request("10.10.0.64"));
        let elapsed = started.elapsed();

        assert_eq!(first.status(), StatusCode::OK);
        assert_eq!(second.status(), StatusCode::OK);
        assert!(
            elapsed >= Duration::from_millis(550),
            "with max concurrency 1 the two 300ms requests must run serially, took {elapsed:?}"
        );
    }

    /// The JWT verifier cache is built once per `RuntimeState`: rotating the
    /// env secret mid-flight must not affect an existing state (no
    /// per-request provider reload), while a freshly built state picks up
    /// the new secret.
    #[tokio::test]
    #[serial]
    async fn test_jwt_verifier_cache_reused_across_requests() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");

        let (app, _state) = test_app_and_state();
        let token = generate_token(json!({
            "sub": "user",
            "exp": 9999999999i64
        }));

        let response = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.65")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);

        // Rotate the env secret. The existing state's cache must keep
        // verifying with the material it was built from.
        std::env::set_var("KRAB_JWT_SECRET", "rotated-secret");

        let response = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.66")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            response.status(),
            StatusCode::OK,
            "the cached provider must be reused; a per-request env reload would reject this token"
        );

        // A fresh state (fresh cache) sees the rotated secret and rejects
        // the old token.
        let fresh_app = test_app();
        let response = fresh_app
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("Authorization", format!("Bearer {}", token))
                    .header("x-forwarded-for", "10.10.0.67")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    #[serial]
    async fn test_metrics_stays_open_by_default() {
        let _guard = env_lock();
        reset_auth_env();
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_JWT_SECRET", "secret");

        let app = test_app();
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/metrics")
                    .header("x-forwarded-for", "10.10.0.51")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        // The test router has no /metrics route; the point is that the auth
        // layer passes the request through (404 from routing, not 401).
        assert_ne!(response.status(), StatusCode::UNAUTHORIZED);
    }
}