lonkero 3.7.0

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

/**
 * Bountyy Oy - GraphQL Security Scanner
 * Tests for GraphQL API vulnerabilities and misconfigurations
 *
 * @copyright 2026 Bountyy Oy
 * @license Proprietary - Enterprise Edition
 */
use crate::detection_helpers::AppCharacteristics;
use crate::http_client::HttpClient;
use crate::types::{Confidence, ScanConfig, Severity, Vulnerability};
use anyhow::Result;
use std::sync::Arc;
use tracing::info;

pub struct GraphQlScanner {
    http_client: Arc<HttpClient>,
}

impl GraphQlScanner {
    pub fn new(http_client: Arc<HttpClient>) -> Self {
        Self { http_client }
    }

    /// Scan URL for GraphQL vulnerabilities
    pub async fn scan(
        &self,
        url: &str,
        _config: &ScanConfig,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        info!("[GraphQL] Scanning: {}", url);

        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        // Test 1: Check if endpoint is GraphQL
        tests_run += 1;
        let is_graphql = self.detect_graphql_endpoint(url).await;

        if !is_graphql {
            info!("[NOTE] [GraphQL] Not a GraphQL endpoint, skipping");
            return Ok((vulnerabilities, tests_run));
        }

        // Store characteristics for intelligent testing
        if let Ok(response) = self.http_client.get(url).await {
            let _characteristics = AppCharacteristics::from_response(&response, url);
        }

        info!("[SUCCESS] [GraphQL] GraphQL endpoint detected");

        // Test 2: Check for introspection enabled
        tests_run += 1;
        if let Ok(response) = self.test_introspection(url).await {
            if self.check_introspection_enabled(&response, url, &mut vulnerabilities) {
                info!("[ALERT] [GraphQL] Introspection is enabled - critical finding");
            }
        }

        // Test 3: Test query depth limits
        tests_run += 1;
        if let Ok(response) = self.test_depth_attack(url).await {
            self.check_depth_limit(&response, url, &mut vulnerabilities);
        }

        // Test 4: Test batching attacks
        tests_run += 1;
        if let Ok(response) = self.test_batch_attack(url).await {
            self.check_batch_limit(&response, url, &mut vulnerabilities);
        }

        // Test 5: Test field duplication
        tests_run += 1;
        if let Ok(response) = self.test_field_duplication(url).await {
            self.check_field_duplication(&response, url, &mut vulnerabilities);
        }

        // Test 6: Test authorization bypass
        tests_run += 1;
        if let Ok(response) = self.test_auth_bypass(url).await {
            self.check_auth_bypass(&response, url, &mut vulnerabilities);
        }

        // Test 7: Test verbose error messages
        tests_run += 1;
        if let Ok(response) = self.test_error_disclosure(url).await {
            self.check_error_disclosure(&response, url, &mut vulnerabilities);
        }

        info!(
            "[SUCCESS] [GraphQL] Completed {} tests, found {} issues",
            tests_run,
            vulnerabilities.len()
        );

        Ok((vulnerabilities, tests_run))
    }

    /// Detect if endpoint is GraphQL
    async fn detect_graphql_endpoint(&self, url: &str) -> bool {
        // Try common GraphQL paths
        let graphql_paths = vec![
            "", // base URL (might already be /graphql)
            "/graphql",
            "/graphql/",
            "/api/graphql",
            "/query",
            "/gql",
        ];

        let base_url = url.trim_end_matches('/');

        for path in graphql_paths {
            let test_url = if path.is_empty() {
                base_url.to_string()
            } else {
                format!("{}{}", base_url, path)
            };

            // Try POST request (most common for GraphQL)
            let query = r#"{"query":"query{__typename}"}"#.to_string();
            if let Ok(response) = self.http_client.post(&test_url, query.clone()).await {
                if response.body.contains("__typename")
                    || response.body.contains("\"data\"")
                    || (response.body.contains("\"errors\"") && response.body.contains("query"))
                {
                    info!("[GraphQL] Found GraphQL endpoint at: {}", test_url);
                    return true;
                }
            }

            // Also try GET request with query param
            if let Ok(response) = self
                .http_client
                .get(&format!(
                    "{}?query={}",
                    test_url,
                    urlencoding::encode(&query)
                ))
                .await
            {
                if response.body.contains("__typename")
                    || response.body.contains("\"data\"")
                    || (response.body.contains("\"errors\"") && response.body.contains("query"))
                {
                    info!("[GraphQL] Found GraphQL endpoint at: {}", test_url);
                    return true;
                }
            }
        }

        false
    }

