fraiseql-core 2.16.0

Core execution engine for FraiseQL v2 - Compiled GraphQL over SQL
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
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
//! Integration tests for the OIDC module covering providers and token validation logic.

#![allow(clippy::unwrap_used, clippy::panic)] // Reason: test code, panics acceptable
use crate::security::{
    errors::SecurityError,
    oidc::{providers::OidcConfig, token::OidcValidator},
};

// ============================================================================
// OidcConfig / provider factory tests
// ============================================================================

#[test]
fn test_oidc_config_default() {
    let config = OidcConfig::default();
    assert!(config.issuer.is_none());
    assert!(config.audience.is_none());
    // SECURITY: Cache TTL reduced to 5 minutes to prevent token cache poisoning
    assert_eq!(config.jwks_cache_ttl_secs, 300);
    assert_eq!(config.allowed_algorithms, vec!["RS256"]);
    assert_eq!(config.clock_skew_secs, 60);
    assert!(config.required);
}

#[test]
fn test_oidc_config_auth0() {
    let config = OidcConfig::auth0("my-tenant.auth0.com", "my-api");
    assert_eq!(config.issuer.as_deref(), Some("https://my-tenant.auth0.com/"));
    assert_eq!(config.audience, Some("my-api".to_string()));
}

#[test]
fn test_oidc_config_keycloak() {
    let config = OidcConfig::keycloak("https://keycloak.example.com", "myrealm", "myclient");
    assert_eq!(config.issuer.as_deref(), Some("https://keycloak.example.com/realms/myrealm"));
    assert_eq!(config.audience, Some("myclient".to_string()));
}

#[test]
fn test_oidc_config_okta() {
    let config = OidcConfig::okta("myorg.okta.com", "api://default");
    assert_eq!(config.issuer.as_deref(), Some("https://myorg.okta.com"));
    assert_eq!(config.audience, Some("api://default".to_string()));
}

#[test]
fn test_oidc_config_cognito() {
    let config = OidcConfig::cognito("us-east-1", "us-east-1_abc123", "client123");
    assert_eq!(
        config.issuer.as_deref(),
        Some("https://cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123")
    );
    assert_eq!(config.audience, Some("client123".to_string()));
}

#[test]
fn test_oidc_config_azure_ad() {
    let config = OidcConfig::azure_ad("tenant-id-123", "client-id-456");
    assert_eq!(
        config.issuer.as_deref(),
        Some("https://login.microsoftonline.com/tenant-id-123/v2.0")
    );
    assert_eq!(config.audience, Some("client-id-456".to_string()));
}

#[test]
fn test_oidc_config_google() {
    let config = OidcConfig::google("123456.apps.googleusercontent.com");
    assert_eq!(config.issuer.as_deref(), Some("https://accounts.google.com"));
    assert_eq!(config.audience, Some("123456.apps.googleusercontent.com".to_string()));
}

#[test]
fn test_oidc_config_validate_default_is_rejected() {
    // Default config has no issuer, no jwks_uri, and no audience — every guard
    // must reject it. The first guard reached is the issuer-less/no-jwks check.
    let config = OidcConfig::default();
    let result = config.validate();
    assert!(
        matches!(result, Err(SecurityError::SecurityConfigError(_))),
        "expected SecurityConfigError for an unconfigured OidcConfig, got: {result:?}"
    );
}

#[test]
fn test_oidc_config_validate_http_issuer() {
    let config = OidcConfig {
        issuer: Some("http://insecure.example.com".to_string()),
        ..Default::default()
    };
    let result = config.validate();
    assert!(result.is_err(), "expected http:// issuer to be rejected, got: {result:?}");
}

#[test]
fn test_oidc_config_validate_localhost_allowed() {
    let config = OidcConfig {
        issuer: Some("http://localhost:8080".to_string()),
        audience: Some("my-api".to_string()),
        ..Default::default()
    };
    config
        .validate()
        .unwrap_or_else(|e| panic!("expected localhost to be allowed: {e}"));
}

#[test]
fn test_oidc_config_validate_https_required() {
    let config = OidcConfig {
        issuer: Some("https://secure.example.com".to_string()),
        audience: Some("https://api.example.com".to_string()),
        ..Default::default()
    };
    config
        .validate()
        .unwrap_or_else(|e| panic!("expected https:// issuer to be valid: {e}"));
}

// ============================================================================
// Issuer-less mode: IdPs whose access tokens omit the `iss` claim (e.g. Hanko).
// `issuer` is optional, symmetric with `audience`; when unset the JWKS URI must
// be pinned (discovery is impossible without an issuer) and `iss` is not checked.
// ============================================================================

#[test]
fn issuerless_config_with_pinned_jwks_and_audience_is_valid() {
    let config = OidcConfig {
        issuer: None,
        audience: Some("relying-party-id".to_string()),
        jwks_uri: Some("https://hanko.example.com/.well-known/jwks.json".to_string()),
        ..Default::default()
    };
    config
        .validate()
        .unwrap_or_else(|e| panic!("issuer-less config with pinned jwks_uri must be valid: {e}"));
}

#[test]
fn issuerless_config_without_jwks_uri_is_rejected() {
    // Without an issuer, discovery cannot find the JWKS endpoint, so `jwks_uri`
    // must be pinned. Audience is set so this isolates the issuer/jwks_uri guard.
    let config = OidcConfig {
        issuer: None,
        audience: Some("relying-party-id".to_string()),
        jwks_uri: None,
        ..Default::default()
    };
    let result = config.validate();
    assert!(
        matches!(result, Err(SecurityError::SecurityConfigError(_))),
        "issuer-less config without a pinned jwks_uri must be rejected, got: {result:?}"
    );
}

#[test]
fn test_oidc_config_with_custom_cache_ttl() {
    let config = OidcConfig {
        issuer: Some("http://localhost:8080".to_string()),
        jwks_cache_ttl_secs: 600, // Custom 10-minute TTL
        ..Default::default()
    };
    assert_eq!(config.jwks_cache_ttl_secs, 600);
}

#[test]
fn test_oidc_config_default_cache_ttl_is_short() {
    let config = OidcConfig::default();
    assert!(
        config.jwks_cache_ttl_secs <= 300,
        "Default cache TTL should be short (≤ 300 seconds) to prevent token poisoning"
    );
}

// ============================================================================
// OidcValidator / token validation tests
// ============================================================================

/// A validator pinned to `jwks_uri`, in the shape the `[auth]` path builds.
///
/// Built through the real constructor: `OidcValidator` no longer has a cache of
/// its own to reach into, so a test cannot hand-assemble one — which is the point
/// (#1335). Seeding a private `jwks_cache` was how three tests asserted the
/// *shape* of a cache this crate no longer owns.
fn make_validator(jwks_uri: &str) -> OidcValidator {
    let config = OidcConfig {
        issuer: Some("https://idp.example.com".to_string()),
        audience: Some("fraiseql-test".to_string()),
        ..Default::default()
    };
    OidcValidator::with_jwks_uri(config, jwks_uri)
        .expect("an https or loopback jwks_uri is accepted")
}

