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
//! Query batching abuse detection module.
//!
//! Detects if the GraphQL endpoint accepts batched queries without proper
//! limits, which can be used for `DoS` or to bypass rate limiting.
//!
//! # Attack Description
//!
//! GraphQL batching allows sending multiple operations in a single HTTP request:
//! ```json
//! [
//!   {"query": "query { user(id: 1) { name } }"},
//!   {"query": "query { user(id: 2) { name } }"},
//!   {"query": "query { user(id: 3) { name } }"},
//!   ... hundreds more ...
//! ]
//! ```
//!
//! This can:
//! - Bypass rate limits (counts as one HTTP request)
//! - Amplify `DoS` attacks
//! - Enable brute force attacks more efficiently
//!
//! # Detection Method
//!
//! 1. Send batch requests with increasing sizes
//! 2. Check if all queries are processed
//! 3. Report if no batch size limits exist
//!
//! # Remediation
//!
//! Implement batch size limiting:
//! - apollo-server: `maxBatchSize: 10`
//! - Custom middleware to reject large batches
//! - Rate limit based on operation count, not just requests

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

use crate::context::ScanContext;
use secfinding::{Finding, FindingKind, Severity};
use serde_json::json;
use tracing::{debug, trace};

/// Batch sizes to test, from small to large.
pub const TEST_BATCH_SIZES: [usize; 5] = [5, 10, 25, 50, 100];

/// Maximum acceptable batch size before flagging as vulnerable.
const MAX_ACCEPTABLE_BATCH_SIZE: usize = 25;

/// Re-export alias query generator (see [`crate::modules::alias_abuse`]).
pub use crate::modules::alias_abuse::generate_alias_abuse_query_legacy as generate_alias_abuse_query;

/// Construct a JSON array of GraphQL operations for batch-size probing.
///
/// Each element is an independent query with a distinct field alias, allowing
/// the scanner to detect how many operations the server will process in a
/// single HTTP request.
///
/// # Attack vector
///
/// GraphQL batching is legitimate, but endpoints that do not enforce an upper
/// bound allow attackers to bypass HTTP-level rate limiters and amplify `DoS`
/// or brute-force attacks by packing many operations into one request.
pub fn generate_batch(size: usize) -> Vec<serde_json::Value> {
    let mut batch = Vec::with_capacity(size);
    for i in 0..size {
        batch.push(json!({
            "query": format!("query Batch{{user{}:user(id:\"__gqlprobe_batch_{}\"){{name}}}}", i, i),
        }));
    }
    batch
}

/// Test for query batching abuse vulnerabilities.
///
/// Sends batched queries of increasing size to test if the server
/// implements proper batch size limits.
///
/// # Arguments
///
/// * `client` - The HTTP client for making requests
/// * `url` - The target GraphQL endpoint URL
///
/// # Returns
///
/// Returns findings if the server accepts dangerously large batches.
///
/// # Errors
///
/// Returns an error if HTTP requests fail critically.
/// Run batching checks using shared scan context.
pub async fn test_with_context(client: &ScanClient, ctx: &ScanContext) -> Result<Vec<Finding>> {
    test(client, ctx.url()).await
}

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

    debug!("Testing query batching on {}", url);

    // Test with progressively larger batches
    for &size in &TEST_BATCH_SIZES {
        let batch = generate_batch(size);

        match send_batch_test(client, url, &batch).await? {
            BatchTestResult::AllProcessed(count) => {
                trace!("Batch size {} processed ({} operations)", size, count);
                max_successful_batch = Some(size);
            }
            BatchTestResult::PartiallyProcessed(processed, rejected) => {
                trace!(
                    "Batch size {} partially processed: {}/{} accepted",
                    size,
                    processed,
                    processed + rejected
                );
                break;
            }
            BatchTestResult::Rejected(reason) => {
                trace!("Batch size {} rejected: {}", size, reason);
                break;
            }
            BatchTestResult::Error(e) => {
                debug!("Batch test error at size {}: {}", size, e);
            }
        }
    }

    // If we accepted very large batches, report it
    if let Some(max_size) = max_successful_batch {
        if max_size > MAX_ACCEPTABLE_BATCH_SIZE {
            findings.push(create_finding(
                url,
                "GraphQL Query Batching Unbounded",
                &format!(
                    "The GraphQL endpoint accepts batches of {max_size}+ queries without limits. \
                     This enables DoS attacks and rate limit bypass."
                ),
                Severity::Medium,
                "Implement batch size limiting. Maximum recommended: 10-25 operations per batch.",
            )?);
        } else if max_size > 10 {
            findings.push(create_finding(
                url,
                "GraphQL Query Batching Limit Too High",
                &format!(
                    "The GraphQL endpoint accepts batches of {max_size}+ queries. \
                     Consider reducing the maximum batch size."
                ),
                Severity::Low,
                "Reduce maximum batch size to 10-15 operations.",
            )?);
        }
    }

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

