lonkero 3.6.2

Web scanner built for actual pentests. Fast, modular, Rust.
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
// Copyright (c) 2026 Bountyy Oy. All rights reserved.
// This software is proprietary and confidential.

/**
 * Bountyy Oy - Advanced API Fuzzing Scanner
 * Comprehensive REST/GraphQL/gRPC API fuzzing and vulnerability detection
 *
 * Features:
 * - REST API fuzzing (HTTP methods, Content-Type, parameters, IDOR, mass assignment)
 * - GraphQL fuzzing (introspection, batch queries, depth limits, circular queries)
 * - gRPC fuzzing (protobuf, metadata, stream handling)
 * - Authentication bypass (JWT, OAuth, API keys, token replay)
 * - Rate limit testing and API versioning issues
 *
 * @copyright 2026 Bountyy Oy
 * @license Proprietary
 */
use crate::detection_helpers::AppCharacteristics;
use crate::http_client::HttpClient;
use crate::types::{Confidence, ScanConfig, ScanMode, Severity, Vulnerability};
use regex::Regex;
use serde_json::{json, Value};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::Duration;
use tracing::{debug, info};

mod uuid {
    pub use uuid::Uuid;
}

/// Advanced API Fuzzing Scanner
pub struct ApiFuzzerScanner {
    http_client: Arc<HttpClient>,
    test_marker: String,
}

impl ApiFuzzerScanner {
    pub fn new(http_client: Arc<HttpClient>) -> Self {
        let test_marker = format!("fuzz-{}", uuid::Uuid::new_v4().to_string().replace('-', ""));
        Self {
            http_client,
            test_marker,
        }
    }

    /// Main scan entry point
    pub async fn scan(
        &self,
        url: &str,
        config: &ScanConfig,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        // Premium feature check
        if !crate::license::is_feature_available("api_fuzzing") {
            info!("[SKIP] Advanced API fuzzing requires Professional or higher license");
            return Ok((Vec::new(), 0));
        }

        info!("Starting advanced API fuzzing scan on {}", url);

        // Intelligent detection - API fuzzing needs API endpoints
        if let Ok(response) = self.http_client.get(url).await {
            let characteristics = AppCharacteristics::from_response(&response, url);
            if characteristics.is_static {
                info!("[ApiFuzzer] Skipping - static site detected");
                return Ok((Vec::new(), 0));
            }
        }

        let mut all_vulnerabilities = Vec::new();
        let mut total_tests = 0;

        // Detect API type and endpoints
        let api_endpoints = self.discover_api_endpoints(url).await?;

        if api_endpoints.is_empty() {
            debug!("No API endpoints detected, skipping API fuzzing");
            return Ok((all_vulnerabilities, total_tests));
        }

        info!("Detected {} API endpoints", api_endpoints.len());

        // Phase 1: REST API Fuzzing
        let (vulns, tests) = self.fuzz_rest_apis(&api_endpoints, config).await?;
        all_vulnerabilities.extend(vulns);
        total_tests += tests;

        // Phase 2: GraphQL Fuzzing
        let (vulns, tests) = self.fuzz_graphql_apis(&api_endpoints, config).await?;
        all_vulnerabilities.extend(vulns);
        total_tests += tests;

        // Phase 3: gRPC Fuzzing
        let (vulns, tests) = self.fuzz_grpc_apis(&api_endpoints, config).await?;
        all_vulnerabilities.extend(vulns);
        total_tests += tests;

        // Phase 4: Authentication Bypass Testing
        let (vulns, tests) = self.test_auth_bypass(&api_endpoints, config).await?;
        all_vulnerabilities.extend(vulns);
        total_tests += tests;

        info!(
            "API fuzzing completed: {} tests run, {} vulnerabilities found",
            total_tests,
            all_vulnerabilities.len()
        );

        Ok((all_vulnerabilities, total_tests))
    }

    /// Discover API endpoints from the target
    async fn discover_api_endpoints(&self, url: &str) -> anyhow::Result<Vec<ApiEndpoint>> {
        let mut endpoints = Vec::new();
        let base_url = self.extract_base_url(url);

        // Common API paths
        let api_paths = vec![
            "/api",
            "/api/v1",
            "/api/v2",
            "/api/v3",
            "/graphql",
            "/api/graphql",
            "/rest",
            "/rest/v1",
            "/v1",
            "/v2",
            "/v3",
        ];

        for path in api_paths {
            let test_url = format!("{}{}", base_url, path);

            match self.http_client.get(&test_url).await {
                Ok(response) => {
                    // CRITICAL: Only detect API type if endpoint actually exists (not 404)
                    // 404 responses with JSON bodies ({"statusCode":404,"message":"Cannot GET ..."})
                    // should NOT be detected as REST APIs
                    if response.status_code >= 200 && response.status_code < 300 {
                        // 2xx success - endpoint exists and returned data
                        let api_type = self.detect_api_type(&response.body, &response.headers);
                        if api_type != ApiType::None {
                            info!("Detected {} API at: {}", api_type.as_str(), test_url);
                            endpoints.push(ApiEndpoint {
                                url: test_url,
                                api_type,
                                methods: vec!["GET".to_string()],
                            });
                        }
                    } else if response.status_code == 401 || response.status_code == 403 {
                        // 401/403 - endpoint exists but requires auth
                        let api_type = self.detect_api_type(&response.body, &response.headers);
                        if api_type != ApiType::None {
                            info!(
                                "Detected {} API at: {} (requires authentication)",
                                api_type.as_str(),
                                test_url
                            );
                            endpoints.push(ApiEndpoint {
                                url: test_url,
                                api_type,
                                methods: vec!["GET".to_string()],
                            });
                        }
                    } else if response.status_code == 405 {
                        // 405 Method Not Allowed - endpoint exists but GET not supported
                        // Try to detect API type anyway since endpoint clearly exists
                        let api_type = self.detect_api_type(&response.body, &response.headers);
                        if api_type != ApiType::None {
                            info!(
                                "Detected {} API at: {} (GET not allowed)",
                                api_type.as_str(),
                                test_url
                            );
                            endpoints.push(ApiEndpoint {
                                url: test_url,
                                api_type,
                                methods: vec!["POST".to_string()], // Assume POST works
                            });
                        }
                    }
                    // 404, 500, etc - endpoint doesn't exist or error, skip
                }
                Err(e) => {
                    debug!("Failed to probe {}: {}", test_url, e);
                }
            }
        }

        Ok(endpoints)
    }