/// A JWKS endpoint serving `kids`, counting every GET.
async fn jwks_serving(kids: &[&str]) -> wiremock::MockServer {
    use serde_json::json;
    use wiremock::{
        Mock, MockServer, ResponseTemplate,
        matchers::{method, path},
    };

    let keys: Vec<serde_json::Value> = kids
        .iter()
        .map(|kid| json!({ "kty": "RSA", "kid": kid, "n": TEST_RSA_N, "e": TEST_RSA_E }))
        .collect();
    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path(JWKS_FIXTURE_PATH))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "keys": keys })))
        .mount(&mock)
        .await;
    mock
}

/// Where every fixture publisher in this file serves its keys.
const JWKS_FIXTURE_PATH: &str = "/.well-known/jwks.json";

/// How many times a fixture publisher was asked for its keys.
async fn jwks_fetches(mock: &wiremock::MockServer) -> usize {
    mock.received_requests()
        .await
        .expect("the fixture publisher records its requests")
        .len()
}

// ============================================================================
// #1335: the JWKS cache moved, and these are the seams that stayed
// ============================================================================
//
// What used to be here: three `detect_key_rotation` cases, two `find_key` cases,
// a `CachedJwks::is_expired` case that slept 1.1 s, a JWK/JWKS deserialisation
// pair, and three "sentinels" that compared `MAX + 1 > MAX` **in the test body**
// and so pinned nothing in the code at all.
//
// Every one of those described the cache's internals, and the cache is now
// `fraiseql_jwks` — one implementation instead of the two that had drifted, with
// each of those properties exercised there against the code that runs:
// `a_withdrawn_key_is_reported_as_a_rotation_and_an_added_one_is_not`,
// `a_key_is_selected_by_kid_and_only_by_kid`,
// `an_expired_set_is_not_served_even_while_the_cooldown_holds`,
// `a_refetch_that_drops_a_key_stops_that_key_verifying`,
// `an_oversized_key_set_is_refused_before_it_is_parsed` and
// `a_key_set_exactly_at_the_size_cap_is_accepted`.
//
// What stays here is what is genuinely this crate's: that the operator's two
// controls reach the shared client. The refetch bound is measured from this side
// too, in `mod jwks_refetch_bound` at the end of this file — from the caller that
// #1335 measured, because the `alg`-ordering half of the defect is invisible from
// anywhere else.

#[tokio::test]
async fn the_operators_forced_refresh_reaches_the_provider() {
    let mock = jwks_serving(&["rotated_in_kid"]).await;
    let validator = make_validator(&format!("{}{JWKS_FIXTURE_PATH}", mock.uri()));

    let count = validator.refresh_jwks().await.expect("force refresh should succeed");
    assert_eq!(count, 1, "refresh_jwks returns the number of keys the provider now serves");

    // This is the operator's response to a known key compromise, so the refetch
    // cooldown — which the call above has just armed — must not refuse it.
    let again = validator.refresh_jwks().await.expect("and again, immediately");
    assert_eq!(again, 1, "a second forced refresh is not rate-limited");
    assert_eq!(jwks_fetches(&mock).await, 2, "both refreshes reached the provider");
}

#[tokio::test]
async fn invalidating_makes_the_very_next_validation_refetch() {
    let mock = jwks_serving(&["compromised_kid"]).await;
    let validator = make_validator(&format!("{}{JWKS_FIXTURE_PATH}", mock.uri()));

    validator.issuers[0]
        .get_decoding_key("compromised_kid")
        .await
        .expect("published");
    assert_eq!(jwks_fetches(&mock).await, 1);

    // The flush has to clear the cooldown as well as the keys. Dropping only the
    // keys would answer the operator's "stop trusting these" by refusing every
    // token until the cooldown lapsed, rather than by fetching.
    validator.invalidate_jwks_cache();
    validator.issuers[0]
        .get_decoding_key("compromised_kid")
        .await
        .expect("re-fetched");
    assert_eq!(
        jwks_fetches(&mock).await,
        2,
        "the flush must make the next validation fetch, not merely stop answering"
    );
}

#[test]
fn a_jwks_uri_that_could_never_be_fetched_refuses_the_validator() {
    // It used to be stored unexamined, so this built a validator that refused
    // every token at its first delivery instead of refusing to exist. The sibling
    // cache in `fraiseql_auth` had always checked at construction (#1335).
    let config = OidcConfig {
        audience: Some("fraiseql-test".to_string()),
        ..Default::default()
    };
    for uri in ["not a url", "http://idp.example.com/jwks", "ftp://idp/jwks"] {
        let error = OidcValidator::with_jwks_uri(config.clone(), uri)
            .err()
            .unwrap_or_else(|| panic!("{uri} must be refused at construction"));
        assert!(
            matches!(error, SecurityError::SecurityConfigError(_)),
            "and refused as the operator's configuration error: {error:?}"
        );
    }
}

// ============================================================================
// S22-H1: OIDC discovery response size cap
// ============================================================================

#[tokio::test]
async fn oidc_discovery_oversized_response_is_rejected() {
    use wiremock::{
        Mock, MockServer, ResponseTemplate,
        matchers::{method, path},
    };

    use crate::security::oidc::token::MAX_DISCOVERY_RESPONSE_BYTES;

    let mock = MockServer::start().await;

    // Serve a body that exceeds the cap
    let oversized_body = vec![b'x'; MAX_DISCOVERY_RESPONSE_BYTES + 1];
    Mock::given(method("GET"))
        .and(path("/.well-known/openid-configuration"))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(oversized_body))
        .mount(&mock)
        .await;

    let config = OidcConfig {
        issuer: Some(mock.uri()),
        audience: Some("test-audience".to_string()),
        ..Default::default()
    };
    let result = OidcValidator::new(config).await;
    assert!(result.is_err(), "oversized discovery response must be rejected");
    let msg = result.err().unwrap().to_string();
    assert!(msg.contains("too large"), "error must mention size limit: {msg}");
}

#[tokio::test]
async fn oidc_discovery_within_size_limit_proceeds_to_parse() {
    use wiremock::{
        Mock, MockServer, ResponseTemplate,
        matchers::{method, path},
    };

    let mock = MockServer::start().await;

    // A small (invalid JSON) body — size check passes, JSON parse fails gracefully
    Mock::given(method("GET"))
        .and(path("/.well-known/openid-configuration"))
        .respond_with(ResponseTemplate::new(200).set_body_string("not json"))
        .mount(&mock)
        .await;

    let config = OidcConfig {
        issuer: Some(mock.uri()),
        audience: Some("test-audience".to_string()),
        ..Default::default()
    };
    let result = OidcValidator::new(config).await;
    // Must fail with a JSON parse error, NOT a size error
    assert!(result.is_err(), "expected JSON parse failure for 'not json' body");
    let msg = result.err().unwrap().to_string();
    assert!(
        !msg.contains("too large"),
        "small body must not trigger size limit error: {msg}"
    );
}

// ============================================================================
// with_jwks_uri: what it keeps from the config it is handed
// ============================================================================

/// The positive counterweight to
/// [`a_jwks_uri_that_could_never_be_fetched_refuses_the_validator`]: a usable URI
/// builds a validator that still knows its issuer.
///
/// It replaces `with_jwks_uri_creates_validator_without_panicking`, whose subject
/// no longer exists — the constructor built an HTTP client it never used and
/// `expect`ed on it, and that client is gone (#1335). A test named for a panic
/// that cannot happen reads as coverage and is none.
#[test]
fn with_jwks_uri_keeps_the_configured_issuer() {
    let config = OidcConfig {
        issuer: Some("https://example.com".to_string()),
        jwks_uri: Some("https://example.com/.well-known/jwks.json".to_string()),
        ..Default::default()
    };
    let validator = OidcValidator::with_jwks_uri(config, "https://example.com/jwks")
        .expect("an https jwks_uri is accepted");
    assert_eq!(validator.issuer(), Some("https://example.com"));
}

