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 TYPO_TESTS: &[(&str, &str)] = &[
("nam", "Did you mean 'name'?"),
("id_", "Did you mean 'id'?"),
("emaill", "Did you mean 'email'?"),
("usser", "Did you mean 'user'?"),
("usres", "Did you mean 'users'?"),
("nme", "Did you mean 'name'?"),
("idd", "Did you mean 'id'?"),
("emai", "Did you mean 'email'?"),
("ussr", "Did you mean 'user'?"),
("dsecription", "Did you mean 'description'?"),
("tittle", "Did you mean 'title'?"),
("ccreatedAt", "Did you mean 'createdAt'?"),
];
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 suggestion_examples = Vec::new();
debug!("Testing field suggestion enumeration on {}", url);
for (typo, _expected_suggestion) in TYPO_TESTS {
match test_typo(client, url, typo).await? {
TypoTestResult::SuggestsFields(suggestions) => {
trace!("Typo '{}' triggered suggestions: {:?}", typo, suggestions);
suggestion_examples.push(((*typo).to_string(), suggestions));
}
TypoTestResult::NoSuggestion => {
trace!("Typo '{}' did not trigger suggestions", typo);
}
TypoTestResult::Error(e) => {
debug!("Typo test error for '{}': {}", typo, e);
}
}
}
if !suggestion_examples.is_empty() {
let examples_str = suggestion_examples
.iter()
.take(3)
.map(|(typo, suggestions)| {
format!(" - '{}' suggests: {}", typo, suggestions.join(", "))
})
.collect::<Vec<_>>()
.join("\n");
findings.push(create_finding(
url,
"GraphQL Field Suggestion Enumeration Enabled",
&format!(
"The GraphQL endpoint provides field suggestions in error messages, \
allowing attackers to enumerate the schema even when introspection is disabled.\
\n\nExamples found:\n{examples_str}"
),
Severity::Medium,
"Disable field suggestions in GraphQL error responses. \
Implement custom error formatting that strips 'Did you mean' suggestions.",
)?);
}
if let EnumTestResult::SuggestsValues(values) = test_enum_suggestion(client, url).await? {
findings.push(create_finding(
url,
"GraphQL Enum Value Suggestion Enumeration Enabled",
&format!(
"The GraphQL endpoint suggests valid enum values in error messages. \
This allows enumeration of enum types. Example values found: {}",
values.join(", ")
),
Severity::Low,
"Disable enum value suggestions in error responses.",
)?);
}
debug!(
"Field suggestion test complete: {} findings",
findings.len()
);
Ok(findings)
}
#[derive(Debug)]
pub enum TypoTestResult {
SuggestsFields(Vec<String>),
NoSuggestion,
Error(String),
}
pub async fn test_typo(client: &ScanClient, url: &str, typo: &str) -> Result<TypoTestResult> {
let queries = vec![
format!("query {{ user {{ {} }} }}", typo),
format!("query {{ {} }}", typo),
format!("query {{ user(id: 1) {{ {} }} }}", typo),
];
for query in queries {
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().to_lowercase();
let suggestion = extract_suggestions(&body_text);
if !suggestion.is_empty() {
return Ok(TypoTestResult::SuggestsFields(suggestion));
}
}
Err(e) => {
return Ok(TypoTestResult::Error(e.to_string()));
}
}
}
Ok(TypoTestResult::NoSuggestion)
}
pub fn extract_suggestions(error_text: &str) -> Vec<String> {
let mut suggestions = Vec::new();
let lower = error_text.to_lowercase();
if lower.contains("did you mean") {
if let Some(pos) = lower.find("did you mean") {
let after = &error_text[pos..];
for part in after.split('\'').skip(1).step_by(2) {
let trimmed = part.trim();
if !trimmed.is_empty() && trimmed.len() < 50 && trimmed != "s" {
suggestions.push(trimmed.to_string());
}
}
}
}
if lower.contains("suggestion") {
if let Some(start) = lower.find('[') {
if let Some(end) = lower[start..].find(']') {
let list = &lower[start + 1..start + end];
for item in list.split(',') {
let trimmed = item.trim().trim_matches('\'').trim_matches('"');
if !trimmed.is_empty() {
suggestions.push(trimmed.to_string());
}
}
}
}
}
suggestions
}
#[derive(Debug)]
pub enum EnumTestResult {
SuggestsValues(Vec<String>),
NoSuggestion,
Error(String),
}
pub async fn test_enum_suggestion(client: &ScanClient, url: &str) -> Result<EnumTestResult> {
let query = "query { users(filter: INVALID_ENUM_VALUE) { 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) => {
let body_text = resp.body_text().unwrap_or_default().to_lowercase();
if body_text.contains("did you mean") && body_text.contains("enum") {
let suggestions = extract_suggestions(&body_text);
if !suggestions.is_empty() {
return Ok(EnumTestResult::SuggestsValues(suggestions));
}
}
if body_text.contains("expected one of") || body_text.contains("valid values") {
if let Some(start) = body_text.find('[') {
if let Some(end) = body_text[start..].find(']') {
let list = &body_text[start + 1..start + end];
let values: Vec<String> = list
.split(',')
.map(|s: &str| {
s.trim().trim_matches('"').trim_matches('\'').to_string()
})
.filter(|s: &String| !s.is_empty())
.collect();
if !values.is_empty() {
return Ok(EnumTestResult::SuggestsValues(values));
}
}
}
}
Ok(EnumTestResult::NoSuggestion)
}
Err(e) => Ok(EnumTestResult::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::InfoDisclosure)
.tag("graphql")
.tag("enumeration")
.tag("introspection-bypass")
.cwe("CWE-200") .remediation(remediation)
.build()?)
}