    /// Fuzz REST API endpoints
    async fn fuzz_rest_apis(
        &self,
        endpoints: &[ApiEndpoint],
        config: &ScanConfig,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        for endpoint in endpoints.iter().filter(|e| e.api_type == ApiType::Rest) {
            info!("Fuzzing REST API: {}", endpoint.url);

            // Test HTTP method fuzzing
            let (vulns, tests) = self.fuzz_http_methods(&endpoint.url, config).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;

            // Test Content-Type fuzzing
            let (vulns, tests) = self.fuzz_content_types(&endpoint.url, config).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;

            // Test parameter tampering
            let (vulns, tests) = self.fuzz_parameters(&endpoint.url, config).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;

            // Test mass assignment
            let (vulns, tests) = self.test_mass_assignment(&endpoint.url, config).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;

            // Test IDOR vulnerabilities
            let (vulns, tests) = self.test_idor(&endpoint.url, config).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;

            // Test broken object level authorization
            let (vulns, tests) = self.test_bola(&endpoint.url, config).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;

            // Test rate limiting
            let (vulns, tests) = self.test_rate_limits(&endpoint.url).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;

            // Test API versioning issues
            let (vulns, tests) = self.test_api_versioning(&endpoint.url).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Fuzz HTTP methods (GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD)
    async fn fuzz_http_methods(
        &self,
        url: &str,
        _config: &ScanConfig,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let methods = vec![
            "GET".to_string(),
            "POST".to_string(),
            "PUT".to_string(),
            "DELETE".to_string(),
            "PATCH".to_string(),
            "OPTIONS".to_string(),
            "HEAD".to_string(),
            "TRACE".to_string(),
        ];
        let tests_run = methods.len();

        debug!("Testing HTTP method fuzzing");

        for method in &methods {
            match self.send_http_request(url, &method, None, vec![]).await {
                Ok(response) => {
                    // Check for unexpected method acceptance
                    if response.status_code < 400 && (*method == "DELETE" || *method == "TRACE") {
                        vulnerabilities.push(self.create_vulnerability(
                            "Unsafe HTTP Method Allowed",
                            url,
                            &format!("HTTP {} method is allowed", method),
                            &format!(
                                "Server accepted {} request with status {}",
                                method, response.status_code
                            ),
                            Severity::Medium,
                            "CWE-650",
                            6.5,
                        ));
                    }

                    // Check for method override vulnerabilities
                    if response.body.contains("X-HTTP-Method-Override") {
                        vulnerabilities.push(self.create_vulnerability(
                            "HTTP Method Override Detected",
                            url,
                            "X-HTTP-Method-Override header",
                            "Server supports HTTP method override, which may bypass security controls",
                            Severity::Medium,
                            "CWE-650",
                            5.3,
                        ));
                    }
                }
                Err(e) => {
                    debug!("Method {} test failed: {}", method, e);
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Fuzz Content-Type headers
    async fn fuzz_content_types(
        &self,
        url: &str,
        _config: &ScanConfig,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();

        let content_types = vec![
            ("application/json", r#"{"test":"value"}"#),
            (
                "application/xml",
                r#"<?xml version="1.0"?><test>value</test>"#,
            ),
            ("application/x-www-form-urlencoded", "test=value"),
            ("multipart/form-data", "test=value"),
            ("application/msgpack", "test"),
            ("application/protobuf", "test"),
            ("text/plain", "test"),
            ("application/x-yaml", "test: value"),
        ];

        let tests_run = content_types.len();

        debug!("Testing Content-Type fuzzing");

        for (content_type, payload) in &content_types {
            let headers = vec![("Content-Type".to_string(), content_type.to_string())];

            match self
                .http_client
                .post_with_headers(url, payload, headers)
                .await
            {
                Ok(response) => {
                    // Check for unexpected processing
                    if response.status_code == 200
                        && (*content_type == "application/msgpack"
                            || *content_type == "application/protobuf")
                    {
                        vulnerabilities.push(self.create_vulnerability(
                            "Unusual Content-Type Accepted",
                            url,
                            &format!("Content-Type: {}", content_type),
                            &format!("Server processes unusual content type: {}", content_type),
                            Severity::Low,
                            "CWE-436",
                            3.7,
                        ));
                    }

                    // Check for content type confusion
                    if response.body.contains("SyntaxError") || response.body.contains("ParseError")
                    {
                        if response.body.contains("stack") || response.body.contains("trace") {
                            vulnerabilities.push(self.create_vulnerability(
                                "Content-Type Confusion with Verbose Errors",
                                url,
                                &format!("Content-Type: {}", content_type),
                                "Server returns verbose error messages during content type processing",
                                Severity::Low,
                                "CWE-209",
                                3.1,
                            ));
                        }
                    }
                }
                Err(e) => {
                    debug!("Content-Type {} test failed: {}", content_type, e);
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Fuzz API parameters with type confusion and boundary values
    async fn fuzz_parameters(
        &self,
        url: &str,
        config: &ScanConfig,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        debug!("Testing parameter fuzzing");

        // Type confusion payloads
        let type_confusion = vec![
            (json!({"id": "string_instead_of_int"}), "String for integer"),
            (
                json!({"id": ["array", "instead", "of", "scalar"]}),
                "Array for scalar",
            ),
            (json!({"id": {"nested": "object"}}), "Object for scalar"),
            (json!({"id": null}), "Null value"),
            (json!({"id": true}), "Boolean for integer"),
        ];

        for (payload, description) in &type_confusion {
            tests_run += 1;
            let headers = vec![("Content-Type".to_string(), "application/json".to_string())];

            match self
                .http_client
                .post_with_headers(url, &payload.to_string(), headers)
                .await
            {
                Ok(response) => {
                    if response.status_code == 200 {
                        vulnerabilities.push(self.create_vulnerability(
                            "Type Confusion Vulnerability",
                            url,
                            &format!("{}: {}", description, payload),
                            "API accepts unexpected data types without validation",
                            Severity::Medium,
                            "CWE-843",
                            5.3,
                        ));
                        break; // Found one, no need to test all
                    }

                    // Check for error leakage
                    if self.detect_error_leakage(&response.body) {
                        vulnerabilities.push(self.create_vulnerability(
                            "Information Leakage in Error Messages",
                            url,
                            &format!("{}: {}", description, payload),
                            &format!(
                                "Verbose error: {}",
                                self.extract_evidence(&response.body, 200)
                            ),
                            Severity::Low,
                            "CWE-209",
                            3.7,
                        ));
                    }
                }
                Err(e) => {
                    debug!("Parameter fuzzing failed: {}", e);
                }
            }
        }

        // Boundary value testing
        let boundary_values = vec![
            (json!({"id": -1}), "Negative value"),
            (json!({"id": 0}), "Zero"),
            (json!({"id": 2147483647}), "Max int32"),
            (json!({"id": 2147483648i64}), "Max int32 + 1"),
            (json!({"id": -2147483648}), "Min int32"),
            (json!({"amount": 0.01}), "Minimal decimal"),
            (json!({"amount": 999999999.99}), "Large decimal"),
            (json!({"quantity": -1}), "Negative quantity"),
        ];

        for (payload, description) in &boundary_values {
            tests_run += 1;
            let headers = vec![("Content-Type".to_string(), "application/json".to_string())];

            match self
                .http_client
                .post_with_headers(url, &payload.to_string(), headers)
                .await
            {
                Ok(response) => {
                    if response.status_code == 200
                        && (description.contains("Negative") || description.contains("Large"))
                    {
                        vulnerabilities.push(self.create_vulnerability(
                            "Insufficient Input Validation",
                            url,
                            &format!("{}: {}", description, payload),
                            "API accepts boundary/edge case values without proper validation",
                            Severity::Medium,
                            "CWE-20",
                            5.3,
                        ));
                    }
                }
                Err(e) => {
                    debug!("Boundary value test failed: {}", e);
                }
            }
        }

        // Integer overflow testing
        if config.scan_mode == ScanMode::Thorough || config.scan_mode == ScanMode::Insane {
            let overflow_payloads = vec![
                json!({"id": "9223372036854775807"}),  // Max int64
                json!({"id": "18446744073709551615"}), // Max uint64
                json!({"price": "999999999999999.99"}),
            ];

            for payload in &overflow_payloads {
                tests_run += 1;
                let headers = vec![("Content-Type".to_string(), "application/json".to_string())];

                if let Ok(response) = self
                    .http_client
                    .post_with_headers(url, &payload.to_string(), headers)
                    .await
                {
                    if response.body.contains("overflow") || response.body.contains("out of range")
                    {
                        vulnerabilities.push(self.create_vulnerability(
                            "Integer Overflow Potential",
                            url,
                            &payload.to_string(),
                            "API may be vulnerable to integer overflow",
                            Severity::Medium,
                            "CWE-190",
                            5.3,
                        ));
                        break;
                    }
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test for mass assignment vulnerabilities
    async fn test_mass_assignment(
        &self,
        url: &str,
        _config: &ScanConfig,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 4;

        debug!("Testing mass assignment vulnerabilities");

        // Attempt to modify sensitive fields
        let mass_assignment_payloads = vec![
            json!({
                "username": "testuser",
                "role": "admin",
                "is_admin": true
            }),
            json!({
                "email": "test@example.com",
                "is_verified": true,
                "permissions": ["admin", "write", "delete"]
            }),
            json!({
                "name": "Test",
                "balance": 1000000,
                "credits": 9999
            }),
            json!({
                "id": 1,
                "user_id": 1,
                "admin": true,
                "superuser": true
            }),
        ];

        for payload in &mass_assignment_payloads {
            let headers = vec![("Content-Type".to_string(), "application/json".to_string())];

            match self
                .http_client
                .post_with_headers(url, &payload.to_string(), headers)
                .await
            {
                Ok(response) => {
                    // Check if sensitive fields were accepted
                    let response_json: Result<Value, _> = serde_json::from_str(&response.body);
                    if let Ok(json) = response_json {
                        let sensitive_fields = vec![
                            "role",
                            "is_admin",
                            "admin",
                            "superuser",
                            "balance",
                            "credits",
                            "permissions",
                        ];

                        for field in sensitive_fields {
                            if json.get(field).is_some() {
                                vulnerabilities.push(self.create_vulnerability(
                                    "Mass Assignment Vulnerability",
                                    url,
                                    &payload.to_string(),
                                    &format!(
                                        "API allows modification of sensitive field: {}",
                                        field
                                    ),
                                    Severity::High,
                                    "CWE-915",
                                    7.5,
                                ));
                                break;
                            }
                        }
                    }
                }
                Err(e) => {
                    debug!("Mass assignment test failed: {}", e);
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test for IDOR (Insecure Direct Object Reference) vulnerabilities
    async fn test_idor(
        &self,
        url: &str,
        _config: &ScanConfig,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 10;

        debug!("Testing IDOR vulnerabilities");

        // Test sequential ID access
        let id_patterns = vec![
            ("/users/1", "/users/2"),
            ("/api/users/1", "/api/users/2"),
            ("/accounts/1", "/accounts/2"),
            ("/orders/1", "/orders/2"),
            ("/invoices/1", "/invoices/2"),
        ];

        for (id1, id2) in &id_patterns {
            let url1 = self.build_url(url, id1);
            let url2 = self.build_url(url, id2);

            // Request two different IDs
            let result1 = self.http_client.get(&url1).await;
            let result2 = self.http_client.get(&url2).await;

            if let (Ok(resp1), Ok(resp2)) = (result1, result2) {
                // Both requests successful - potential IDOR
                if resp1.status_code == 200 && resp2.status_code == 200 {
                    // Check if responses contain different user data
                    if resp1.body != resp2.body && self.contains_user_data(&resp1.body) {
                        vulnerabilities.push(self.create_vulnerability(
                            "IDOR - Insecure Direct Object Reference",
                            &url1,
                            &format!("Sequential access: {} and {}", id1, id2),
                            "API allows unauthorized access to objects via predictable IDs",
                            Severity::High,
                            "CWE-737",
                            7.5,
                        ));
                        break;
                    }
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test for Broken Object Level Authorization (BOLA)
    async fn test_bola(
        &self,
        url: &str,
        _config: &ScanConfig,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 4;

        debug!("Testing broken object level authorization");

        // Test with and without authentication
        let test_urls = vec![
            format!("{}/users/1", url.trim_end_matches('/')),
            format!("{}/api/users/1", url.trim_end_matches('/')),
            format!("{}/profile/1", url.trim_end_matches('/')),
            format!("{}/account/1", url.trim_end_matches('/')),
        ];

        for test_url in &test_urls {
            // Request without auth
            if let Ok(response) = self.http_client.get(test_url).await {
                if response.status_code == 200 && self.contains_user_data(&response.body) {
                    vulnerabilities.push(self.create_vulnerability(
                        "Broken Object Level Authorization",
                        test_url,
                        "Unauthenticated access",
                        "API endpoint returns user data without authentication",
                        Severity::Critical,
                        "CWE-284",
                        9.1,
                    ));
                    break;
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test API rate limiting
    async fn test_rate_limits(&self, url: &str) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let max_requests = 100;
        let tests_run = max_requests;

        debug!("Testing rate limiting");

        let mut rate_limited = false;
        let mut request_count = 0;

        for i in 0..max_requests {
            match self.http_client.get(url).await {
                Ok(response) => {
                    request_count = i + 1;

                    // Check for rate limit response
                    if response.status_code == 429 {
                        rate_limited = true;
                        debug!("Rate limited after {} requests", request_count);
                        break;
                    }

                    // Check for rate limit headers
                    if response.header("X-RateLimit-Limit").is_some() {
                        rate_limited = true;
                        debug!("Rate limit headers detected");
                        break;
                    }
                }
                Err(_) => break,
            }

            // Small delay to avoid overwhelming the server
            tokio::time::sleep(Duration::from_millis(10)).await;
        }

        if !rate_limited && request_count >= 50 {
            vulnerabilities.push(self.create_vulnerability(
                "Missing Rate Limiting",
                url,
                &format!("{} requests without rate limiting", request_count),
                "API endpoint does not implement rate limiting",
                Severity::Medium,
                "CWE-770",
                5.3,
            ));
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test API versioning issues
    async fn test_api_versioning(&self, url: &str) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 6;

        debug!("Testing API versioning issues");

        // Extract version from URL
        let version_regex = Regex::new(r"/v(\d+)/").ok();

        if let Some(regex) = version_regex {
            if let Some(captures) = regex.captures(url) {
                if let Some(version) = captures.get(1) {
                    let current_version: i32 = version.as_str().parse().unwrap_or(1);

                    // Test older versions
                    for old_version in 1..current_version {
                        let old_url = url.replace(
                            &format!("/v{}/", current_version),
                            &format!("/v{}/", old_version),
                        );

                        if let Ok(response) = self.http_client.get(&old_url).await {
                            if response.status_code == 200 {
                                vulnerabilities.push(self.create_vulnerability(
                                    "Outdated API Version Accessible",
                                    &old_url,
                                    &format!("Old version v{} still accessible", old_version),
                                    "Outdated API versions may contain unpatched vulnerabilities",
                                    Severity::Medium,
                                    "CWE-1104",
                                    5.3,
                                ));
                                break;
                            }
                        }
                    }
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Fuzz GraphQL APIs
    async fn fuzz_graphql_apis(
        &self,
        endpoints: &[ApiEndpoint],
        config: &ScanConfig,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        for endpoint in endpoints.iter().filter(|e| e.api_type == ApiType::GraphQL) {
            info!("Fuzzing GraphQL API: {}", endpoint.url);

            // Test introspection query exploitation
            let (vulns, tests) = self.test_graphql_introspection(&endpoint.url).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;

            // Test batch query attacks
            let (vulns, tests) = self.test_graphql_batch_queries(&endpoint.url).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;

            // Test depth limit
            let (vulns, tests) = self.test_graphql_depth_limit(&endpoint.url).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;

            // Test query cost analysis
            let (vulns, tests) = self.test_graphql_query_cost(&endpoint.url, config).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;

            // Test circular query detection
            let (vulns, tests) = self.test_graphql_circular_queries(&endpoint.url).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;

            // Test field suggestion attacks
            let (vulns, tests) = self.test_graphql_field_suggestions(&endpoint.url).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test GraphQL introspection exploitation
    async fn test_graphql_introspection(
        &self,
        url: &str,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 1;

        debug!("Testing GraphQL introspection");

        let introspection_query = json!({
            "query": r#"
                query IntrospectionQuery {
                    __schema {
                        queryType { name }
                        mutationType { name }
                        subscriptionType { name }
                        types {
                            name
                            kind
                            description
                            fields {
                                name
                                description
                                args {
                                    name
                                    type { name }
                                }
                            }
                        }
                    }
                }
            "#
        });

        let headers = vec![("Content-Type".to_string(), "application/json".to_string())];

        match self
            .http_client
            .post_with_headers(url, &introspection_query.to_string(), headers)
            .await
        {
            Ok(response) => {
                if response.status_code == 200
                    && (response.body.contains("__schema") || response.body.contains("queryType"))
                {
                    let schema_size = response.body.len();
                    vulnerabilities.push(self.create_vulnerability(
                        "GraphQL Introspection Enabled",
                        url,
                        "Full introspection query",
                        &format!(
                            "GraphQL introspection is enabled, exposing {} bytes of schema",
                            schema_size
                        ),
                        Severity::Medium,
                        "CWE-200",
                        5.3,
                    ));
                }
            }
            Err(e) => {
                debug!("Introspection test failed: {}", e);
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test GraphQL batch query attacks
    async fn test_graphql_batch_queries(
        &self,
        url: &str,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 1;

        debug!("Testing GraphQL batch query attacks");

        // Create batch query with 10 identical queries
        let mut queries = Vec::new();
        for i in 0..10 {
            queries.push(json!({
                "query": format!(r#"query Query{} {{ __typename }}"#, i)
            }));
        }

        let headers = vec![("Content-Type".to_string(), "application/json".to_string())];

        match self
            .http_client
            .post_with_headers(url, &serde_json::to_string(&queries)?, headers)
            .await
        {
            Ok(response) => {
                if response.status_code == 200 {
                    vulnerabilities.push(self.create_vulnerability(
                        "GraphQL Batch Query Attack Possible",
                        url,
                        "10 batched queries",
                        "Server accepts batch queries without limits, enabling DoS attacks",
                        Severity::Medium,
                        "CWE-770",
                        5.3,
                    ));
                }
            }
            Err(e) => {
                debug!("Batch query test failed: {}", e);
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test GraphQL depth limit
    async fn test_graphql_depth_limit(
        &self,
        url: &str,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 1;

        debug!("Testing GraphQL depth limit");

        // Create deeply nested query
        let deep_query = json!({
            "query": r#"
                query DeepQuery {
                    user {
                        posts {
                            comments {
                                author {
                                    posts {
                                        comments {
                                            author {
                                                posts {
                                                    comments {
                                                        author {
                                                            id
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            "#
        });

        let headers = vec![("Content-Type".to_string(), "application/json".to_string())];

        match self
            .http_client
            .post_with_headers(url, &deep_query.to_string(), headers)
            .await
        {
            Ok(response) => {
                if response.status_code == 200
                    && !response.body.contains("depth")
                    && !response.body.contains("too deep")
                {
                    vulnerabilities.push(self.create_vulnerability(
                        "GraphQL Depth Limit Missing",
                        url,
                        "Deeply nested query",
                        "Server accepts deeply nested queries without depth limits",
                        Severity::Medium,
                        "CWE-770",
                        5.3,
                    ));
                }
            }
            Err(e) => {
                debug!("Depth limit test failed: {}", e);
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test GraphQL query cost analysis
    async fn test_graphql_query_cost(
        &self,
        url: &str,
        _config: &ScanConfig,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 1;

        debug!("Testing GraphQL query cost analysis");

        // Create expensive query
        let expensive_query = json!({
            "query": r#"
                query ExpensiveQuery {
                    users(first: 1000) {
                        posts(first: 1000) {
                            comments(first: 1000) {
                                id
                            }
                        }
                    }
                }
            "#
        });

        let headers = vec![("Content-Type".to_string(), "application/json".to_string())];

        let start = std::time::Instant::now();
        match self
            .http_client
            .post_with_headers(url, &expensive_query.to_string(), headers)
            .await
        {
            Ok(response) => {
                let duration = start.elapsed();

                if response.status_code == 200 && duration.as_secs() > 5 {
                    vulnerabilities.push(self.create_vulnerability(
                        "GraphQL Query Cost Not Analyzed",
                        url,
                        "Expensive nested list query",
                        &format!(
                            "Server processed expensive query in {} seconds without cost limits",
                            duration.as_secs()
                        ),
                        Severity::Medium,
                        "CWE-770",
                        5.3,
                    ));
                }
            }
            Err(e) => {
                debug!("Query cost test failed: {}", e);
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test GraphQL circular queries
    async fn test_graphql_circular_queries(
        &self,
        url: &str,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 1;

        debug!("Testing GraphQL circular queries");

        let circular_query = json!({
            "query": r#"
                query CircularQuery {
                    user {
                        friends {
                            friends {
                                friends {
                                    friends {
                                        id
                                    }
                                }
                            }
                        }
                    }
                }
            "#
        });

        let headers = vec![("Content-Type".to_string(), "application/json".to_string())];

        match self
            .http_client
            .post_with_headers(url, &circular_query.to_string(), headers)
            .await
        {
            Ok(response) => {
                if response.status_code == 200 && !response.body.contains("circular") {
                    vulnerabilities.push(self.create_vulnerability(
                        "GraphQL Circular Query Not Prevented",
                        url,
                        "Circular reference query",
                        "Server allows circular queries that may cause infinite loops",
                        Severity::Medium,
                        "CWE-674",
                        5.3,
                    ));
                }
            }
            Err(e) => {
                debug!("Circular query test failed: {}", e);
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test GraphQL field suggestions
    async fn test_graphql_field_suggestions(
        &self,
        url: &str,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 1;

        debug!("Testing GraphQL field suggestions");

        let typo_query = json!({
            "query": r#"{ usr { nam } }"#
        });

        let headers = vec![("Content-Type".to_string(), "application/json".to_string())];

        match self
            .http_client
            .post_with_headers(url, &typo_query.to_string(), headers)
            .await
        {
            Ok(response) => {
                if response.body.contains("Did you mean")
                    || response.body.contains("suggestion")
                    || (response.body.contains("user") && response.body.contains("name"))
                {
                    vulnerabilities.push(self.create_vulnerability(
                        "GraphQL Field Suggestions Leak Schema",
                        url,
                        "Typo query: { usr { nam } }",
                        "Server provides field suggestions that leak schema information",
                        Severity::Low,
                        "CWE-200",
                        3.7,
                    ));
                }
            }
            Err(e) => {
                debug!("Field suggestion test failed: {}", e);
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Fuzz gRPC APIs
    async fn fuzz_grpc_apis(
        &self,
        endpoints: &[ApiEndpoint],
        _config: &ScanConfig,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        for endpoint in endpoints.iter().filter(|e| e.api_type == ApiType::Grpc) {
            info!("Fuzzing gRPC API: {}", endpoint.url);

            // Test protocol buffer fuzzing
            let (vulns, tests) = self.test_grpc_protobuf(&endpoint.url).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;

            // Test metadata manipulation
            let (vulns, tests) = self.test_grpc_metadata(&endpoint.url).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;

            // Test stream handling
            let (vulns, tests) = self.test_grpc_streams(&endpoint.url).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test gRPC protocol buffer fuzzing
    async fn test_grpc_protobuf(&self, url: &str) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 3;

        debug!("Testing gRPC protobuf fuzzing");

        // Malformed protobuf payloads
        let malformed_payloads = vec![
            vec![0xFF, 0xFF, 0xFF, 0xFF], // Invalid varint
            vec![0x08, 0x96, 0x01],       // Large field number
            vec![0x00, 0x00, 0x00, 0x00], // All zeros
        ];

        let headers = vec![
            ("Content-Type".to_string(), "application/grpc".to_string()),
            ("grpc-encoding".to_string(), "identity".to_string()),
        ];

        for payload in &malformed_payloads {
            let payload_str = String::from_utf8_lossy(payload);

            match self
                .http_client
                .post_with_headers(url, &payload_str, headers.clone())
                .await
            {
                Ok(response) => {
                    if self.detect_error_leakage(&response.body) {
                        vulnerabilities.push(self.create_vulnerability(
                            "gRPC Protobuf Error Leakage",
                            url,
                            "Malformed protobuf",
                            "Server leaks internal information when processing malformed protobuf",
                            Severity::Low,
                            "CWE-209",
                            3.7,
                        ));
                        break;
                    }
                }
                Err(e) => {
                    debug!("Protobuf fuzzing failed: {}", e);
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test gRPC metadata manipulation
    async fn test_grpc_metadata(&self, url: &str) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 4;

        debug!("Testing gRPC metadata manipulation");

        let metadata_tests = vec![
            ("grpc-timeout", "1n"),           // Very short timeout
            ("grpc-timeout", "999999H"),      // Very long timeout
            ("grpc-encoding", "malicious"),   // Invalid encoding
            ("authorization", "Bearer fake"), // Fake auth
        ];

        for (key, value) in &metadata_tests {
            let headers = vec![
                ("Content-Type".to_string(), "application/grpc".to_string()),
                (key.to_string(), value.to_string()),
            ];

            match self.http_client.post_with_headers(url, "", headers).await {
                Ok(response) => {
                    if response.status_code == 200 && *key == "authorization" {
                        vulnerabilities.push(self.create_vulnerability(
                            "gRPC Metadata Authentication Bypass",
                            url,
                            &format!("{}: {}", key, value),
                            "Server accepts invalid authentication metadata",
                            Severity::High,
                            "CWE-287",
                            7.5,
                        ));
                        break;
                    }
                }
                Err(e) => {
                    debug!("Metadata test failed: {}", e);
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test gRPC stream handling
    async fn test_grpc_streams(&self, url: &str) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 2;

        debug!("Testing gRPC stream handling");

        let headers = vec![
            ("Content-Type".to_string(), "application/grpc".to_string()),
            ("grpc-encoding".to_string(), "identity".to_string()),
        ];

        // Test with large payload to check stream handling
        let large_payload = "A".repeat(1024 * 1024); // 1MB

        match self
            .http_client
            .post_with_headers(url, &large_payload, headers)
            .await
        {
            Ok(response) => {
                if response.status_code == 200 {
                    vulnerabilities.push(self.create_vulnerability(
                        "gRPC Stream Size Limit Missing",
                        url,
                        "1MB payload",
                        "Server accepts large payloads without stream size limits",
                        Severity::Medium,
                        "CWE-770",
                        5.3,
                    ));
                }
            }
            Err(e) => {
                debug!("Stream test failed: {}", e);
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test authentication bypass techniques
    async fn test_auth_bypass(
        &self,
        endpoints: &[ApiEndpoint],
        config: &ScanConfig,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        debug!("Testing authentication bypass techniques");

        for endpoint in endpoints {
            // Test JWT manipulation
            let (vulns, tests) = self.test_jwt_manipulation(&endpoint.url).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;

            // Test OAuth flow attacks
            let (vulns, tests) = self.test_oauth_attacks(&endpoint.url).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;

            // Test API key enumeration
            let (vulns, tests) = self.test_api_key_enumeration(&endpoint.url).await?;
            vulnerabilities.extend(vulns);
            tests_run += tests;

            // Test token replay attacks
            if config.scan_mode == ScanMode::Thorough || config.scan_mode == ScanMode::Insane {
                let (vulns, tests) = self.test_token_replay(&endpoint.url).await?;
                vulnerabilities.extend(vulns);
                tests_run += tests;
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test JWT manipulation (alg:none, weak signing)
    async fn test_jwt_manipulation(
        &self,
        url: &str,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 5;

        debug!("Testing JWT manipulation");

        // JWT with alg:none
        let none_jwt = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJhZG1pbiIsInJvbGUiOiJhZG1pbiIsImV4cCI6OTk5OTk5OTk5OX0.";

        // JWT with alg:None (capital N)
        let none_capital_jwt =
            "eyJhbGciOiJOb25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJhZG1pbiIsInJvbGUiOiJhZG1pbiJ9.";

        // JWT with alg:NONE (all caps)
        let none_upper_jwt =
            "eyJhbGciOiJOT05FIiwidHlwIjoiSldUIn0.eyJzdWIiOiJhZG1pbiIsInJvbGUiOiJhZG1pbiJ9.";

        let jwt_tests = vec![
            (none_jwt, "alg:none"),
            (none_capital_jwt, "alg:None"),
            (none_upper_jwt, "alg:NONE"),
        ];

        for (jwt, description) in &jwt_tests {
            let headers = vec![("Authorization".to_string(), format!("Bearer {}", jwt))];

            match self.http_client.get_with_headers(url, headers).await {
                Ok(response) => {
                    if response.status_code < 400 {
                        vulnerabilities.push(self.create_vulnerability(
                            "JWT None Algorithm Vulnerability",
                            url,
                            &format!("JWT with {}", description),
                            "Server accepts JWT tokens with 'none' algorithm",
                            Severity::Critical,
                            "CWE-347",
                            9.8,
                        ));
                        break;
                    }
                }
                Err(e) => {
                    debug!("JWT test failed: {}", e);
                }
            }
        }

        // Test JWT with modified payload but same signature
        let tampered_jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZG1pbiIsInJvbGUiOiJhZG1pbiIsImlhdCI6MTUxNjIzOTAyMn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";

        let headers = vec![(
            "Authorization".to_string(),
            format!("Bearer {}", tampered_jwt),
        )];

        if let Ok(response) = self.http_client.get_with_headers(url, headers).await {
            if response.status_code < 400 {
                vulnerabilities.push(self.create_vulnerability(
                    "JWT Signature Not Verified",
                    url,
                    "Tampered JWT accepted",
                    "Server does not properly verify JWT signatures",
                    Severity::Critical,
                    "CWE-347",
                    9.8,
                ));
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test OAuth flow attacks
    async fn test_oauth_attacks(&self, url: &str) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 3;

        debug!("Testing OAuth flow attacks");

        // Look for OAuth endpoints
        let oauth_paths = vec![
            "/oauth/token".to_string(),
            "/oauth/authorize".to_string(),
            "/api/oauth/token".to_string(),
        ];

        for path in &oauth_paths {
            let test_url = self.build_url(url, &path);

            // Test with fake authorization code
            let fake_auth = json!({
                "grant_type": "authorization_code",
                "code": "fake_code_12345",
                "client_id": "test_client",
                "redirect_uri": "http://evil.com"
            });

            let headers = vec![("Content-Type".to_string(), "application/json".to_string())];

            match self
                .http_client
                .post_with_headers(&test_url, &fake_auth.to_string(), headers)
                .await
            {
                Ok(response) => {
                    // Check for verbose error messages
                    if self.detect_error_leakage(&response.body) {
                        vulnerabilities.push(self.create_vulnerability(
                            "OAuth Error Information Leakage",
                            &test_url,
                            &fake_auth.to_string(),
                            "OAuth endpoint leaks sensitive information in error messages",
                            Severity::Low,
                            "CWE-209",
                            3.7,
                        ));
                    }

                    // Check for redirect_uri validation
                    if response.body.contains("access_token") {
                        vulnerabilities.push(self.create_vulnerability(
                            "OAuth Redirect URI Not Validated",
                            &test_url,
                            "redirect_uri: http://evil.com",
                            "OAuth endpoint does not properly validate redirect_uri",
                            Severity::High,
                            "CWE-601",
                            7.5,
                        ));
                        break;
                    }
                }
                Err(e) => {
                    debug!("OAuth test failed: {}", e);
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test API key enumeration
    async fn test_api_key_enumeration(
        &self,
        url: &str,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 5;

        debug!("Testing API key enumeration");

        // Test different API key formats
        let api_key_headers = vec![
            ("X-API-Key", "test123"),
            ("X-Api-Key", "fake_key_12345"),
            ("API-Key", "00000000-0000-0000-0000-000000000000"),
            ("Authorization", "ApiKey test123"),
            ("x-api-key", "ABCDEF123456"),
        ];

        let mut response_lengths = HashSet::new();

        for (header, key) in &api_key_headers {
            let headers = vec![(header.to_string(), key.to_string())];

            if let Ok(response) = self.http_client.get_with_headers(url, headers).await {
                response_lengths.insert(response.body.len());
            }
        }

        // If all responses have different lengths, enumeration is possible
        if response_lengths.len() == api_key_headers.len() {
            vulnerabilities.push(self.create_vulnerability(
                "API Key Enumeration Possible",
                url,
                "Different response lengths for different keys",
                "Server response varies based on API key validity, enabling enumeration",
                Severity::Medium,
                "CWE-203",
                5.3,
            ));
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test token replay attacks
    async fn test_token_replay(&self, url: &str) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 2;

        debug!("Testing token replay attacks");

        // Create a test token
        let test_token = format!("test_token_{}", self.test_marker);
        let headers = vec![(
            "Authorization".to_string(),
            format!("Bearer {}", test_token),
        )];

        // First request
        let first_response = self
            .http_client
            .get_with_headers(url, headers.clone())
            .await;

        // Small delay
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Replay request
        let replay_response = self.http_client.get_with_headers(url, headers).await;

        if let (Ok(resp1), Ok(resp2)) = (first_response, replay_response) {
            // CRITICAL: Don't report replay vulnerability on non-existent endpoints
            // 404 responses are identical because the endpoint doesn't exist, not because replay worked
            if resp1.status_code != 404  // Endpoint must exist
                && resp1.status_code == resp2.status_code
                && resp1.body == resp2.body
                && !resp1.body.to_lowercase().contains("not found")  // Additional check
                && !resp1.body.to_lowercase().contains("cannot get")
            {
                // NestJS 404 message
                vulnerabilities.push(self.create_vulnerability(
                    "Token Replay Attack Possible",
                    url,
                    "Same token used twice",
                    "Server does not implement nonce or timestamp validation for token replay prevention",
                    Severity::Medium,
                    "CWE-294",
                    6.5,
                ));
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    // Helper methods

    /// Detect API type from response
    fn detect_api_type(&self, body: &str, headers: &HashMap<String, String>) -> ApiType {
        // Check headers
        if let Some(content_type) = headers.get("content-type") {
            let ct_lower = content_type.to_lowercase();
            if ct_lower.contains("application/grpc") {
                return ApiType::Grpc;
            }
            if ct_lower.contains("application/json") || ct_lower.contains("application/graphql") {
                if body.contains("\"data\"") && body.contains("\"errors\"") {
                    return ApiType::GraphQL;
                }
                if serde_json::from_str::<Value>(body).is_ok() {
                    return ApiType::Rest;
                }
            }
        }

        // Check body content
        if body.contains("__schema") || body.contains("__type") {
            return ApiType::GraphQL;
        }

        ApiType::None
    }

    /// Send HTTP request with custom method
    async fn send_http_request(
        &self,
        url: &str,
        method: &str,
        body: Option<&str>,
        headers: Vec<(String, String)>,
    ) -> anyhow::Result<crate::http_client::HttpResponse> {
        match method {
            "GET" => self.http_client.get_with_headers(url, headers).await,
            "POST" => {
                self.http_client
                    .post_with_headers(url, body.unwrap_or(""), headers)
                    .await
            }
            "PUT" | "DELETE" | "PATCH" | "OPTIONS" | "HEAD" | "TRACE" => {
                // For now, treat these as GET requests
                // A full implementation would use reqwest directly
                self.http_client.get_with_headers(url, headers).await
            }
            _ => self.http_client.get(url).await,
        }
    }

    /// Detect error leakage in response
    fn detect_error_leakage(&self, body: &str) -> bool {
        let error_indicators = vec![
            "at ",
            "stack trace",
            "Exception",
            "Error:",
            "/home/",
            "/var/",
            "C:\\",
            ".java:",
            ".py:",
            ".rb:",
            ".js:",
            "line ",
        ];

        error_indicators
            .iter()
            .any(|indicator| body.contains(indicator))
    }

    /// Check if response contains user data
    fn contains_user_data(&self, body: &str) -> bool {
        let user_indicators = vec![
            "email",
            "username",
            "user_id",
            "userId",
            "firstName",
            "lastName",
            "phone",
            "address",
        ];

        user_indicators
            .iter()
            .any(|indicator| body.contains(indicator))
    }

    /// Extract base URL from full URL
    fn extract_base_url(&self, url: &str) -> String {
        if let Ok(parsed) = url::Url::parse(url) {
            format!("{}://{}", parsed.scheme(), parsed.host_str().unwrap_or(""))
        } else {
            url.to_string()
        }
    }

    /// Build URL from base and path
    fn build_url(&self, base: &str, path: &str) -> String {
        let base_trimmed = base.trim_end_matches('/');
        let path_trimmed = path.trim_start_matches('/');
        format!("{}/{}", base_trimmed, path_trimmed)
    }

    /// Extract evidence from response body
    fn extract_evidence(&self, body: &str, max_len: usize) -> String {
        if body.len() > max_len {
            format!("{}...", &body[..max_len])
        } else {
            body.to_string()
        }
    }

    /// Create a vulnerability record
    fn create_vulnerability(
        &self,
        vuln_type: &str,
        url: &str,
        payload: &str,
        description: &str,
        severity: Severity,
        cwe: &str,
        cvss: f64,
    ) -> Vulnerability {
        let confidence = match severity {
            Severity::Critical | Severity::High => Confidence::High,
            Severity::Medium => Confidence::Medium,
            _ => Confidence::Low,
        };

        Vulnerability {
            id: format!("apifuzz_{}", uuid::Uuid::new_v4().to_string()),
            vuln_type: vuln_type.to_string(),
            severity,
            confidence,
            category: "API Security".to_string(),
            url: url.to_string(),
            parameter: None,
            payload: payload.to_string(),
            description: description.to_string(),
            evidence: Some(description.to_string()),
            cwe: cwe.to_string(),
            cvss: cvss as f32,
            verified: true,
            false_positive: false,
            remediation: self.get_remediation(vuln_type),
            discovered_at: chrono::Utc::now().to_rfc3339(),
            ml_data: None,
        }
    }

    /// Get remediation advice
    fn get_remediation(&self, vuln_type: &str) -> String {
        match vuln_type {
            "Unsafe HTTP Method Allowed" => "1. Disable unnecessary HTTP methods (TRACE, DELETE)\n\
                 2. Implement proper method-based access control\n\
                 3. Configure web server to reject unsafe methods\n\
                 4. Use method whitelisting instead of blacklisting"
                .to_string(),
            "Type Confusion Vulnerability" => "1. Implement strict input type validation\n\
                 2. Use schema validation (JSON Schema, OpenAPI)\n\
                 3. Reject unexpected data types\n\
                 4. Sanitize and validate all inputs"
                .to_string(),
            "Mass Assignment Vulnerability" => "1. Use allowlists for updatable fields\n\
                 2. Never bind request data directly to models\n\
                 3. Implement role-based field access control\n\
                 4. Use Data Transfer Objects (DTOs)\n\
                 5. Validate all field modifications"
                .to_string(),
            "IDOR - Insecure Direct Object Reference" => {
                "1. Implement proper authorization checks\n\
                 2. Use indirect object references (UUIDs)\n\
                 3. Verify user owns requested resource\n\
                 4. Implement access control lists (ACLs)\n\
                 5. Never expose sequential IDs"
                    .to_string()
            }
            "Broken Object Level Authorization" => "1. Implement authentication on all endpoints\n\
                 2. Verify user authorization for each resource\n\
                 3. Use middleware for consistent auth checks\n\
                 4. Implement least privilege principle\n\
                 5. Log all access attempts"
                .to_string(),
            "Missing Rate Limiting" => "1. Implement rate limiting per endpoint\n\
                 2. Use token bucket or sliding window algorithms\n\
                 3. Return 429 status when limit exceeded\n\
                 4. Implement different limits for authenticated users\n\
                 5. Monitor for rate limit abuse"
                .to_string(),
            "GraphQL Introspection Enabled" => "1. Disable introspection in production\n\
                 2. Use environment-based configuration\n\
                 3. Implement authentication for introspection\n\
                 4. Use GraphQL security tools\n\
                 5. Monitor introspection queries"
                .to_string(),
            "GraphQL Batch Query Attack Possible" => "1. Limit number of queries per request\n\
                 2. Implement query complexity analysis\n\
                 3. Set timeout limits for queries\n\
                 4. Use query cost analysis\n\
                 5. Monitor for abuse patterns"
                .to_string(),
            "JWT None Algorithm Vulnerability" => "1. Never accept 'none' algorithm\n\
                 2. Use strong algorithms (RS256, ES256)\n\
                 3. Validate algorithm in token header\n\
                 4. Implement proper JWT library\n\
                 5. Set token expiration\n\
                 6. Rotate signing keys regularly"
                .to_string(),
            "OAuth Redirect URI Not Validated" => "1. Implement strict redirect_uri validation\n\
                 2. Use exact match, not partial match\n\
                 3. Maintain allowlist of valid URIs\n\
                 4. Never use wildcards in validation\n\
                 5. Log all redirect attempts"
                .to_string(),
            _ => "Follow OWASP API Security Top 10 guidelines:\n\
                  1. Implement proper authentication and authorization\n\
                  2. Validate all inputs\n\
                  3. Use rate limiting\n\
                  4. Implement logging and monitoring\n\
                  5. Keep security libraries updated"
                .to_string(),
        }
    }
}

/// API endpoint information
#[derive(Debug, Clone)]
struct ApiEndpoint {
    url: String,
    api_type: ApiType,
    methods: Vec<String>,
}

/// API type enumeration
#[derive(Debug, Clone, PartialEq)]
enum ApiType {
    Rest,
    GraphQL,
    Grpc,
    None,
}

impl ApiType {
    fn as_str(&self) -> &str {
        match self {
            ApiType::Rest => "REST",
            ApiType::GraphQL => "GraphQL",
            ApiType::Grpc => "gRPC",
            ApiType::None => "None",
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::http_client::HttpClient;

    fn create_test_scanner() -> ApiFuzzerScanner {
        let http_client = Arc::new(HttpClient::new(30, 3).unwrap());
        ApiFuzzerScanner::new(http_client)
    }

    #[test]
    fn test_detect_api_type_rest() {
        let scanner = create_test_scanner();
        let body = r#"{"users": [{"id": 1}]}"#;
        let mut headers = HashMap::new();
        headers.insert("content-type".to_string(), "application/json".to_string());

        let api_type = scanner.detect_api_type(body, &headers);
        assert_eq!(api_type, ApiType::Rest);
    }

    #[test]
    fn test_detect_api_type_graphql() {
        let scanner = create_test_scanner();
        let body = r#"{"data": {"users": []}, "errors": []}"#;
        let mut headers = HashMap::new();
        headers.insert("content-type".to_string(), "application/json".to_string());

        let api_type = scanner.detect_api_type(body, &headers);
        assert_eq!(api_type, ApiType::GraphQL);
    }

    #[test]
    fn test_detect_api_type_grpc() {
        let scanner = create_test_scanner();
        let body = "";
        let mut headers = HashMap::new();
        headers.insert("content-type".to_string(), "application/grpc".to_string());

        let api_type = scanner.detect_api_type(body, &headers);
        assert_eq!(api_type, ApiType::Grpc);
    }

    #[test]
    fn test_detect_error_leakage() {
        let scanner = create_test_scanner();

        assert!(scanner.detect_error_leakage("Error at line 123"));
        assert!(scanner.detect_error_leakage("Exception in /home/user/app.js"));
        assert!(scanner.detect_error_leakage("Stack trace: ..."));
        assert!(!scanner.detect_error_leakage("Success"));
    }

    #[test]
    fn test_contains_user_data() {
        let scanner = create_test_scanner();

        assert!(scanner.contains_user_data(r#"{"email": "test@example.com"}"#));
        assert!(scanner.contains_user_data(r#"{"userId": 123}"#));
        assert!(!scanner.contains_user_data(r#"{"status": "ok"}"#));
    }

    #[test]
    fn test_build_url() {
        let scanner = create_test_scanner();

        assert_eq!(
            scanner.build_url("http://example.com", "/api/users"),
            "http://example.com/api/users"
        );
        assert_eq!(
            scanner.build_url("http://example.com/", "/api/users"),
            "http://example.com/api/users"
        );
        assert_eq!(
            scanner.build_url("http://example.com", "api/users"),
            "http://example.com/api/users"
        );
    }

    #[test]
    fn test_extract_evidence() {
        let scanner = create_test_scanner();

        let long_text = "A".repeat(500);
        let evidence = scanner.extract_evidence(&long_text, 100);
        assert_eq!(evidence.len(), 103); // 100 + "..."

        let short_text = "Short";
        let evidence = scanner.extract_evidence(short_text, 100);
        assert_eq!(evidence, "Short");
    }

    #[test]
    fn test_extract_base_url() {
        let scanner = create_test_scanner();

        assert_eq!(
            scanner.extract_base_url("http://example.com/api/users"),
            "http://example.com"
        );
        assert_eq!(
            scanner.extract_base_url("https://api.example.com/v1/data"),
            "https://api.example.com"
        );
    }

    #[test]
    fn test_create_vulnerability() {
        let scanner = create_test_scanner();

        let vuln = scanner.create_vulnerability(
            "Test Vulnerability",
            "http://example.com",
            "test payload",
            "Test description",
            Severity::High,
            "CWE-123",
            7.5,
        );

        assert_eq!(vuln.vuln_type, "Test Vulnerability");
        assert_eq!(vuln.severity, Severity::High);
        assert_eq!(vuln.confidence, Confidence::High);
        assert_eq!(vuln.cwe, "CWE-123");
        assert_eq!(vuln.cvss, 7.5);
    }
}