// ============================================================================
// C14: JWT validation with real RSA keypair + wiremock JWKS endpoint
// ============================================================================

/// Test RSA private key (2048-bit, PEM PKCS#8 format).
/// Generated offline for testing only — not a real secret.
const TEST_RSA_PRIVATE_KEY_PEM: &str = "\
-----BEGIN PRIVATE KEY-----\n\
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCpf3bisHt/omOk\n\
VFHz/xb4p14mkeOerg4balAN0NznbieVbmnKwPjaaUfS9ZspwwCn9bLbIAaMIa3G\n\
oKqsSyfIITWNikiLp8ZnzaQH8JbgPLGaSfvy4w6dTp0cm9kL4te6KRk2J7owbVdp\n\
wW6nfFKyYwtNAJLSDg6aX7HCJ9QAoWT9rWC8lKvCodTwYvrf2T5PkLje8UDZYHx1\n\
WC+T9bal+0uKl+hP7j5NIM84Kh2W0KfMEOkMlGdQ6r8Y7aSuum2qYnH5K8gSoWlB\n\
Tn7393F+dbkTGmfGlo9k36flmIhu1eFWUgrYhG5HdKwofOI4HQEH9cuW+RHplrpt\n\
S6D9BJnRAgMBAAECggEAOz6FVGjxUcR15YtfddR0uAbwHrUhhWY7IhP/1URq4i2b\n\
glysd6UJlnX0F+WnDWrOgOadVIAWKcbf0ax4224NgqMw778k6kODUucK7YeHhOtR\n\
/KbdfKEmi49d1REYRVJNqxEQceBi8OhXBG0K+1m2IgoCejC4INmu+wB1xnJbZLhz\n\
B4uGLljKaqBssFIfsV4n+zcZcqesCTpsCcqcWURjcCWbWVBpqG7EkTFRtq35T/+c\n\
eQQTeH/UR/Bv9IHALJeTXQ41GYskZ4UPV0OMQ/bQtpojB6KZfTyz+CNn2iUeLNN6\n\
HXE8oAg3h4Unhajq8jT4XrWxY69HZhb/8zSeXRxEfQKBgQDdwvNmcG2GH1quysD+\n\
9qvO+w19lRun4AC886nQoaalrhaXAeK/GjS1D6vnUiJoN/rhkfI8mzhWdjHVgtql\n\
yJjKWb6C2bwTGsF1eDn1JTOZx+O4E/ToU/h1OzyAjrRTTPIiabSLNsCugwF45KHM\n\
ACEctgfUKVel/KAPeN0dkpPjEwKBgQDDqs/RZWj/FqJtj+SGBl6xcOL6F7L9d2hW\n\
0nZj/8/bgmRyvncO8A0YooqcJnMsYUWuhxdkkOH5f/q6FEuDrxJn9EdUxJNp4g4H\n\
65pcTJynQEF0QN/cc/1zR2H0h2TblS5mTW/Ya1GbLmu5KYshLjqDfKGDUgqpV73+\n\
6juxARHICwKBgQC3YgaLmL9JYVZJIwu0C+IJ2JvQVOS4z0ls94ZfK742Vh8CIyIR\n\
7CbX76y1LrubOWey71DFA4r0HOua54nN/HM1Kj+bz1hy5/ZBIPm0ml3wdlb+myo0\n\
kXPt5d1jZh8Cn6fAA2+0i8OMzHMEOPT/UMAREQqqTMHZVm46PTWExfiblwKBgQCH\n\
EYqTyaVJMZ6+cu4VdqA3bO3CJknwnlTwWihPr28U4FXmv4QAU8U2lD2KvSAUKrGn\n\
YKnNShYz3Rx/BzN5m4jhKcdzxJ7eIKX+4ayUum4JJloInh/qVkdHJKeB3VTKH5kA\n\
FcR3aN3UeZ7zGrJoHTlXOtljhWbGr0MAjUDXVx2nMQKBgAOyNRVrUMJiwamU2Gc1\n\
BapbzTBbUEbvWImcNE0hk7GyENBNhse6z/nIdp/DPMEJH8N45qpePcHGsgCBjS2M\n\
uwC0NSetnZwbndQWR409pzWQL9oeQL1vo0w+lHGhX7Ll7onkWgzJg7rPMc7swmoC\n\
AKX8L9QxXylh0eeeaWhGmS8M\n\
-----END PRIVATE KEY-----\n";

/// RSA modulus (n) as base64url, matching the test private key above.
const TEST_RSA_N: &str = "qX924rB7f6JjpFRR8_8W-KdeJpHjnq4OG2pQDdDc524nlW5pysD42mlH0vWbKcMAp_Wy2yAGjCGtxqCqrEsnyCE1jYpIi6fGZ82kB_CW4Dyxmkn78uMOnU6dHJvZC-LXuikZNie6MG1XacFup3xSsmMLTQCS0g4Oml-xwifUAKFk_a1gvJSrwqHU8GL639k-T5C43vFA2WB8dVgvk_W2pftLipfoT-4-TSDPOCodltCnzBDpDJRnUOq_GO2krrptqmJx-SvIEqFpQU5-9_dxfnW5ExpnxpaPZN-n5ZiIbtXhVlIK2IRuR3SsKHziOB0BB_XLlvkR6Za6bUug_QSZ0Q";

/// RSA public exponent (e) as base64url (65537 = 0x010001).
const TEST_RSA_E: &str = "AQAB";

#[tokio::test]
async fn validate_token_with_real_rsa_keypair_and_wiremock_jwks() {
    use jsonwebtoken::{Algorithm, EncodingKey, Header};
    use serde_json::json;
    use wiremock::{
        Mock, MockServer, ResponseTemplate,
        matchers::{method, path},
    };

    // ── 1. Start wiremock and derive issuer URL ──────────────────────
    let mock = MockServer::start().await;
    let port = mock.uri().rsplit(':').next().unwrap().to_string();
    let issuer = format!("http://localhost:{port}");
    let jwks_path = "/.well-known/jwks.json";

    // ── 2. Serve JWKS containing our test public key ─────────────────
    let jwks_body = json!({
        "keys": [{
            "kty": "RSA",
            "kid": "test-key-c14",
            "alg": "RS256",
            "use": "sig",
            "n":   TEST_RSA_N,
            "e":   TEST_RSA_E,
        }]
    });

    Mock::given(method("GET"))
        .and(path(jwks_path))
        .respond_with(ResponseTemplate::new(200).set_body_json(&jwks_body))
        .expect(1..)
        .mount(&mock)
        .await;

    // ── 3. Sign a JWT with the test private key ──────────────────────
    let now = chrono::Utc::now().timestamp();
    let claims = json!({
        "sub":   "user-42",
        "iss":   issuer,
        "aud":   "fraiseql-test-api",
        "exp":   now + 3600,
        "iat":   now,
        "scope": "read write admin",
    });

    let mut header = Header::new(Algorithm::RS256);
    header.kid = Some("test-key-c14".to_string());

    let encoding_key = EncodingKey::from_rsa_pem(TEST_RSA_PRIVATE_KEY_PEM.as_bytes())
        .expect("test RSA private key PEM should be valid");

    let token =
        jsonwebtoken::encode(&header, &claims, &encoding_key).expect("JWT encoding should succeed");

    // ── 4. Create OidcValidator pointing at wiremock ─────────────────
    let config = OidcConfig {
        issuer: Some(issuer.clone()),
        audience: Some("fraiseql-test-api".to_string()),
        allowed_algorithms: vec!["RS256".to_string()],
        ..Default::default()
    };
    let validator = OidcValidator::with_jwks_uri(config, &format!("{issuer}{jwks_path}"))
        .expect("a loopback http jwks_uri is accepted");

    // ── 5. Validate the token end-to-end ─────────────────────────────
    let user = validator.validate_token(&token).await.expect("token validation should succeed");

    assert_eq!(user.user_id.as_str(), "user-42");
    assert_eq!(user.scopes, vec!["read", "write", "admin"]);
    assert!(user.expires_at > chrono::Utc::now(), "token should not be expired yet");
}

