gqlprobe 1.0.0

Fast GraphQL security scanner - schema-aware introspection, injection, DoS, CSRF, auth bypass, SARIF
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
//! Directive abuse detection module.
//!
//! Detects if the GraphQL endpoint allows excessive or dangerous directive
//! usage that can lead to `DoS` or information disclosure.
//!
//! # Attack Description
//!
//! GraphQL directives like @include and @skip can be abused:
//!
//! 1. **Directive Overloading**: Hundreds of directives in one query
//! 2. **Deprecated Field Access**: Using @deprecated to find old fields
//! 3. **Skip/Include Abuse**: Complex conditional logic causing CPU load
//!
//! Example of directive overload:
//! ```graphql
//! query {
//!   user @include(if: true) @include(if: true) @include(if: true) ...
//! }
//! ```
//!
//! # Detection Method
//!
//! 1. Send queries with excessive @include/@skip directives
//! 2. Test for deprecated field introspection
//! 3. Check directive repetition limits
//!
//! # Remediation
//!
//! - Limit number of directives per query
//! - Disable deprecated field introspection in production
//! - Implement query complexity analysis

use anyhow::Result;

use crate::context::ScanContext;
use scanclient::reqwest::header::CONTENT_TYPE;
use scanclient::ScanClient;
use secfinding::{Finding, FindingKind, Severity};
use serde_json::json;
use tracing::{debug, trace};

/// Number of repeated directives to test.
pub const DIRECTIVE_REPETITIONS: [usize; 4] = [10, 50, 100, 200];

/// Test for directive abuse vulnerabilities.
///
/// Sends queries with excessive directives to test for:
/// - Unbounded directive repetition
/// - Deprecated field introspection
/// - Directive-based `DoS`
///
/// # Arguments
///
/// * `client` - The HTTP client for making requests
/// * `url` - The target GraphQL endpoint URL
///
/// # Returns
///
/// Returns findings if directive abuse is possible.
///
/// # Errors
///
/// Returns an error if HTTP requests fail critically.
pub async fn test_with_context(client: &ScanClient, ctx: &ScanContext) -> Result<Vec<Finding>> {
    test(client, ctx.url()).await
}

/// Test for directive abuse vulnerabilities.
pub async fn test(client: &ScanClient, url: &str) -> Result<Vec<Finding>> {
    let mut findings = Vec::new();

    debug!("Testing directive abuse on {}", url);

    // Test 1: Directive repetition (many @include on same field)
    match test_directive_repetition(client, url).await? {
        DirectiveRepetitionResult::Vulnerable(count) => {
            findings.push(create_finding(
                url,
                "GraphQL Directive Repetition Unbounded",
                &format!(
                    "The GraphQL endpoint accepts queries with {count}+ repeated directives. \
                     This can be used for DoS attacks by overwhelming the parser."
                ),
                Severity::Medium,
                "Implement limits on the number of directives per field/query. \
                 Maximum recommended: 10-20 directives per field.",
            )?);
        }
        DirectiveRepetitionResult::Limited(limit) => {
            trace!("Directive repetition limited at {}", limit);
        }
        DirectiveRepetitionResult::Error(e) => {
            debug!("Directive repetition test error: {}", e);
        }
    }

    // Test 2: Deprecated field introspection
    match test_deprecated_introspection(client, url).await? {
        DeprecatedTestResult::Enabled(response) => {
            findings.push(create_finding(
                url,
                "GraphQL Deprecated Field Introspection Enabled",
                "The GraphQL endpoint exposes deprecated field information through introspection. \
                 This can reveal old API surfaces that should be hidden.",
                Severity::Low,
                "Disable deprecated field introspection in production or filter it from responses.",
            )?);

            // Add evidence
            if let Some(_idx) = findings
                .iter()
                .position(|f| f.title() == "GraphQL Deprecated Field Introspection Enabled")
            {
                let excerpt = if response.chars().count() > 500 {
                    format!(
                        "{}...[truncated]",
                        response.chars().take(500).collect::<String>()
                    )
                } else {
                    response
                };
                // Note: We already created the finding, evidence is limited in this design
                let _ = excerpt;
            }
        }
        DeprecatedTestResult::Disabled => {
            trace!("Deprecated field introspection disabled");
        }
        DeprecatedTestResult::Error(e) => {
            debug!("Deprecated introspection test error: {}", e);
        }
    }

    // Test 3: Multiple directive locations
    match test_multiple_directives(client, url).await? {
        MultipleDirectiveResult::Vulnerable(count) => {
            findings.push(create_finding(
                url,
                "GraphQL Multiple Directives Abuse Possible",
                &format!(
                    "The GraphQL endpoint allows {count}+ different directives in a single query. \
                     This increases attack surface for directive-based attacks."
                ),
                Severity::Low,
                "Review and limit the number of custom directives. \
                 Validate directive combinations for safety.",
            )?);
        }
        MultipleDirectiveResult::Limited => {
            trace!("Multiple directives properly limited");
        }
        MultipleDirectiveResult::Error(e) => {
            debug!("Multiple directives test error: {}", e);
        }
    }

    debug!("Directive abuse test complete: {} findings", findings.len());
    Ok(findings)
}