/// Outcome of sending a batched GraphQL request to the target endpoint.
///
/// Batched queries are JSON arrays of GraphQL operations sent in a single HTTP
/// POST. The server may process all items, reject the batch entirely, or accept
/// only a subset. This enum captures that behavior so the scanner can decide
/// whether the endpoint enforces safe batch-size limits.
#[derive(Debug)]
pub enum BatchTestResult {
    /// Every operation in the batch was processed and at least one response
    /// contained non-null `data`.
    ///
    /// Returned when the server accepts the full batch without enforcing size
    /// limits. The embedded `usize` is the number of operations executed.
    /// This result is a prerequisite for flagging unbounded batching abuse.
    AllProcessed(usize),
    /// The server accepted fewer operations than were sent.
    ///
    /// The first `usize` is the count of processed items; the second is the
    /// count of rejected items. This indicates the presence of a batch-size
    /// limit or rate limit, which is the desired defensive behavior.
    PartiallyProcessed(usize, usize),
    /// The server rejected the entire batch.
    ///
    /// The string explains why (e.g. *Batch size limit exceeded*). This is
    /// returned when the response contains explicit limit-exceeded messages or
    /// when every item in the batch returns an error.
    Rejected(String),
    /// The HTTP request succeeded but the response could not be parsed, or the
    /// request itself failed.
    ///
    /// Contains a human-readable description of the failure. This variant
    /// prevents a single malformed response from aborting the entire scan.
    Error(String),
}

/// Transmit a JSON array of GraphQL operations and classify the response.
///
/// # Returns
///
/// - [`BatchTestResult::AllProcessed`] when every item is executed and at
///   least one response contains non-null `data`. This means the server does
///   not limit batch size, which is a security concern for large arrays.
/// - [`BatchTestResult::PartiallyProcessed`] when the response array is
///   shorter than the request array, indicating a partial limit.
/// - [`BatchTestResult::Rejected`] when the server returns an explicit batch
///   limit error or when every item returns an error.
/// - [`BatchTestResult::Error`] when the response cannot be parsed or the
///   request fails.
pub async fn send_batch_test(
    client: &ScanClient,
    url: &str,
    batch: &[serde_json::Value],
) -> Result<BatchTestResult> {
    let body = serde_json::to_string(batch)?;
    let request = client
        .request(scanclient::reqwest::Method::POST, url)
        .header(CONTENT_TYPE, "application/json")
        .body(body);

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

            // Check for batch limit errors
            if body_text.contains("batch") && body_text.contains("exceed") {
                return Ok(BatchTestResult::Rejected(
                    "Batch size limit exceeded".to_string(),
                ));
            }
            if body_text.contains("maximum") && body_text.contains("batch") {
                return Ok(BatchTestResult::Rejected(
                    "Maximum batch size exceeded".to_string(),
                ));
            }

            // Try to parse response as array and verify at least one has non-null data
            let parsed: Result<Vec<serde_json::Value>, _> = serde_json::from_str(body_text);
            if let Ok(responses) = parsed {
                let count = responses.len();
                let has_any_data = responses
                    .iter()
                    .any(|r| r.get("data").is_some_and(|d| !d.is_null()));
                if count == batch.len() {
                    if has_any_data {
                        return Ok(BatchTestResult::AllProcessed(count));
                    }
                    // All responses are errors - server rejected the batch
                    return Ok(BatchTestResult::Rejected(
                        "All batch items returned errors".to_string(),
                    ));
                }
                return Ok(BatchTestResult::PartiallyProcessed(
                    count,
                    batch.len() - count,
                ));
            }

            // Check for single response with errors
            let single_parsed: Result<serde_json::Value, _> = serde_json::from_str(body_text);
            if let Ok(json) = single_parsed {
                if json.get("errors").is_some() {
                    return Ok(BatchTestResult::Rejected("Batch rejected".to_string()));
                }
                // Single response for batch might mean only first query processed
                return Ok(BatchTestResult::PartiallyProcessed(1, batch.len() - 1));
            }

            Ok(BatchTestResult::Error(
                "Could not parse response".to_string(),
            ))
        }
        Err(e) => Ok(BatchTestResult::Error(e.to_string())),
    }
}