#[tokio::test]
async fn validate_token_rejects_wrong_signing_key() {
    use jsonwebtoken::{Algorithm, EncodingKey, Header};
    use serde_json::json;
    use wiremock::{
        Mock, MockServer, ResponseTemplate,
        matchers::{method, path},
    };

    let mock = MockServer::start().await;
    let port = mock.uri().rsplit(':').next().unwrap().to_string();
    let issuer = format!("http://localhost:{port}");
    let jwks_path = "/.well-known/jwks.json";

    // Serve JWKS with the *correct* public key
    let jwks_body = json!({
        "keys": [{
            "kty": "RSA",
            "kid": "test-key-c14",
            "alg": "RS256",
            "use": "sig",
            "n":   TEST_RSA_N,
            "e":   TEST_RSA_E,
        }]
    });

    Mock::given(method("GET"))
        .and(path(jwks_path))
        .respond_with(ResponseTemplate::new(200).set_body_json(&jwks_body))
        .expect(1..)
        .mount(&mock)
        .await;

    let now = chrono::Utc::now().timestamp();
    let claims = json!({
        "sub": "user-42",
        "iss": issuer,
        "aud": "fraiseql-test-api",
        "exp": now + 3600,
        "iat": now,
    });

    let mut header = Header::new(Algorithm::RS256);
    header.kid = Some("test-key-c14".to_string());

    let encoding_key = EncodingKey::from_rsa_pem(TEST_RSA_PRIVATE_KEY_PEM.as_bytes()).unwrap();
    let token = jsonwebtoken::encode(&header, &claims, &encoding_key).unwrap();

    // Corrupt the signature portion (everything after the last '.')
    let last_dot = token.rfind('.').unwrap();
    let mut chars: Vec<char> = token.chars().collect();
    // Flip the last character of the signature
    chars[last_dot + 1] = if chars[last_dot + 1] == 'A' { 'B' } else { 'A' };
    let token: String = chars.into_iter().collect();

    let config = OidcConfig {
        issuer: Some(issuer.clone()),
        audience: Some("fraiseql-test-api".to_string()),
        allowed_algorithms: vec!["RS256".to_string()],
        ..Default::default()
    };
    let validator = OidcValidator::with_jwks_uri(config, &format!("{issuer}{jwks_path}"))
        .expect("a loopback http jwks_uri is accepted");

    let result = validator.validate_token(&token).await;
    assert!(result.is_err(), "corrupted signature must be rejected");
}

#[tokio::test]
async fn validate_token_rejects_expired_jwt() {
    use jsonwebtoken::{Algorithm, EncodingKey, Header};
    use serde_json::json;
    use wiremock::{
        Mock, MockServer, ResponseTemplate,
        matchers::{method, path},
    };

    let mock = MockServer::start().await;
    let port = mock.uri().rsplit(':').next().unwrap().to_string();
    let issuer = format!("http://localhost:{port}");
    let jwks_path = "/.well-known/jwks.json";

    let jwks_body = json!({
        "keys": [{
            "kty": "RSA",
            "kid": "test-key-c14",
            "alg": "RS256",
            "use": "sig",
            "n":   TEST_RSA_N,
            "e":   TEST_RSA_E,
        }]
    });

    Mock::given(method("GET"))
        .and(path(jwks_path))
        .respond_with(ResponseTemplate::new(200).set_body_json(&jwks_body))
        .expect(1..)
        .mount(&mock)
        .await;

    // Sign a JWT that is already expired (exp in the past, beyond clock skew)
    let now = chrono::Utc::now().timestamp();
    let claims = json!({
        "sub": "user-42",
        "iss": issuer,
        "aud": "fraiseql-test-api",
        "exp": now - 600, // expired 10 minutes ago (beyond 60s default skew)
        "iat": now - 4200,
    });

    let mut header = Header::new(Algorithm::RS256);
    header.kid = Some("test-key-c14".to_string());

    let encoding_key = EncodingKey::from_rsa_pem(TEST_RSA_PRIVATE_KEY_PEM.as_bytes()).unwrap();
    let token = jsonwebtoken::encode(&header, &claims, &encoding_key).unwrap();

    let config = OidcConfig {
        issuer: Some(issuer.clone()),
        audience: Some("fraiseql-test-api".to_string()),
        allowed_algorithms: vec!["RS256".to_string()],
        ..Default::default()
    };
    let validator = OidcValidator::with_jwks_uri(config, &format!("{issuer}{jwks_path}"))
        .expect("a loopback http jwks_uri is accepted");

    let result = validator.validate_token(&token).await;
    assert!(result.is_err(), "expired token must be rejected");
    assert!(
        matches!(result, Err(SecurityError::TokenExpired { .. })),
        "error should be TokenExpired, got: {result:?}"
    );
}

#[tokio::test]
async fn validate_token_rejects_wrong_audience() {
    use jsonwebtoken::{Algorithm, EncodingKey, Header};
    use serde_json::json;
    use wiremock::{
        Mock, MockServer, ResponseTemplate,
        matchers::{method, path},
    };

    let mock = MockServer::start().await;
    let port = mock.uri().rsplit(':').next().unwrap().to_string();
    let issuer = format!("http://localhost:{port}");
    let jwks_path = "/.well-known/jwks.json";

    let jwks_body = json!({
        "keys": [{
            "kty": "RSA",
            "kid": "test-key-c14",
            "alg": "RS256",
            "use": "sig",
            "n":   TEST_RSA_N,
            "e":   TEST_RSA_E,
        }]
    });

    Mock::given(method("GET"))
        .and(path(jwks_path))
        .respond_with(ResponseTemplate::new(200).set_body_json(&jwks_body))
        .expect(1..)
        .mount(&mock)
        .await;

    // Sign a JWT with a WRONG audience
    let now = chrono::Utc::now().timestamp();
    let claims = json!({
        "sub": "user-42",
        "iss": issuer,
        "aud": "wrong-audience",
        "exp": now + 3600,
        "iat": now,
    });

    let mut header = Header::new(Algorithm::RS256);
    header.kid = Some("test-key-c14".to_string());

    let encoding_key = EncodingKey::from_rsa_pem(TEST_RSA_PRIVATE_KEY_PEM.as_bytes()).unwrap();
    let token = jsonwebtoken::encode(&header, &claims, &encoding_key).unwrap();

    let config = OidcConfig {
        issuer: Some(issuer.clone()),
        audience: Some("fraiseql-test-api".to_string()),
        allowed_algorithms: vec!["RS256".to_string()],
        ..Default::default()
    };
    let validator = OidcValidator::with_jwks_uri(config, &format!("{issuer}{jwks_path}"))
        .expect("a loopback http jwks_uri is accepted");

    let result = validator.validate_token(&token).await;
    assert!(result.is_err(), "wrong audience must be rejected");
}