/// Outcome of the directive-repetition probe.
///
/// This enum distinguishes three endpoint behaviors when confronted with
/// queries that repeat the same directive many times on a single field.
#[derive(Debug)]
pub enum DirectiveRepetitionResult {
    /// The endpoint accepted a large number of repeated directives without
    /// enforcing a limit, indicating a potential `DoS` vector via parser or
    /// validator overload.
    Vulnerable(usize),
    /// The endpoint rejected the query after `limit` repetitions, showing
    /// that a directive cap is in place.
    Limited(usize),
    /// A network or unexpected server error prevented a clear determination.
    Error(String),
}

/// Probe the endpoint for unbounded directive repetition.
///
/// Sends a sequence of queries that append `@include(if: true)` an
/// increasing number of times to a single field.  The function walks
/// through [`DIRECTIVE_REPETITIONS`] and stops when the server signals
/// a limit or when the highest count is accepted.
///
/// # When it returns each variant
///
/// - `Vulnerable` - the server accepted 100+ repetitions with no cap.
/// - `Limited`   - the server accepted some repetitions but eventually
///   refused the query with a directive-limit error.
/// - `Error`     - the HTTP request failed or the response was
///   inconclusive.
pub async fn test_directive_repetition(
    client: &ScanClient,
    url: &str,
) -> Result<DirectiveRepetitionResult> {
    let mut max_accepted = 0;
    let mut found_limit = false;

    for &count in &DIRECTIVE_REPETITIONS {
        let directives = " @include(if: true)".repeat(count);
        let query = format!("query {{ user{directives} {{ name }} }}");

        let body = json!({ "query": query });
        let request = client
            .request(scanclient::reqwest::Method::POST, url)
            .header(CONTENT_TYPE, "application/json")
            .body(body.to_string());

        match client.execute(request).await {
            Ok(resp) => {
                if !resp.status().is_success() {
                    return Ok(DirectiveRepetitionResult::Error(format!(
                        "Server returned {}",
                        resp.status()
                    )));
                }
                let body_text = resp.body_text().unwrap_or_default();

                // Check for directive limit errors
                if body_text.contains("directive") && body_text.contains("limit") {
                    found_limit = true;
                    break;
                }
                if body_text.contains("too many") && body_text.contains("directive") {
                    found_limit = true;
                    break;
                }

                // Check for validation errors
                if let Ok(json) = serde_json::from_str::<serde_json::Value>(body_text) {
                    if let Some(errors) = json.get("errors") {
                        let errors_str = errors.to_string().to_lowercase();
                        if errors_str.contains("directive")
                            && (errors_str.contains("limit") || errors_str.contains("maximum"))
                        {
                            found_limit = true;
                            break;
                        }
                    }
                }

                // If response has non-null data without directive-related errors, count was accepted
                let parsed = serde_json::from_str::<serde_json::Value>(body_text);
                let has_non_null_data = parsed
                    .as_ref()
                    .ok()
                    .and_then(|j| j.get("data"))
                    .is_some_and(|d| !d.is_null());
                let has_directive_error = parsed
                    .as_ref()
                    .ok()
                    .and_then(|j| j.get("errors"))
                    .and_then(|e| e.as_array())
                    .is_some_and(|arr| {
                        arr.iter().any(|e| {
                            let msg = e
                                .get("message")
                                .and_then(|m| m.as_str())
                                .unwrap_or("")
                                .to_lowercase();
                            msg.contains("directive")
                                || msg.contains("limit")
                                || msg.contains("maximum")
                        })
                    });

                if has_non_null_data && !has_directive_error {
                    max_accepted = count;
                }
            }
            Err(e) => {
                return Ok(DirectiveRepetitionResult::Error(e.to_string()));
            }
        }
    }

    if max_accepted >= 100 && !found_limit {
        Ok(DirectiveRepetitionResult::Vulnerable(max_accepted))
    } else if max_accepted > 0 {
        Ok(DirectiveRepetitionResult::Limited(max_accepted))
    } else {
        Ok(DirectiveRepetitionResult::Error(
            "No successful tests".to_string(),
        ))
    }
}