/// Outcome of probing the endpoint for alias-based Denial-of-Service abuse.
///
/// Alias abuse allows an attacker to execute many expensive field resolutions
/// inside a single GraphQL query by renaming the same field many times
/// (e.g. `u0:user(id:0){name} u1:user(id:1){name} ...`). This enum records
/// whether the server accepted the abusive query, rejected it, or failed to
/// produce a conclusive response.
#[derive(Debug)]
pub enum AliasTestResult {
    /// The server processed the query containing many aliases and returned
    /// non-null `data` without errors.
    ///
    /// The embedded `usize` is the number of aliases that were accepted.
    /// This indicates the absence of alias limits or query-complexity checks,
    /// making the endpoint susceptible to amplification `DoS`.
    Vulnerable(usize),
    /// The server rejected the alias-heavy query.
    ///
    /// Returned when the response mentions alias limits, complexity limits, or
    /// returns errors that explicitly reference aliases. This is the desired
    /// defensive posture.
    Protected,
    /// The probe did not yield a conclusive security result.
    ///
    /// Contains a description of the unexpected condition (e.g. network
    /// failure or an unparseable response).
    Error(String),
}

/// Probe whether the endpoint restricts the number of field aliases per query.
///
/// Sends a single query containing 50 aliases for the same field and inspects
/// the response for alias limits, complexity limits, or successful execution.
///
/// # Returns
///
/// - [`AliasTestResult::Vulnerable`] when non-null `data` is returned without
///   alias-related errors, indicating no alias limit is enforced.
/// - [`AliasTestResult::Protected`] when the response mentions alias limits,
///   complexity limits, or returns errors referencing aliases.
/// - [`AliasTestResult::Error`] when the response is inconclusive.
pub async fn test_alias_abuse(client: &ScanClient, url: &str) -> Result<AliasTestResult> {
    // Create a query with many aliases for the same field
    let alias_count = 50;
    let query = generate_alias_abuse_query(alias_count);

    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 query was rejected
            if body_text.contains("alias") && body_text.contains("limit") {
                return Ok(AliasTestResult::Protected);
            }
            if body_text.contains("complexity") || body_text.contains("too complex") {
                return Ok(AliasTestResult::Protected);
            }

            // Check for 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("alias") || errors_str.contains("complexity") {
                        return Ok(AliasTestResult::Protected);
                    }
                }
            }

            // If we got non-null data back without errors, aliases were processed
            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(AliasTestResult::Vulnerable(alias_count));
            }

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

/// Build a [`Finding`] for a batching or alias-abuse vulnerability.
///
/// The finding is tagged with:
/// - **GQL-ID / scanner**: `gqlprobe`
/// - **Kind**: [`FindingKind::Vulnerability`]
/// - **Tags**: `graphql`, `batching`, `dos`
/// - **CWE**: `CWE-400` (Uncontrolled Resource Consumption)
///
/// Severity is chosen by the caller: [`Severity::Medium`] for unbounded
/// batching or alias abuse, and [`Severity::Low`] when a limit exists but is
/// considered too permissive.
///
/// # Arguments
///
/// * `url` - The target GraphQL endpoint URL.
/// * `title` - Short vulnerability title.
/// * `detail` - Human-readable explanation of the batching weakness.
/// * `severity` - Assessed severity level.
/// * `remediation` - Recommended mitigation.
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("batching")
        .tag("dos")
        .cwe("CWE-400") // Uncontrolled Resource Consumption
        .remediation(remediation)
        .build()?)
}