/// Issuer-less end-to-end: a Hanko-shaped access token that carries **no `iss`
/// claim** must validate when `issuer` is unset and the JWKS URI is pinned.
/// Signature (against the pinned JWKS) and `audience` still gate the token.
#[tokio::test]
async fn validate_token_without_iss_claim_accepted_when_issuer_unset() {
    use jsonwebtoken::{Algorithm, EncodingKey, Header};
    use serde_json::json;
    use wiremock::{
        Mock, MockServer, ResponseTemplate,
        matchers::{method, path},
    };

    let mock = MockServer::start().await;
    let jwks_path = "/.well-known/jwks.json";
    let jwks_body = json!({
        "keys": [{
            "kty": "RSA",
            "kid": "hanko-key",
            "alg": "RS256",
            "use": "sig",
            "n":   TEST_RSA_N,
            "e":   TEST_RSA_E,
        }]
    });
    Mock::given(method("GET"))
        .and(path(jwks_path))
        .respond_with(ResponseTemplate::new(200).set_body_json(&jwks_body))
        .expect(1..)
        .mount(&mock)
        .await;

    // Hanko 2.x access-token shape: sub/aud/exp/iat (+ session_id, email); no `iss`.
    let now = chrono::Utc::now().timestamp();
    let claims = json!({
        "sub":        "hanko-user-1",
        "aud":        ["relying-party-id"],
        "exp":        now + 3600,
        "iat":        now,
        "email":      "user@example.com",
        "session_id": "sess-123",
    });

    let mut header = Header::new(Algorithm::RS256);
    header.kid = Some("hanko-key".to_string());
    let encoding_key = EncodingKey::from_rsa_pem(TEST_RSA_PRIVATE_KEY_PEM.as_bytes()).unwrap();
    let token = jsonwebtoken::encode(&header, &claims, &encoding_key).unwrap();

    // Issuer-less config: no `issuer`, pinned `jwks_uri`, mandatory `audience`.
    let config = OidcConfig {
        issuer: None,
        audience: Some("relying-party-id".to_string()),
        jwks_uri: Some(format!("{}{jwks_path}", mock.uri())),
        allowed_algorithms: vec!["RS256".to_string()],
        ..Default::default()
    };
    let validator = OidcValidator::with_jwks_uri(config, &format!("{}{jwks_path}", mock.uri()))
        .expect("a loopback http jwks_uri is accepted");

    let user = validator
        .validate_token(&token)
        .await
        .expect("issuer-less token (no `iss`) must validate against a pinned JWKS");
    assert_eq!(user.user_id.as_str(), "hanko-user-1");
    assert_eq!(user.email.as_deref(), Some("user@example.com"));
}

/// Security boundary: when an `issuer` **is** configured, a token that omits
/// `iss` must still be rejected — setting an issuer keeps `iss` mandatory
/// (jsonwebtoken's `set_issuer` requires the claim). This pins that the
/// issuer-less relaxation only applies when the operator opts out of `iss`.
#[tokio::test]
async fn validate_token_missing_iss_rejected_when_issuer_set() {
    use jsonwebtoken::{Algorithm, EncodingKey, Header};
    use serde_json::json;
    use wiremock::{
        Mock, MockServer, ResponseTemplate,
        matchers::{method, path},
    };

    let mock = MockServer::start().await;
    let jwks_path = "/.well-known/jwks.json";
    let jwks_body = json!({
        "keys": [{
            "kty": "RSA",
            "kid": "with-issuer-key",
            "alg": "RS256",
            "use": "sig",
            "n":   TEST_RSA_N,
            "e":   TEST_RSA_E,
        }]
    });
    Mock::given(method("GET"))
        .and(path(jwks_path))
        .respond_with(ResponseTemplate::new(200).set_body_json(&jwks_body))
        // A token without `iss` names no issuer, so it is refused before any key
        // set is consulted (#1400): it costs the provider nothing.
        .expect(0)
        .mount(&mock)
        .await;

    // Token omits `iss`.
    let now = chrono::Utc::now().timestamp();
    let claims = json!({
        "sub": "user-42",
        "aud": "fraiseql-test-api",
        "exp": now + 3600,
        "iat": now,
    });
    let mut header = Header::new(Algorithm::RS256);
    header.kid = Some("with-issuer-key".to_string());
    let encoding_key = EncodingKey::from_rsa_pem(TEST_RSA_PRIVATE_KEY_PEM.as_bytes()).unwrap();
    let token = jsonwebtoken::encode(&header, &claims, &encoding_key).unwrap();

    // Issuer IS configured → `iss` is mandatory, so the token is rejected.
    let config = OidcConfig {
        issuer: Some("https://issuer.example.com".to_string()),
        audience: Some("fraiseql-test-api".to_string()),
        jwks_uri: Some(format!("{}{jwks_path}", mock.uri())),
        allowed_algorithms: vec!["RS256".to_string()],
        ..Default::default()
    };
    let validator = OidcValidator::with_jwks_uri(config, &format!("{}{jwks_path}", mock.uri()))
        .expect("a loopback http jwks_uri is accepted");

    let result = validator.validate_token(&token).await;
    assert!(
        result.is_err(),
        "a token missing `iss` must be rejected when an issuer is configured"
    );
}

mod audience_tests {
    #![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable

    use crate::security::oidc::*;

    #[test]
    fn test_audience_none() {
        let aud = Audience::None;
        assert!(!aud.contains("test"));
        assert!(aud.to_vec().is_empty());
    }

    #[test]
    fn test_audience_single() {
        let aud = Audience::Single("my-api".to_string());
        assert!(aud.contains("my-api"));
        assert!(!aud.contains("other"));
        assert_eq!(aud.to_vec(), vec!["my-api"]);
    }

    #[test]
    fn test_audience_multiple() {
        let aud = Audience::Multiple(vec!["api1".to_string(), "api2".to_string()]);
        assert!(aud.contains("api1"));
        assert!(aud.contains("api2"));
        assert!(!aud.contains("api3"));
        assert_eq!(aud.to_vec(), vec!["api1", "api2"]);
    }

    #[test]
    fn test_extra_claims_captures_namespaced_claim() {
        let claims_json = r#"{
            "sub": "user123",
            "exp": 1735689600,
            "https://myapp.com/role": "admin",
            "tenant_id": "acme-corp"
        }"#;