/// Outcome of the deprecated-field introspection probe.
///
/// GraphQL schemas can flag fields as `@deprecated`.  Exposing this
/// metadata through introspection leaks old API surfaces that may
/// contain vulnerabilities or sensitive logic.
#[derive(Debug)]
pub enum DeprecatedTestResult {
    /// The introspection query returned `isDeprecated` or
    /// `deprecationReason` data, meaning deprecated field metadata is
    /// exposed to any client.
    Enabled(String),
    /// The server either disabled introspection entirely or did not
    /// return deprecation metadata.
    Disabled,
    /// A network or parsing error prevented a clear determination.
    Error(String),
}

/// Probe whether the endpoint leaks deprecated field metadata.
///
/// Sends an introspection query asking for `__type(name: "Query")`
/// fields together with their `isDeprecated` and `deprecationReason`
/// attributes.
///
/// # When it returns each variant
///
/// - `Enabled`  - the response body contains deprecation fields,
///   proving the schema exposes historical API surface.
/// - `Disabled` - introspection is off or the deprecation data is
///   stripped from the response.
/// - `Error`    - the HTTP request failed.
pub async fn test_deprecated_introspection(
    client: &ScanClient,
    url: &str,
) -> Result<DeprecatedTestResult> {
    // Query for deprecated fields via introspection
    let query = r#"
        {
            __type(name: "Query") {
                fields {
                    name
                    isDeprecated
                    deprecationReason
                }
            }
        }
    "#;

    let body = json!({ "query": query });
    let request = client
        .request(scanclient::reqwest::Method::POST, url)
        .header(CONTENT_TYPE, "application/json")
        .body(body.to_string());

    match client.execute(request).await {
        Ok(resp) => {
            let body_text = resp.body_text().unwrap_or_default();

            // Check if response contains deprecation info
            if body_text.contains("isDeprecated") || body_text.contains("deprecationReason") {
                // Check if we actually got data (not just an error about introspection)
                if let Ok(json) = serde_json::from_str::<serde_json::Value>(body_text) {
                    // Check if the data actually contains deprecation info, regardless of errors
                    if json.get("data").is_some()
                        && (body_text.contains("isDeprecated")
                            || body_text.contains("deprecationReason"))
                    {
                        return Ok(DeprecatedTestResult::Enabled(body_text.to_string()));
                    }
                }
            }

            // Check if introspection itself is disabled
            if body_text.contains("introspection") && body_text.contains("disabled") {
                return Ok(DeprecatedTestResult::Disabled);
            }

            Ok(DeprecatedTestResult::Disabled)
        }
        Err(e) => Ok(DeprecatedTestResult::Error(e.to_string())),
    }
}

