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};
pub const TEST_BATCH_SIZES: [usize; 5] = [5, 10, 25, 50, 100];
const MAX_ACCEPTABLE_BATCH_SIZE: usize = 25;
pub use crate::modules::alias_abuse::generate_alias_abuse_query_legacy as generate_alias_abuse_query;
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
}
pub async fn test_with_context(client: &ScanClient, ctx: &ScanContext) -> Result<Vec<Finding>> {
test(client, ctx.url()).await
}
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);
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 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)
}
#[derive(Debug)]
pub enum BatchTestResult {
AllProcessed(usize),
PartiallyProcessed(usize, usize),
Rejected(String),
Error(String),
}
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();
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(),
));
}
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));
}
return Ok(BatchTestResult::Rejected(
"All batch items returned errors".to_string(),
));
}
return Ok(BatchTestResult::PartiallyProcessed(
count,
batch.len() - count,
));
}
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()));
}
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())),
}
}
#[derive(Debug)]
pub enum AliasTestResult {
Vulnerable(usize),
Protected,
Error(String),
}
pub async fn test_alias_abuse(client: &ScanClient, url: &str) -> Result<AliasTestResult> {
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();
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);
}
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);
}
}
}
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())),
}
}
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") .remediation(remediation)
.build()?)
}