        let claims: JwtClaims = serde_json::from_str(claims_json).unwrap();
        assert_eq!(claims.extra.get("https://myapp.com/role"), Some(&serde_json::json!("admin")));
        assert_eq!(claims.extra.get("tenant_id"), Some(&serde_json::json!("acme-corp")));
    }

    #[test]
    fn test_named_claim_not_duplicated_in_extra() {
        // Named fields (sub, exp, email, etc.) must not appear in extra.
        let claims_json = r#"{
            "sub": "user123",
            "exp": 1735689600,
            "email": "user@example.com",
            "name": "Alice"
        }"#;

        let claims: JwtClaims = serde_json::from_str(claims_json).unwrap();
        assert_eq!(claims.email, Some(serde_json::json!("user@example.com")));
        assert!(!claims.extra.contains_key("email"), "named claim must not appear in extra");
        assert!(!claims.extra.contains_key("name"), "named claim must not appear in extra");
    }

    #[test]
    fn test_extra_claims_empty_when_no_unknowns() {
        let claims_json = r#"{"sub": "user123", "exp": 1735689600}"#;

        let claims: JwtClaims = serde_json::from_str(claims_json).unwrap();
        assert!(claims.extra.is_empty());
    }

    #[test]
    fn test_jwt_claims_deserialization() {
        let claims_json = r#"{
            "sub": "user123",
            "iss": "https://issuer.example.com",
            "aud": "my-api",
            "exp": 1735689600,
            "iat": 1735686000,
            "scope": "read write",
            "email": "user@example.com"
        }"#;

        let claims: JwtClaims = serde_json::from_str(claims_json).unwrap();
        assert_eq!(claims.sub, Some("user123".to_string()));
        assert_eq!(claims.iss, Some("https://issuer.example.com".to_string()));
        assert!(claims.aud.contains("my-api"));
        assert_eq!(claims.exp, Some(1_735_689_600));
        assert_eq!(claims.scope, Some("read write".to_string()));
    }

    #[test]
    fn test_jwt_claims_array_audience() {
        let claims_json = r#"{
            "sub": "user123",
            "aud": ["api1", "api2"],
            "exp": 1735689600
        }"#;

        let claims: JwtClaims = serde_json::from_str(claims_json).unwrap();
        assert!(claims.aud.contains("api1"));
        assert!(claims.aud.contains("api2"));
    }
}

mod discovery_document_tests {
    #![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable

    use crate::security::oidc::*;

    #[test]
    fn test_oidc_discovery_document_deserialization() {
        let doc_json = r#"{
            "issuer": "https://issuer.example.com",
            "jwks_uri": "https://issuer.example.com/.well-known/jwks.json",
            "authorization_endpoint": "https://issuer.example.com/authorize",
            "token_endpoint": "https://issuer.example.com/oauth/token",
            "id_token_signing_alg_values_supported": ["RS256", "RS384", "RS512"]
        }"#;

        let doc: OidcDiscoveryDocument = serde_json::from_str(doc_json).unwrap();
        assert_eq!(doc.issuer, "https://issuer.example.com");
        assert_eq!(doc.jwks_uri, "https://issuer.example.com/.well-known/jwks.json");
        assert_eq!(doc.id_token_signing_alg_values_supported.len(), 3);
    }

    /// The size cap is the shared client's own constant, re-exported rather than
    /// repeated, so this crate cannot come to hold a second copy of the number.
    ///
    /// The three tests that used to sit here compared `MAX + 1 > MAX` *in the test
    /// body*: they pinned the arithmetic of `>`, never the guard. Both sides of
    /// the real boundary are exercised against the fetch itself in
    /// `fraiseql_jwks`.
    #[test]
    fn the_size_cap_is_the_shared_clients_own_constant() {
        assert_eq!(MAX_JWKS_RESPONSE_BYTES, fraiseql_jwks::MAX_RESPONSE_BYTES);
    }
}

mod replay_cache_tests {
    #![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable

    use std::time::Duration;

    use async_trait::async_trait;

    use crate::security::oidc::*;

    #[tokio::test]
    async fn test_first_use_accepted() {
        let cache = ReplayCache::new(MemoryReplayCache::new());
        let result = cache.check_and_record("jti-abc", Duration::from_mins(15)).await;
        assert!(result.is_ok(), "first use should be accepted");
    }

    #[tokio::test]
    async fn test_replay_rejected() {
        let cache = ReplayCache::new(MemoryReplayCache::new());
        cache.check_and_record("jti-abc", Duration::from_mins(15)).await.unwrap();
        let result = cache.check_and_record("jti-abc", Duration::from_mins(15)).await;
        assert!(
            matches!(result, Err(ReplayCacheError::Replayed)),
            "second use of same jti should be rejected"
        );
    }

    #[tokio::test]
    async fn test_different_jtis_accepted_independently() {
        let cache = ReplayCache::new(MemoryReplayCache::new());
        cache.check_and_record("jti-1", Duration::from_mins(15)).await.unwrap();
        let result = cache.check_and_record("jti-2", Duration::from_mins(15)).await;
        assert!(result.is_ok(), "different jti should be accepted");
    }

    #[tokio::test]
    async fn test_fail_open_policy_on_backend_error() {
        struct AlwaysErrorBackend;

        #[async_trait]
        impl ReplayCacheBackend for AlwaysErrorBackend {
            async fn check_and_record(
                &self,
                _jti: &str,
                _ttl: Duration,
            ) -> Result<(), ReplayCacheError> {
                Err(ReplayCacheError::Backend("simulated error".to_string()))
            }
        }

        let cache = ReplayCache::new(AlwaysErrorBackend).with_policy(FailurePolicy::FailOpen);
        let result = cache.check_and_record("jti-xyz", Duration::from_mins(15)).await;
        assert!(result.is_ok(), "fail-open should accept on backend error");
    }

    #[tokio::test]
    async fn test_fail_closed_policy_on_backend_error() {
        struct AlwaysErrorBackend;

        #[async_trait]
        impl ReplayCacheBackend for AlwaysErrorBackend {
            async fn check_and_record(
                &self,
                _jti: &str,
                _ttl: Duration,
            ) -> Result<(), ReplayCacheError> {
                Err(ReplayCacheError::Backend("simulated error".to_string()))
            }
        }

        let cache = ReplayCache::new(AlwaysErrorBackend).with_policy(FailurePolicy::FailClosed);
        let result = cache.check_and_record("jti-xyz", Duration::from_mins(15)).await;
        assert!(result.is_err(), "fail-closed should reject on backend error");
    }

    #[tokio::test]
    async fn test_replay_counter_increments() {
        let before = jwt_replay_rejected_total();
        let cache = ReplayCache::new(MemoryReplayCache::new());
        cache.check_and_record("jti-counter", Duration::from_mins(15)).await.unwrap();
        let _ = cache.check_and_record("jti-counter", Duration::from_mins(15)).await;
        let after = jwt_replay_rejected_total();
        assert!(after > before, "replay counter should have incremented");
    }
}

// ============================================================================
// #1335: the JWKS refetch is bounded, and the algorithm allow-list runs first
// ============================================================================

/// Every request whose `kid` the cache does not hold used to make the server
/// fetch the `IdP`'s JWKS again: no negative cache, no cooldown between refetches,
/// no single-flight for concurrent misses, and the algorithm allow-list checked
/// *after* the key lookup (`token.rs` took `kid` and called `get_decoding_key`
/// before `get_algorithm`).
///
/// A `/graphql` request needs no credential to reach this code, so any anonymous
/// client could make the server issue one outbound HTTPS request per inbound
/// one. The consequence is not the amplification itself but what it turns into:
/// once the `IdP` throttles this server, a genuine key rotation cannot be fetched
/// and every user holding a new-`kid` token is refused — an authentication
/// outage produced by unauthenticated traffic.
///
/// # Why these count fetches through `validate_token`
///
/// `get_decoding_key` cannot see half the defect. The `alg` ordering is only
/// observable from the caller that does both things, and that caller is
/// `validate_token`. Counting at the mock rather than asserting on an internal
/// counter also keeps the suite honest across cycle A3, where this logic moves
/// into a shared primitive: what is pinned here is the number of requests the
/// *provider* sees, which is the property the issue is about.
mod jwks_refetch_bound {
    use std::time::Duration;

