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
//! Query depth `DoS` detection module.
//!
//! Tests for deep nesting vulnerabilities that can cause denial of service
//! through resource exhaustion (CPU/memory). Many GraphQL implementations
//! don't limit query depth by default.
//!
//! # Attack Description
//!
//! Attackers send deeply nested queries like:
//! ```graphql
//! query {
//!   user {
//!     friends {
//!       friends {
//!         friends {
//!           friends { ... }
//!         }
//!       }
//!     }
//!   }
//! }
//! ```
//!
//! Each level may trigger database queries or computations, causing
//! exponential resource consumption.
//!
//! # Detection Method
//!
//! 1. Send progressively deeper queries (5, 10, 20, 50, 100+ levels)
//! 2. Measure response time and success rate
//! 3. Report if server accepts very deep queries without limits
//!
//! # Remediation
//!
//! Implement depth limiting:
//! - graphql-ruby: `max_depth 10`
//! - apollo-server: `validationRules: [depthLimit(10)]`
//! - graphene: middleware to calculate and limit depth

use anyhow::Result;
use scanclient::reqwest::header::CONTENT_TYPE;
use scanclient::ScanClient;

use crate::context::ScanContext;
use crate::schema::SchemaGraph;
use secfinding::{Finding, FindingKind, Severity};
use serde_json::json;
use std::fmt::Write as _;
use tracing::{debug, trace};

/// Depth levels to test, from shallow to deep.
const TEST_DEPTHS: [usize; 6] = [5, 10, 20, 50, 100, 200];

/// Maximum acceptable query depth before flagging as vulnerable.
const MAX_ACCEPTABLE_DEPTH: usize = 20;

/// Generate a deeply nested query string using the default `user`/`friends` pattern.
pub fn generate_deep_query(depth: usize) -> String {
    generate_deep_query_for_field(depth, "user", "friends")
}

/// Generate a deeply nested query using schema-derived field names when possible.
pub fn generate_deep_query_for_field(depth: usize, root: &str, nested: &str) -> String {
    let mut query = String::with_capacity(depth * 8 + 40);
    query.push_str("query DeepTest{");
    query.push_str(root);
    query.push('{');

    for _ in 0..depth {
        query.push_str(nested);
        query.push('{');
    }

    query.push_str("__typename");

    for _ in 0..depth {
        query.push('}');
    }

    query.push('}');
    query.push('}');

    query
}

/// Generate a deeply nested fragment query.
pub fn generate_fragment_query(depth: usize) -> String {
    let mut query = String::with_capacity(depth * 12 + 60);
    query.push_str("query FragmentTest{");
    query.push_str("user{...UserFields}}");
    query.push_str("fragment UserFields on User{");

    for i in 0..depth {
        let _ = write!(query, "f{i}:friends{{");
    }

    query.push_str("name");

    for _ in 0..depth {
        query.push('}');
    }

    query.push('}'); // close fragment
    query
}

/// Test for query depth `DoS` vulnerabilities.
///
/// Sends progressively deeper queries to identify if the server
/// implements proper depth limiting.
///
/// # Arguments
///
/// * `client` - The HTTP client for making requests
/// * `url` - The target GraphQL endpoint URL
///
/// # Returns
///
/// Returns findings if the server accepts dangerously deep queries.
///
/// # Errors
///
/// Returns an error if HTTP requests fail critically.
/// Run query depth checks using schema-derived nesting paths when available.
pub async fn test_with_context(client: &ScanClient, ctx: &ScanContext) -> Result<Vec<Finding>> {
    test_inner(client, ctx.url(), ctx.schema.as_ref()).await
}

/// Test for query depth `DoS` vulnerabilities.
pub async fn test(client: &ScanClient, url: &str) -> Result<Vec<Finding>> {
    test_inner(client, url, None).await
}

