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};
pub const DIRECTIVE_REPETITIONS: [usize; 4] = [10, 50, 100, 200];
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();
debug!("Testing directive abuse on {}", url);
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);
}
}
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.",
)?);
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
};
let _ = excerpt;
}
}
DeprecatedTestResult::Disabled => {
trace!("Deprecated field introspection disabled");
}
DeprecatedTestResult::Error(e) => {
debug!("Deprecated introspection test error: {}", e);
}
}
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)
}
#[derive(Debug)]
pub enum DirectiveRepetitionResult {
Vulnerable(usize),
Limited(usize),
Error(String),
}
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();
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;
}
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;
}
}
}
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(),
))
}
}
#[derive(Debug)]
pub enum DeprecatedTestResult {
Enabled(String),
Disabled,
Error(String),
}
pub async fn test_deprecated_introspection(
client: &ScanClient,
url: &str,
) -> Result<DeprecatedTestResult> {
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();
if body_text.contains("isDeprecated") || body_text.contains("deprecationReason") {
if let Ok(json) = serde_json::from_str::<serde_json::Value>(body_text) {
if json.get("data").is_some()
&& (body_text.contains("isDeprecated")
|| body_text.contains("deprecationReason"))
{
return Ok(DeprecatedTestResult::Enabled(body_text.to_string()));
}
}
}
if body_text.contains("introspection") && body_text.contains("disabled") {
return Ok(DeprecatedTestResult::Disabled);
}
Ok(DeprecatedTestResult::Disabled)
}
Err(e) => Ok(DeprecatedTestResult::Error(e.to_string())),
}
}
#[derive(Debug)]
pub enum MultipleDirectiveResult {
Vulnerable(usize),
Limited,
Error(String),
}
pub async fn test_multiple_directives(
client: &ScanClient,
url: &str,
) -> Result<MultipleDirectiveResult> {
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 !body_text.contains("errors") {
return Ok(MultipleDirectiveResult::Vulnerable(4));
}
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())),
}
}
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") .remediation(remediation)
.build()?)
}