    /// Test introspection query
    async fn test_introspection(&self, url: &str) -> Result<crate::http_client::HttpResponse> {
        let introspection_query = r#"{
            "query": "query IntrospectionQuery { __schema { types { name kind description fields { name type { name kind ofType { name kind } } } } } }"
        }"#;

        self.http_client
            .get(&format!(
                "{}?query={}",
                url,
                urlencoding::encode(introspection_query)
            ))
            .await
    }

    /// Check if introspection is enabled
    fn check_introspection_enabled(
        &self,
        response: &crate::http_client::HttpResponse,
        url: &str,
        vulnerabilities: &mut Vec<Vulnerability>,
    ) -> bool {
        if response.body.contains("__schema") && response.body.contains("types") {
            vulnerabilities.push(self.create_vulnerability(
                "GraphQL Introspection Enabled",
                url,
                Severity::High,
                Confidence::High,
                "GraphQL introspection is publicly accessible - exposes entire API schema",
                "Introspection query returned full schema with types and fields".to_string(),
                r#"query IntrospectionQuery { __schema { types { name kind description fields { name type { name kind ofType { name kind } } } } } }"#.to_string(),
                6.5,
            ));
            return true;
        }
        false
    }

    /// Test query depth attack
    async fn test_depth_attack(&self, url: &str) -> Result<crate::http_client::HttpResponse> {
        // Create deeply nested query (20 levels deep)
        let deep_query = r#"{
            "query": "query { user { posts { author { posts { author { posts { author { posts { author { posts { author { posts { author { posts { author { posts { author { posts { author { name } } } } } } } } } } } } } } } } } } } }"
        }"#;

        self.http_client
            .get(&format!(
                "{}?query={}",
                url,
                urlencoding::encode(deep_query)
            ))
            .await
    }

    /// Check depth limit protection
    fn check_depth_limit(
        &self,
        response: &crate::http_client::HttpResponse,
        url: &str,
        vulnerabilities: &mut Vec<Vulnerability>,
    ) {
        // If deep query succeeds, depth limit is not enforced
        if response.status_code == 200
            && !response.body.contains("depth")
            && !response.body.contains("complexity")
        {
            vulnerabilities.push(self.create_vulnerability(
                "No GraphQL Query Depth Limit",
                url,
                Severity::Medium,
                Confidence::Medium,
                "GraphQL API does not enforce query depth limits - vulnerable to DoS",
                "Deeply nested query (20+ levels) was accepted without error".to_string(),
                r#"query { user { posts { author { posts { author { posts { author { posts { author { posts { author { posts { author { posts { author { posts { author { posts { author { name } } } } } } } } } } } } } } } } } } } }"#.to_string(),
                5.3,
            ));
        }
    }

    /// Test batching attack
    async fn test_batch_attack(&self, url: &str) -> Result<crate::http_client::HttpResponse> {
        // Send 100 queries in one batch
        let batch_query = r#"[
            {"query":"query{__typename}"},
            {"query":"query{__typename}"},
            {"query":"query{__typename}"},
            {"query":"query{__typename}"},
            {"query":"query{__typename}"}
        ]"#;

        self.http_client
            .get(&format!(
                "{}?query={}",
                url,
                urlencoding::encode(batch_query)
            ))
            .await
    }

    /// Check batch limit protection
    fn check_batch_limit(
        &self,
        response: &crate::http_client::HttpResponse,
        url: &str,
        vulnerabilities: &mut Vec<Vulnerability>,
    ) {
        // If batch succeeds, batching is allowed
        if response.status_code == 200 && (response.body.matches("__typename").count() > 1) {
            vulnerabilities.push(self.create_vulnerability(
                "GraphQL Query Batching Allowed",
                url,
                Severity::Medium,
                Confidence::High,
                "GraphQL API allows query batching - can be used for DoS or brute force",
                "Multiple queries in single request were executed".to_string(),
                r#"[{"query":"query{__typename}"},{"query":"query{__typename}"},{"query":"query{__typename}"},{"query":"query{__typename}"},{"query":"query{__typename}"}]"#.to_string(),
                5.0,
            ));
        }
    }

    /// Test field duplication attack
    async fn test_field_duplication(&self, url: &str) -> Result<crate::http_client::HttpResponse> {
        let duplicate_query = r#"{
            "query": "query { __typename __typename __typename __typename __typename __typename __typename __typename __typename __typename }"
        }"#;

        self.http_client
            .get(&format!(
                "{}?query={}",
                url,
                urlencoding::encode(duplicate_query)
            ))
            .await
    }

    /// Check field duplication protection
    fn check_field_duplication(
        &self,
        response: &crate::http_client::HttpResponse,
        url: &str,
        vulnerabilities: &mut Vec<Vulnerability>,
    ) {
        if response.status_code == 200 && response.body.matches("__typename").count() > 5 {
            vulnerabilities.push(self.create_vulnerability(
                "GraphQL Field Duplication Not Limited",
                url,
                Severity::Low,
                Confidence::Medium,
                "GraphQL allows unlimited field duplication - potential resource exhaustion",
                "Same field was queried multiple times in single query".to_string(),
                "query { __typename __typename __typename __typename __typename __typename __typename __typename __typename __typename }".to_string(),
                4.0,
            ));
        }
    }

    /// Test authorization bypass
    async fn test_auth_bypass(&self, url: &str) -> Result<crate::http_client::HttpResponse> {
        // Try to access admin/user queries without auth
        let auth_query = r#"{
            "query": "query { users { id email password } admin { id email } }"
        }"#;

        self.http_client
            .get(&format!(
                "{}?query={}",
                url,
                urlencoding::encode(auth_query)
            ))
            .await
    }

    /// Check for authorization bypass
    fn check_auth_bypass(
        &self,
        response: &crate::http_client::HttpResponse,
        url: &str,
        vulnerabilities: &mut Vec<Vulnerability>,
    ) {
        // Only report if the response contains actual data (not just error messages).
        // The test query asks for users with password/email fields.
        // Previously matched generic keywords like "email", "token", "admin" which
        // appear in error messages, documentation, and GraphQL schema descriptions,
        // causing massive false positives.
        //
        // Now we require:
        // 1. Response contains "data" key (actual GraphQL data response)
        // 2. Response does NOT contain "errors" as the primary response
        // 3. Actual user data pattern (not just keyword mention)
        let body = &response.body;
        let body_lower = body.to_lowercase();

        if response.status_code != 200 {
            return;
        }

        // Must be a successful data response, not an error
        let has_data = body.contains("\"data\"") && !body.contains("\"data\":null");
        let is_error_only =
            body.contains("\"errors\"") && (!body.contains("\"data\"") || body.contains("\"data\":null"));

        if !has_data || is_error_only {
            return;
        }

        // Look for actual sensitive data patterns - require structured data, not just keywords
        // Check for password hashes or plaintext passwords in user objects
        let has_password_data = body_lower.contains("\"password\":")
            && (body_lower.contains("\"email\":")
                || body_lower.contains("\"username\":"));

        // Check for actual SSN/credit card data patterns
        let has_pii_data = body_lower.contains("\"ssn\":")
            || body_lower.contains("\"credit_card\":")
            || body_lower.contains("\"social_security\":");

        if has_password_data || has_pii_data {
            let evidence = if has_password_data {
                "GraphQL returned user objects with password fields in data response"
            } else {
                "GraphQL returned PII data (SSN/credit card) in data response"
            };

            vulnerabilities.push(self.create_vulnerability(
                "GraphQL Authorization Bypass",
                url,
                Severity::Critical,
                Confidence::High,
                "GraphQL exposes sensitive fields without proper authorization",
                evidence.to_string(),
                "query { users { id email password } admin { id email } }".to_string(),
                8.2,
            ));
        }
    }

    /// Test error message disclosure
    async fn test_error_disclosure(&self, url: &str) -> Result<crate::http_client::HttpResponse> {
        // Send invalid query to trigger error
        let error_query = r#"{
            "query": "query { invalid_field_xyz_123 }"
        }"#;

        self.http_client
            .get(&format!(
                "{}?query={}",
                url,
                urlencoding::encode(error_query)
            ))
            .await
    }

    /// Check for verbose error messages
    fn check_error_disclosure(
        &self,
        response: &crate::http_client::HttpResponse,
        url: &str,
        vulnerabilities: &mut Vec<Vulnerability>,
    ) {
        let body_lower = response.body.to_lowercase();

        // Only check for ACTUALLY dangerous error disclosure.
        // GraphQL spec NORMALLY returns "line" and "column" in error locations -
        // that's standard behavior, NOT information disclosure.
        // "resolver" is also a normal GraphQL term.
        // Only flag when we see real backend details like stack traces,
        // file paths, database info, or exception details.
        let serious_indicators = vec![
            "stack",     // Stack trace
            "exception", // Exception details
            "trace",     // Trace output
            "file:",     // File path disclosure
            "database",  // Database info
            "sql",       // SQL query leak
            ".js:",      // JS file path
            ".py:",      // Python file path
            ".java:",    // Java file path
            ".rb:",      // Ruby file path
            "/app/",     // Server path disclosure
            "/src/",     // Source path disclosure
            "/home/",    // Home directory disclosure
        ];

        let mut found_indicators = Vec::new();
        for indicator in &serious_indicators {
            if body_lower.contains(indicator) {
                found_indicators.push(*indicator);
            }
        }

        // Require at least 2 serious indicators (not standard GraphQL error fields)
        if found_indicators.len() >= 2 {
            vulnerabilities.push(self.create_vulnerability(
                "GraphQL Verbose Error Messages",
                url,
                Severity::Low,
                Confidence::High,
                "GraphQL returns verbose error messages with backend details - information disclosure",
                format!("Error response contains: {:?}", found_indicators),
                "query { invalid_field_xyz_123 }".to_string(),
                3.7,
            ));
        }
    }

    /// Create vulnerability record
    fn create_vulnerability(
        &self,
        title: &str,
        url: &str,
        severity: Severity,
        confidence: Confidence,
        description: &str,
        evidence: String,
        payload: String,
        cvss: f32,
    ) -> Vulnerability {
        Vulnerability {
            id: format!("graphql_{}", uuid::Uuid::new_v4().to_string()),
            vuln_type: format!("GraphQL Vulnerability - {}", title),
            severity,
            confidence,
            category: "API Security".to_string(),
            url: url.to_string(),
            parameter: None,
            payload,
            description: description.to_string(),
            evidence: Some(evidence),
            cwe: "CWE-285".to_string(), // Improper Authorization
            cvss,
            verified: true,
            false_positive: false,
            remediation: r#"IMMEDIATE ACTION REQUIRED:

1. **Disable Introspection in Production**
   ```javascript
   // Apollo Server (Node.js)
   const server = new ApolloServer({
     introspection: process.env.NODE_ENV !== 'production',
     schema,
   });

   // GraphQL-Go
   h := handler.New(&handler.Config{
     Schema: &schema,
     Pretty: true,
     GraphiQL: false,  // Disable GraphiQL in production
   })
   ```

2. **Implement Query Depth Limiting**
   ```javascript
   // graphql-depth-limit (Node.js)
   const depthLimit = require('graphql-depth-limit');

   const server = new ApolloServer({
     validationRules: [depthLimit(10)],  // Max depth: 10
     schema,
   });
   ```

3. **Implement Query Complexity Limiting**
   ```javascript
   // graphql-query-complexity
   const { createComplexityLimitRule } = require('graphql-validation-complexity');

   const server = new ApolloServer({
     validationRules: [
       createComplexityLimitRule(1000)  // Max complexity: 1000
     ],
     schema,
   });
   ```

4. **Disable or Limit Query Batching**
   ```javascript
   const server = new ApolloServer({
     // Disable batching entirely
     allowBatchedHttpRequests: false,
     schema,
   });
   ```

5. **Implement Proper Authorization**
   ```javascript
   // Field-level authorization
   const typeDefs = gql`
     type User {
       id: ID!
       email: String @auth(requires: USER)
       password: String @auth(requires: ADMIN)
     }
   `;

   // Resolver-level checks
   const resolvers = {
     Query: {
       users: (parent, args, context) => {
         if (!context.user.isAdmin) {
           throw new Error('Unauthorized');
         }
         return getUsers();
       }
     }
   };
   ```

6. **Sanitize Error Messages**
   ```javascript
   const server = new ApolloServer({
     formatError: (err) => {
       // Log full error for debugging
       console.error(err);

       // Return sanitized error to client
       if (process.env.NODE_ENV === 'production') {
         return new Error('Internal server error');
       }
       return err;
     },
     schema,
   });
   ```

7. **Implement Rate Limiting**
   ```javascript
   // graphql-rate-limit
   const { createRateLimitDirective } = require('graphql-rate-limit-directive');

   const rateLimitDirective = createRateLimitDirective({
     identifyContext: (ctx) => ctx.user.id
   });

   const typeDefs = gql`
     type Query {
       users: [User!]! @rateLimit(limit: 100, duration: 60)
     }
   `;
   ```

8. **Use Query Allow Lists (Persisted Queries)**
   ```javascript
   // Only allow pre-approved queries
   const server = new ApolloServer({
     persistedQueries: {
       cache: new Map(),
     },
     schema,
   });
   ```

9. **Field-Level Pagination**
   ```javascript
   type Query {
     users(first: Int = 10, offset: Int = 0): [User!]!
   }
   // Enforce max page size server-side
   ```

10. **Security Headers**
    - Set appropriate CORS headers
    - Disable caching for sensitive queries
    - Use HTTPS only

11. **Monitoring and Logging**
    - Log all introspection attempts
    - Alert on suspicious query patterns
    - Monitor query complexity metrics
    - Track authentication failures

12. **Production Checklist**
    - [ ] Introspection disabled
    - [ ] Query depth limit: ≤ 10
    - [ ] Query complexity limit: ≤ 1000
    - [ ] Batching disabled or limited to 5
    - [ ] Field-level authorization implemented
    - [ ] Error messages sanitized
    - [ ] Rate limiting active
    - [ ] Persisted queries (optional but recommended)
    - [ ] HTTPS enforced
    - [ ] Security monitoring enabled

References:
- OWASP GraphQL Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/GraphQL_Cheat_Sheet.html
- GraphQL Security Best Practices: https://www.apollographql.com/blog/graphql/security/
- Escape GraphQL Security Guide: https://escape.tech/blog/9-graphql-security-best-practices/
"#
            .to_string(),
            discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
        }
    }
}