/// Outcome of the multiple-directive-locations probe.
///
/// Some GraphQL implementations allow many distinct directives to be
/// stacked on a single field or spread across several locations.
/// Accepting an excessive number increases the attack surface for
/// directive-based `DoS` or logic-abuse attacks.
#[derive(Debug)]
pub enum MultipleDirectiveResult {
    /// The endpoint accepted a query with several different directives
    /// without error, suggesting loose directive validation.
    Vulnerable(usize),
    /// The endpoint rejected the query because of a directive limit
    /// or validation rule.
    Limited,
    /// A network or unexpected server error prevented a clear
    /// determination.
    Error(String),
}

/// Probe the endpoint for acceptance of multiple distinct directives.
///
/// Sends a single query that applies `@include`, `@skip`, and
/// additional directives on multiple fields.  If the server returns
/// data without errors, the endpoint is assumed to allow unconstrained
/// directive stacking.
///
/// # When it returns each variant
///
/// - `Vulnerable` - the server executed the query with 4+ directives
///   and returned no GraphQL errors.
/// - `Limited`    - the server responded with a directive-limit or
///   validation error.
/// - `Error`      - the HTTP request itself failed.
pub async fn test_multiple_directives(
    client: &ScanClient,
    url: &str,
) -> Result<MultipleDirectiveResult> {
    // Query with many different directive types
    let query = r"
        query ($include: Boolean!, $skip: Boolean!) {
            user @include(if: $include) @skip(if: $skip) {
                name
                email @include(if: $include)
                id @skip(if: $skip)
            }
        }
    ";

    let body = json!({
        "query": query,
        "variables": {
            "include": true,
            "skip": false
        }
    });

    let request = client
        .request(scanclient::reqwest::Method::POST, url)
        .header(CONTENT_TYPE, "application/json")
        .body(body.to_string());

    match client.execute(request).await {
        Ok(resp) => {
            if !resp.status().is_success() {
                return Ok(MultipleDirectiveResult::Error(format!(
                    "Server returned {}",
                    resp.status()
                )));
            }
            let body_text = resp.body_text().unwrap_or_default();

            // If multiple directives work, we count this as accepting multiple
            if !body_text.contains("errors") {
                return Ok(MultipleDirectiveResult::Vulnerable(4));
            }

            // Check for specific directive limit errors
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(body_text) {
                if let Some(errors) = json.get("errors") {
                    let errors_str = errors.to_string().to_lowercase();
                    if errors_str.contains("directive")
                        && (errors_str.contains("limit") || errors_str.contains("maximum"))
                    {
                        return Ok(MultipleDirectiveResult::Limited);
                    }
                }
            }

            Ok(MultipleDirectiveResult::Limited)
        }
        Err(e) => Ok(MultipleDirectiveResult::Error(e.to_string())),
    }
}

/// Build a [`Finding`] for a directive-abuse vulnerability.
///
/// Assigns:
/// - **Scanner ID** (`gqlprobe`) and the target `url`.
/// - **Severity** - caller-supplied (`Medium` for repetition, `Low`
///   for introspection and multiple-directive issues).
/// - **Kind** - [`FindingKind::Vulnerability`].
/// - **Tags** - `graphql`, `directive`, `dos`.
/// - **CWE** - `CWE-400` (Uncontrolled Resource Consumption), because
///   unbounded directives are fundamentally a resource-consumption
///   issue.
///
/// The caller provides the human-readable `title`, `detail`, and
/// `remediation` strings.
pub fn create_finding(
    url: &str,
    title: &str,
    detail: &str,
    severity: Severity,
    remediation: &str,
) -> Result<Finding> {
    Ok(Finding::builder("gqlprobe", url, severity)
        .title(title)
        .detail(detail)
        .kind(FindingKind::Vulnerability)
        .tag("graphql")
        .tag("directive")
        .tag("dos")
        .cwe("CWE-400") // Uncontrolled Resource Consumption
        .remediation(remediation)
        .build()?)
}