    use jsonwebtoken::{Algorithm, EncodingKey, Header};
    use serde_json::json;
    use wiremock::{
        Mock, MockServer, ResponseTemplate,
        matchers::{method, path},
    };

    use super::{OidcConfig, OidcValidator, TEST_RSA_E, TEST_RSA_N, TEST_RSA_PRIVATE_KEY_PEM};

    /// Where the fixture `IdP` publishes its keys.
    const JWKS_PATH: &str = "/.well-known/jwks.json";

    /// The one `kid` the fixture `IdP` publishes. Every token below names a
    /// different one, so each is a genuine cache miss.
    const PUBLISHED_KID: &str = "published-kid";

    /// How many deliveries one burst of unauthenticated traffic stands for.
    const BURST: usize = 20;

    /// A JWKS endpoint that publishes one RSA key and counts every GET.
    ///
    /// Mounted without `.expect(...)`: the count is read back with
    /// [`MockServer::received_requests`], because one of these tests asserts the
    /// endpoint is reached **zero** times and an unmet `expect` would panic on
    /// drop instead of failing the assertion that matters.
    async fn published_jwks(delay: Duration) -> MockServer {
        let mock = MockServer::start().await;
        let body = json!({
            "keys": [{
                "kty": "RSA",
                "kid": PUBLISHED_KID,
                "alg": "RS256",
                "use": "sig",
                "n":   TEST_RSA_N,
                "e":   TEST_RSA_E,
            }]
        });
        Mock::given(method("GET"))
            .and(path(JWKS_PATH))
            .respond_with(ResponseTemplate::new(200).set_body_json(&body).set_delay(delay))
            .mount(&mock)
            .await;
        mock
    }

    /// How many times the fixture `IdP` was asked for its keys.
    async fn fetches(mock: &MockServer) -> usize {
        mock.received_requests()
            .await
            .expect("the fixture JWKS server records its requests")
            .len()
    }

    /// A validator pinned to the fixture's JWKS, in the issuer-less mode #708
    /// added and #1335 measured against. `RS256` only, so the `HS256` token
    /// below is outside the allow-list.
    fn validator_for(mock: &MockServer) -> OidcValidator {
        let config = OidcConfig {
            issuer: None,
            audience: Some("fraiseql-1335".to_string()),
            allowed_algorithms: vec!["RS256".to_string()],
            ..Default::default()
        };
        let uri = format!("{}{JWKS_PATH}", mock.uri());
        OidcValidator::with_jwks_uri(config, &uri).expect("a loopback http jwks_uri is accepted")
    }

    /// Claims good enough to reach the key lookup: the point of every token here
    /// is its *header*, so the body only has to decode.
    fn claims() -> serde_json::Value {
        let now = chrono::Utc::now().timestamp();
        json!({ "sub": "anonymous-caller", "aud": "fraiseql-1335", "exp": now + 3600 })
    }

    /// A genuinely RS256-signed token naming `kid`. Signed with the fixture key,
    /// so the only thing wrong with it is that `kid` is not published — which is
    /// what an attacker sends, and what a legitimate client sends during a
    /// rotation the server has not yet seen.
    fn rs256_token(kid: &str) -> String {
        let mut header = Header::new(Algorithm::RS256);
        header.kid = Some(kid.to_string());
        let key = EncodingKey::from_rsa_pem(TEST_RSA_PRIVATE_KEY_PEM.as_bytes())
            .expect("the fixture RSA private key parses");
        jsonwebtoken::encode(&header, &claims(), &key).expect("the fixture token encodes")
    }

    /// An `HS256` token naming an unknown `kid`. `HS256` is not in
    /// `allowed_algorithms`, so this token is refused whatever key the `IdP`
    /// publishes — and must therefore cost no outbound request.
    fn hs256_token(kid: &str) -> String {
        let mut header = Header::new(Algorithm::HS256);
        header.kid = Some(kid.to_string());
        let key = EncodingKey::from_secret(b"not a key this server would ever accept");
        jsonwebtoken::encode(&header, &claims(), &key).expect("the fixture token encodes")
    }

    #[tokio::test]
    async fn many_distinct_unknown_kids_share_one_jwks_fetch() {
        let mock = published_jwks(Duration::ZERO).await;
        let validator = validator_for(&mock);

        for index in 0..BURST {
            let token = rs256_token(&format!("unknown-kid-{index}"));
            assert!(
                validator.validate_token(&token).await.is_err(),
                "a token signed by a key the `IdP` does not publish must be refused (kid \
                 unknown-kid-{index})"
            );
        }

        // Exactly one, not "at most one": the server has to look once to learn the
        // kid is unpublished, and an implementation that never looks could not pick
        // up a rotation at all.
        assert_eq!(
            fetches(&mock).await,
            1,
            "#1335: {BURST} requests with {BURST} distinct unknown kids must cost one JWKS \
             fetch, not one each — otherwise any anonymous caller sets the server's outbound \
             request rate, and the `IdP`'s throttling turns that into an authentication outage"
        );
    }

    #[tokio::test]
    async fn a_repeated_unknown_kid_is_remembered_as_unknown() {
        let mock = published_jwks(Duration::ZERO).await;
        let validator = validator_for(&mock);
        let token = rs256_token("unknown-kid-repeated");

        for _ in 0..BURST {
            assert!(
                validator.validate_token(&token).await.is_err(),
                "a token signed by a key the `IdP` does not publish must be refused"
            );
        }

        assert_eq!(
            fetches(&mock).await,
            1,
            "#1335: the same unknown kid {BURST} times must cost one JWKS fetch. A miss that \
             is never remembered is the cheapest possible amplification — one captured token \
             replayed is enough"
        );
    }

    #[tokio::test]
    async fn a_disallowed_algorithm_never_reaches_the_jwks_endpoint() {
        let mock = published_jwks(Duration::ZERO).await;
        let validator = validator_for(&mock);

        let token = hs256_token("unknown-kid-hs256");
        assert!(
            validator.validate_token(&token).await.is_err(),
            "HS256 is outside allowed_algorithms, so the token must be refused"
        );

        assert_eq!(
            fetches(&mock).await,
            0,
            "#1335: the algorithm allow-list must be checked BEFORE the key lookup. A token \
             this server would refuse on its header alone must not cost an outbound request"
        );
    }

    /// How many deliveries arrive together in the burst below.
    const CONCURRENT: usize = 8;