async fn test_inner(
    client: &ScanClient,
    url: &str,
    schema: Option<&SchemaGraph>,
) -> Result<Vec<Finding>> {
    let mut findings = Vec::new();
    let mut max_successful_depth: Option<usize> = None;

    let root = schema
        .and_then(|s| s.query_fields.first().map(|f| f.name.as_str()))
        .unwrap_or("user");
    let nested = schema
        .and_then(|s| s.nested_object_fields.first().map(|(_, c)| c.as_str()))
        .unwrap_or("friends");

    debug!(
        "Testing query depth limits on {} (root={}, nested={})",
        url, root, nested
    );

    // Test with progressively deeper queries
    for &depth in &TEST_DEPTHS {
        let query = generate_deep_query_for_field(depth, root, nested);

        match send_depth_test(client, url, &query).await? {
            DepthTestResult::Accepted(response_time_ms) => {
                trace!("Query depth {} accepted ({}ms)", depth, response_time_ms);
                max_successful_depth = Some(depth);
            }
            DepthTestResult::Rejected(reason) => {
                trace!("Query depth {} rejected: {}", depth, reason);
                break;
            }
            DepthTestResult::Error(e) => {
                debug!("Depth test error at depth {}: {}", depth, e);
            }
        }
    }

    // If we accepted very deep queries, report it
    if let Some(max_depth) = max_successful_depth {
        if max_depth > MAX_ACCEPTABLE_DEPTH {
            findings.push(create_finding(
                url,
                "GraphQL Query Depth Limit Missing",
                &format!(
                    "The GraphQL endpoint accepts queries with {max_depth}+ levels of nesting. \
                     This enables DoS attacks through resource exhaustion."
                ),
                Severity::High,
                "Implement query depth limiting. Maximum recommended depth: 10-20 levels.",
            )?);
        } else if max_depth > 10 {
            findings.push(create_finding(
                url,
                "GraphQL Query Depth Limit Too High",
                &format!(
                    "The GraphQL endpoint accepts queries with {max_depth}+ levels of nesting. \
                     Consider reducing the maximum allowed depth."
                ),
                Severity::Medium,
                "Reduce maximum query depth to 10-15 levels.",
            )?);
        }
    }

    // Test circular fragment detection
    match test_circular_fragments(client, url).await? {
        FragmentTestResult::CircularAccepted => {
            findings.push(create_finding(
                url,
                "GraphQL Circular Fragment Protection Missing",
                "The GraphQL endpoint accepts queries with circular fragment references. \
                 This can cause infinite loops and DoS.",
                Severity::High,
                "Implement detection and rejection of circular fragment references.",
            )?);
        }
        FragmentTestResult::CircularRejected => {
            trace!("Circular fragments properly rejected");
        }
        FragmentTestResult::Error(e) => {
            debug!("Circular fragment test error: {}", e);
        }
    }

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

/// Result of a single deep-query probe against a GraphQL endpoint.
///
/// Distinguishes between a server that accepts the query, one that rejects it
/// for depth/complexity reasons, and transport or parsing failures.
#[derive(Debug)]
pub enum DepthTestResult {
    /// The server processed the query successfully and returned HTTP 2xx with no
    /// depth-limit or complexity errors. The `u64` is the response time in
    /// milliseconds, which helps gauge whether deeper queries cause linear or
    /// exponential slowdown - an early indicator of resource-exhaustion `DoS`.
    Accepted(u64),
    /// The server refused the query for a depth, complexity, or schema reason.
    /// This is the secure behavior. The `String` carries a human-readable cause
    /// such as "Depth limit exceeded" or "Schema does not contain test fields".
    Rejected(String),
    /// The HTTP request failed or the server returned a non-2xx status that
    /// could not be interpreted as an intentional depth rejection.
    Error(String),
}

/// Send a single deep query and classify the server's response.
///
/// POSTs a JSON payload containing the provided GraphQL query string, then
/// interprets the HTTP status and response body to distinguish acceptance,
/// intentional depth rejection, and unexpected transport errors.
///
/// # Returns
///
/// * `DepthTestResult::Accepted` when the server returns HTTP 2xx with no
///   depth, complexity, or validation errors.
/// * `DepthTestResult::Rejected` when the response contains keywords
///   indicating depth limits, complexity limits, or missing test fields.
/// * `DepthTestResult::Error` for network failures or uninterpretable
///   server errors.
pub async fn send_depth_test(
    client: &ScanClient,
    url: &str,
    query: &str,
) -> Result<DepthTestResult> {
    let body = json!({ "query": query });
    let request = client
        .request(scanclient::reqwest::Method::POST, url)
        .header(CONTENT_TYPE, "application/json")
        .body(body.to_string());

    let start = std::time::Instant::now();
    let response = client.execute(request).await;
    let elapsed_ms = start.elapsed().as_millis().try_into().unwrap_or(u64::MAX);

    match response {
        Ok(resp) => {
            if !resp.status().is_success() {
                return Ok(DepthTestResult::Error(format!(
                    "Server returned {}",
                    resp.status()
                )));
            }
            let body_text = resp.body_text().unwrap_or_default();

            // Check for depth limit errors
            if body_text.contains("depth") && body_text.contains("exceed") {
                return Ok(DepthTestResult::Rejected(
                    "Depth limit exceeded".to_string(),
                ));
            }
            if body_text.contains("maximum") && body_text.contains("depth") {
                return Ok(DepthTestResult::Rejected(
                    "Maximum depth exceeded".to_string(),
                ));
            }
            if body_text.contains("Too complex") || body_text.contains("too complex") {
                return Ok(DepthTestResult::Rejected("Query too complex".to_string()));
            }

            // Check for validation errors that aren't depth-related
            if body_text.contains("errors") {
                let parsed: Result<serde_json::Value, _> = serde_json::from_str(body_text);
                if let Ok(json) = parsed {
                    if json.get("data").is_none() {
                        return Ok(DepthTestResult::Rejected(
                            "Query returned errors with no data".to_string(),
                        ));
                    }
                    if let Some(errors) = json.get("errors") {
                        let errors_str = errors.to_string().to_lowercase();
                        if errors_str.contains("depth")
                            || errors_str.contains("complexity")
                            || errors_str.contains("too deep")
                        {
                            return Ok(DepthTestResult::Rejected(
                                "Depth/complexity limit".to_string(),
                            ));
                        }
                        if errors_str.contains("unknown field")
                            || errors_str.contains("cannot query field")
                        {
                            return Ok(DepthTestResult::Rejected(
                                "Schema does not contain test fields".to_string(),
                            ));
                        }
                    }
                }
            }

            Ok(DepthTestResult::Accepted(elapsed_ms))
        }
        Err(e) => Ok(DepthTestResult::Error(e.to_string())),
    }
}

/// Outcome of probing the server with a self-referencing GraphQL fragment.
///
/// Circular fragment spreads can trigger infinite expansion loops or stack
/// exhaustion, making this a critical `DoS` vector distinct from simple depth
/// abuse.
#[derive(Debug)]
pub enum FragmentTestResult {
    /// The server accepted a query containing a circular fragment spread
    /// (`...A` inside fragment `A`). This means the parser/validator does not
    /// detect infinite recursion, enabling `DoS` via stack exhaustion or
    /// unbounded resolver loops.
    CircularAccepted,
    /// The server returned an error mentioning circularity, infinity, or
    /// spread violations. This is the secure behavior: the engine correctly
    /// detects and blocks the cycle before execution.
    CircularRejected,
    /// The response was ambiguous or the request failed, preventing a clear
    /// security verdict.
    Error(String),
}

/// Test whether the GraphQL engine detects and rejects circular fragment references.
///
/// Constructs a query where fragment `A` spreads itself inside
/// `friends { ...A }`, which would expand infinitely if not blocked. Sends
/// the query over HTTP POST and inspects the response for circularity
/// keywords or a clean `data` payload.
///
/// # Returns
///
/// * `FragmentTestResult::CircularAccepted` when the server returns HTTP 2xx
///   with non-null `data` and no errors, indicating the vulnerability is present.
/// * `FragmentTestResult::CircularRejected` when error text indicates the
///   server detected the cycle.
/// * `FragmentTestResult::Error` for network failures or ambiguous responses.
pub async fn test_circular_fragments(client: &ScanClient, url: &str) -> Result<FragmentTestResult> {
    // Query with self-referencing fragment
    let query = r"
        query CircularTest {
            user {
                ...A
            }
        }
        fragment A on User {
            friends {
                ...A
            }
        }
    ";

    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(FragmentTestResult::Error(format!(
                    "Server returned {}",
                    resp.status()
                )));
            }
            let body_text = resp.body_text().unwrap_or_default();

            // Check if circular reference was rejected
            if body_text.contains("circular")
                || body_text.contains("infinite")
                || body_text.contains("spread")
            {
                return Ok(FragmentTestResult::CircularRejected);
            }
            if body_text.contains("errors") {
                let parsed: Result<serde_json::Value, _> = serde_json::from_str(body_text);
                if let Ok(json) = parsed {
                    if let Some(errors) = json.get("errors") {
                        let errors_str = errors.to_string().to_lowercase();
                        if errors_str.contains("circular") || errors_str.contains("infinite") {
                            return Ok(FragmentTestResult::CircularRejected);
                        }
                    }
                }
            }

            // If no error about circularity and response contains non-null data, it 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_errors = parsed.as_ref().ok().and_then(|j| j.get("errors")).is_some();

            if has_non_null_data && !has_errors {
                return Ok(FragmentTestResult::CircularAccepted);
            }

            Ok(FragmentTestResult::Error("Unexpected response".to_string()))
        }
        Err(e) => Ok(FragmentTestResult::Error(e.to_string())),
    }
}

/// Build a standardized `Finding` for query-depth and circular-fragment vulnerabilities.
///
/// Assigns the scanner ID `"gqlprobe"`, tags `"graphql"`, `"dos"`, and
/// `"query-depth"`, and maps every finding to CWE-400 (Uncontrolled Resource
/// Consumption). The caller provides the `url`, human-readable `title`,
/// `detail`, `severity`, and `remediation` strings; this function wraps them
/// in the `Finding` builder so all depth-related findings share consistent
/// metadata and can be aggregated across scans.
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("dos")
        .tag("query-depth")
        .cwe("CWE-400") // Uncontrolled Resource Consumption
        .remediation(remediation)
        .build()?)
}