use anyhow::Result;
use crate::context::ScanContext;
use scanclient::reqwest::header::CONTENT_TYPE;
use scanclient::ScanClient;
use secfinding::{Evidence, Finding, FindingKind, Severity};
use serde_json::json;
use tracing::debug;
pub const STACK_TRACE_INDICATORS: &[&str] = &[
"stack trace",
"stacktrace",
"traceback",
"exception:",
" at ",
" in ",
"line ",
"file \"",
".rs:",
".py:",
".js:",
];
pub const DEBUG_FIELDS: &[&str] = &["/debug", "/__debug", "/graphql/debug"];
pub const PLAYGROUND_PATHS: &[&str] = &[
"playground",
"graphiql",
"graphql playground",
"<title>graphql</title>",
"altair",
];
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 information disclosure on {}", url);
match test_verbose_errors(client, url).await? {
InfoDisclosureResult::Leaked(_detail, evidence) => {
findings.push(create_finding(
url,
"GraphQL Verbose Error Messages Leak Information",
"The GraphQL endpoint returns verbose error messages that may contain stack traces, \
implementation details, or internal paths.",
Severity::Medium,
"Configure error handling to return generic messages to clients. Log detailed errors server-side only.",
Some(&evidence),
)?);
}
InfoDisclosureResult::Safe => {}
InfoDisclosureResult::Error(e) => {
debug!("Verbose error test error: {}", e);
}
}
match test_debug_endpoint(client, url).await? {
InfoDisclosureResult::Leaked(detail, evidence) => {
findings.push(create_finding(
url,
"GraphQL Debug Endpoint/Field Exposed",
&format!(
"The GraphQL endpoint exposes debug functionality. {detail}"
),
Severity::High,
"Disable debug endpoints and fields in production. Require authentication for administrative functions.",
Some(&evidence),
)?);
}
InfoDisclosureResult::Safe => {}
InfoDisclosureResult::Error(e) => {
debug!("Debug endpoint test error: {}", e);
}
}
match test_playground_exposed(client, url).await? {
InfoDisclosureResult::Leaked(detail, evidence) => {
findings.push(create_finding(
url,
"GraphQL Playground/GraphiQL Exposed in Production",
&format!(
"The GraphQL endpoint exposes an interactive IDE (Playground/GraphiQL) in production. {detail}"
),
Severity::Low,
"Disable GraphQL Playground/GraphiQL in production, or restrict access to authorized users only.",
Some(&evidence),
)?);
}
InfoDisclosureResult::Safe => {}
InfoDisclosureResult::Error(e) => {
debug!("Playground test error: {}", e);
}
}
debug!(
"Information disclosure test complete: {} findings",
findings.len()
);
Ok(findings)
}
#[derive(Debug)]
pub enum InfoDisclosureResult {
Leaked(String, String),
Safe,
Error(String),
}
pub async fn test_verbose_errors(client: &ScanClient, url: &str) -> Result<InfoDisclosureResult> {
let body = json!({ "query": "query { nonexistent_field }" });
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("").to_lowercase();
if STACK_TRACE_INDICATORS
.iter()
.any(|ind| body_text.contains(ind))
|| (body_text.contains("file \"") && body_text.contains("line "))
{
return Ok(InfoDisclosureResult::Leaked(
"Verbose error response detected".to_string(),
body_text,
));
}
Ok(InfoDisclosureResult::Safe)
}
Err(e) => Ok(InfoDisclosureResult::Error(e.to_string())),
}
}
pub async fn test_debug_endpoint(client: &ScanClient, url: &str) -> Result<InfoDisclosureResult> {
for path in DEBUG_FIELDS {
let debug_url = if url.ends_with('/') {
format!("{}{}", url, path.trim_start_matches('/'))
} else {
format!("{url}{path}")
};
let request = client.request(scanclient::reqwest::Method::GET, &debug_url);
if let Ok(resp) = client.execute(request).await {
if resp.status().is_success() {
let body_text = resp.body_text().unwrap_or("").to_lowercase();
if body_text.contains("debug") || body_text.contains("schema") {
return Ok(InfoDisclosureResult::Leaked(
format!("Debug endpoint accessible at {debug_url}"),
body_text,
));
}
}
}
}
Ok(InfoDisclosureResult::Safe)
}
pub async fn test_playground_exposed(
client: &ScanClient,
url: &str,
) -> Result<InfoDisclosureResult> {
let paths = ["", "/altair", "/playground", "/graphql/playground"];
for path in &paths {
let target = if url.ends_with('/') {
format!("{}{}", url, path.trim_start_matches('/'))
} else {
format!("{url}{path}")
};
let request = client.request(scanclient::reqwest::Method::GET, &target);
if let Ok(resp) = client.execute(request).await {
let body_text = resp.body_text().unwrap_or("").to_lowercase();
if PLAYGROUND_PATHS.iter().any(|ind| body_text.contains(ind)) {
return Ok(InfoDisclosureResult::Leaked(
"GraphQL IDE detected".to_string(),
body_text,
));
}
}
}
Ok(InfoDisclosureResult::Safe)
}
pub fn create_finding(
url: &str,
title: &str,
detail: &str,
severity: Severity,
remediation: &str,
evidence_body: Option<&str>,
) -> Result<Finding> {
let mut builder = Finding::builder("gqlprobe", url, severity)
.title(title)
.detail(detail)
.kind(FindingKind::InfoDisclosure)
.tag("graphql")
.tag("information-disclosure")
.cwe("CWE-200") .remediation(remediation);
if let Some(body) = evidence_body {
let excerpt = if body.len() > 1000 {
format!("{}...[truncated]", &body[..1000])
} else {
body.to_string()
};
builder = builder.evidence(Evidence::raw(excerpt));
}
Ok(builder.build()?)
}