    #[tokio::test]
    async fn concurrent_unknown_kid_misses_collapse_onto_one_fetch() {
        // The response is delayed so every miss below is in flight before the
        // first fetch completes. Without that, a cooldown alone passes this test
        // while leaving concurrent misses unbounded — the fetches would merely be
        // serialised, and the test would agree for the wrong reason.
        let mock = published_jwks(Duration::from_millis(300)).await;
        let validator = validator_for(&mock);

        let tokens: Vec<String> =
            (0..CONCURRENT).map(|i| rs256_token(&format!("concurrent-kid-{i}"))).collect();
        let outcomes =
            futures::future::join_all(tokens.iter().map(|token| validator.validate_token(token)))
                .await;

        assert!(
            outcomes.iter().all(std::result::Result::is_err),
            "every token names an unpublished kid, so every one must be refused"
        );
        assert_eq!(
            fetches(&mock).await,
            1,
            "#1335: {CONCURRENT} concurrent misses must single-flight onto one JWKS fetch. A \
             cooldown alone does not give this — it is only consulted once a fetch has \
             finished, and these all start first"
        );
    }
}

// ============================================================================
// #1400: several trusted issuers, each with its own keys, chosen by `iss`
// ============================================================================

mod additional_issuers {
    use jsonwebtoken::{Algorithm, EncodingKey, Header};
    use serde_json::json;

    use super::{JWKS_FIXTURE_PATH, TEST_RSA_PRIVATE_KEY_PEM, jwks_fetches, jwks_serving};
    use crate::security::{
        errors::SecurityError,
        oidc::{
            providers::{OidcConfig, TrustedIssuer},
            token::OidcValidator,
        },
    };

    const IDP: &str = "https://idp.example.com";
    const EXCHANGE: &str = "https://exchange.example.com";

    /// Two issuers, each publishing its own key id at its own endpoint: the `IdP`
    /// (`idp-key`, audience `api`) and a token-exchange service (`exchange-key`,
    /// audience `api-exchange`). Both sign with the one test key, so only the kid
    /// and the issuer tell them apart — which is exactly what must keep them apart.
    async fn two_issuers() -> (OidcValidator, wiremock::MockServer, wiremock::MockServer) {
        let idp = jwks_serving(&["idp-key"]).await;
        let exchange = jwks_serving(&["exchange-key"]).await;
        let config = OidcConfig {
            issuer: Some(IDP.to_string()),
            audience: Some("api".to_string()),
            additional_issuers: vec![TrustedIssuer {
                issuer:               EXCHANGE.to_string(),
                audience:             Some("api-exchange".to_string()),
                additional_audiences: Vec::new(),
                allowed_algorithms:   vec!["RS256".to_string()],
                clock_skew_secs:      60,
                jwks_uri:             Some(format!("{}{JWKS_FIXTURE_PATH}", exchange.uri())),
                scope_claim:          "scope".to_string(),
                require_jti:          false,
            }],
            ..Default::default()
        };
        let validator =
            OidcValidator::with_jwks_uri(config, &format!("{}{JWKS_FIXTURE_PATH}", idp.uri()))
                .unwrap();
        (validator, idp, exchange)
    }

    fn token(kid: &str, iss: &str, aud: &str) -> String {
        let now = chrono::Utc::now().timestamp();
        let mut header = Header::new(Algorithm::RS256);
        header.kid = Some(kid.to_string());
        jsonwebtoken::encode(
            &header,
            &json!({ "sub": "u1", "iss": iss, "aud": aud, "exp": now + 600, "iat": now }),
            &EncodingKey::from_rsa_pem(TEST_RSA_PRIVATE_KEY_PEM.as_bytes()).unwrap(),
        )
        .unwrap()
    }

    #[tokio::test]
    async fn each_issuer_validates_its_own_tokens_and_the_principal_records_which() {
        let (validator, _idp, _exchange) = two_issuers().await;

        let user = validator.validate_token(&token("idp-key", IDP, "api")).await.unwrap();
        assert_eq!(user.extra_claims.get("iss"), Some(&json!(IDP)));

        let user = validator
            .validate_token(&token("exchange-key", EXCHANGE, "api-exchange"))
            .await
            .unwrap();
        assert_eq!(user.extra_claims.get("iss"), Some(&json!(EXCHANGE)));
    }

    /// An `iss` no configured issuer names is refused before any key set is
    /// consulted — it is never tried against every issuer's keys.
    #[tokio::test]
    async fn an_untrusted_issuer_is_refused_without_consulting_any_key_set() {
        let (validator, idp, exchange) = two_issuers().await;
        let result =
            validator.validate_token(&token("idp-key", "https://evil.example", "api")).await;
        assert!(matches!(result, Err(SecurityError::InvalidToken)), "{result:?}");
        assert_eq!(jwks_fetches(&idp).await, 0, "the IdP's keys were consulted");
        assert_eq!(jwks_fetches(&exchange).await, 0, "the exchange's keys were consulted");
    }

    /// A token claiming the `IdP` but signed under the exchange's key id is checked
    /// against the `IdP`'s keys alone, and refused.
    #[tokio::test]
    async fn an_issuer_never_verifies_with_another_issuers_keys() {
        let (validator, _idp, exchange) = two_issuers().await;
        let result = validator.validate_token(&token("exchange-key", IDP, "api")).await;
        assert!(result.is_err(), "verified with the wrong issuer's keys");
        assert_eq!(jwks_fetches(&exchange).await, 0, "the exchange's keys were consulted");
    }

    /// Each issuer has its own audience: an exchange token minted for the `IdP`'s
    /// audience is refused.
    #[tokio::test]
    async fn each_issuer_checks_its_own_audience() {
        let (validator, _idp, _exchange) = two_issuers().await;
        let result = validator.validate_token(&token("exchange-key", EXCHANGE, "api")).await;
        assert!(matches!(result, Err(SecurityError::InvalidToken)), "{result:?}");
    }

    fn with_extra(primary_issuer: Option<&str>, extra: &[&str]) -> OidcConfig {
        OidcConfig {
            issuer: primary_issuer.map(ToString::to_string),
            audience: Some("api".to_string()),
            jwks_uri: Some("https://idp.example.com/jwks.json".to_string()),
            additional_issuers: extra
                .iter()
                .map(|issuer| TrustedIssuer {
                    issuer:               (*issuer).to_string(),
                    audience:             Some("api".to_string()),
                    additional_audiences: Vec::new(),
                    allowed_algorithms:   vec!["RS256".to_string()],
                    clock_skew_secs:      60,
                    jwks_uri:             None,
                    scope_claim:          "scope".to_string(),
                    require_jti:          false,
                })
                .collect(),
            ..Default::default()
        }
    }

    #[test]
    fn additional_issuers_require_a_named_primary_issuer() {
        let err = with_extra(None, &[EXCHANGE]).validate().unwrap_err();
        assert!(err.to_string().contains("requires `issuer`"), "{err}");
        with_extra(Some(IDP), &[EXCHANGE]).validate().unwrap();
    }

    #[test]
    fn an_issuer_configured_twice_is_refused() {
        let err = with_extra(Some(IDP), &[IDP]).validate().unwrap_err();
        assert!(err.to_string().contains("configured twice"), "{err}");
        let err = with_extra(Some(IDP), &[EXCHANGE, EXCHANGE]).validate().unwrap_err();
        assert!(err.to_string().contains("configured twice"), "{err}");
    }

    /// Every additional issuer is held to the single-issuer rules, and the error names it.
    #[test]
    fn an_additional_issuer_is_held_to_the_single_issuer_rules() {
        let err = with_extra(Some(IDP), &["http://plain.example.com"]).validate().unwrap_err();
        assert!(err.to_string().contains("plain.example.com"), "{err}");
    }
}