// UUID generation helper
mod uuid {
    use rand::Rng;

    pub struct Uuid;

    impl Uuid {
        pub fn new_v4() -> Self {
            Self
        }

        pub fn to_string(&self) -> String {
            let mut rng = rand::rng();
            format!(
                "{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
                rng.random::<u32>(),
                rng.random::<u16>(),
                rng.random::<u16>(),
                rng.random::<u16>(),
                rng.random::<u64>() & 0xffffffffffff
            )
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    #[test]
    fn test_graphql_detection() {
        let scanner = GraphQlScanner::new(Arc::new(HttpClient::new(5, 2).unwrap()));

        // Simulate GraphQL response
        let response = crate::http_client::HttpResponse {
            status_code: 200,
            body: r#"{"data":{"__typename":"Query"}}"#.to_string(),
            headers: HashMap::new(),
            duration_ms: 100,
        };

        assert!(response.body.contains("__typename"));
        assert!(response.body.contains("\"data\""));
    }

    #[test]
    fn test_introspection_detection() {
        let scanner = GraphQlScanner::new(Arc::new(HttpClient::new(5, 2).unwrap()));

        let response = crate::http_client::HttpResponse {
            status_code: 200,
            body: r#"{"data":{"__schema":{"types":[{"name":"Query","kind":"OBJECT"}]}}}"#
                .to_string(),
            headers: HashMap::new(),
            duration_ms: 100,
        };

        let mut vulns = Vec::new();
        let result = scanner.check_introspection_enabled(
            &response,
            "https://api.example.com/graphql",
            &mut vulns,
        );

        assert!(result, "Should detect introspection enabled");
        assert_eq!(vulns.len(), 1);
        assert_eq!(vulns[0].severity, Severity::High);
    }

    #[test]
    fn test_batch_detection() {
        let scanner = GraphQlScanner::new(Arc::new(HttpClient::new(5, 2).unwrap()));

        let response = crate::http_client::HttpResponse {
            status_code: 200,
            body: r#"[{"data":{"__typename":"Query"}},{"data":{"__typename":"Query"}}]"#
                .to_string(),
            headers: HashMap::new(),
            duration_ms: 100,
        };

        let mut vulns = Vec::new();
        scanner.check_batch_limit(&response, "https://api.example.com/graphql", &mut vulns);

        assert_eq!(vulns.len(), 1, "Should detect batching allowed");
        assert_eq!(vulns[0].severity, Severity::Medium);
    }

    #[test]
    fn test_auth_bypass_detection() {
        let scanner = GraphQlScanner::new(Arc::new(HttpClient::new(5, 2).unwrap()));

        let response = crate::http_client::HttpResponse {
            status_code: 200,
            body:
                r#"{"data":{"users":[{"id":"1","email":"admin@example.com","password":"hashed"}]}}"#
                    .to_string(),
            headers: HashMap::new(),
            duration_ms: 100,
        };

        let mut vulns = Vec::new();
        scanner.check_auth_bypass(&response, "https://api.example.com/graphql", &mut vulns);

        assert!(vulns.len() > 0, "Should detect sensitive field exposure");
        assert_eq!(vulns[0].severity, Severity::Critical);
    }

    #[test]
    fn test_error_disclosure() {
        let scanner = GraphQlScanner::new(Arc::new(HttpClient::new(5, 2).unwrap()));

        let response = crate::http_client::HttpResponse {
            status_code: 400,
            body: r#"{"errors":[{"message":"Cannot query field on type at line 1 column 5","locations":[{"line":1,"column":5}],"stack":"Error: Cannot query\n  at file: /app/resolvers.js:123"}]}"#.to_string(),
            headers: HashMap::new(),
            duration_ms: 100,
        };

        let mut vulns = Vec::new();
        scanner.check_error_disclosure(&response, "https://api.example.com/graphql", &mut vulns);

        assert_eq!(vulns.len(), 1, "Should detect verbose errors");
        assert_eq!(vulns[0].severity, Severity::Low);
    }
}