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};
const TEST_DEPTHS: [usize; 6] = [5, 10, 20, 50, 100, 200];
const MAX_ACCEPTABLE_DEPTH: usize = 20;
pub fn generate_deep_query(depth: usize) -> String {
generate_deep_query_for_field(depth, "user", "friends")
}
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
}
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('}'); query
}
pub async fn test_with_context(client: &ScanClient, ctx: &ScanContext) -> Result<Vec<Finding>> {
test_inner(client, ctx.url(), ctx.schema.as_ref()).await
}
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
);
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 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.",
)?);
}
}
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)
}
#[derive(Debug)]
pub enum DepthTestResult {
Accepted(u64),
Rejected(String),
Error(String),
}
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();
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()));
}
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())),
}
}
#[derive(Debug)]
pub enum FragmentTestResult {
CircularAccepted,
CircularRejected,
Error(String),
}
pub async fn test_circular_fragments(client: &ScanClient, url: &str) -> Result<FragmentTestResult> {
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();
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);
}
}
}
}
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())),
}
}
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") .remediation(remediation)
.build()?)
}