use anyhow::Result;
use scanclient::reqwest::header::CONTENT_TYPE;
use scanclient::ScanClient;
use crate::context::ScanContext;
use secfinding::{Evidence, Finding, FindingKind, Severity};
use serde_json::json;
use tracing::{debug, trace};
pub const INTROSPECTION_QUERY: &str = r"
query IntrospectionQuery {
__schema {
queryType { name }
mutationType { name }
subscriptionType { name }
types {
name
kind
description
fields {
name
description
args {
name
description
type {
name
kind
ofType {
name
kind
}
}
}
type {
name
kind
ofType {
name
kind
}
}
}
}
}
}
";
pub const SIMPLE_INTROSPECTION_QUERY: &str = r"
{
__schema {
queryType {
name
}
}
}
";
pub const TYPE_QUERY: &str = r"
query TypeQuery($name: String!) {
__type(name: $name) {
name
kind
fields {
name
type {
name
}
}
}
}
";
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 introspection on {}", url);
match send_introspection_query(client, url, SIMPLE_INTROSPECTION_QUERY, None).await? {
IntrospectionResult::Enabled(response_body) => {
trace!("Introspection enabled - simple query succeeded");
findings.push(create_finding(
url,
"GraphQL Introspection Enabled",
"The GraphQL endpoint has introspection enabled, exposing the complete schema structure.",
Severity::High,
"Disable introspection in production configuration",
Some(&response_body),
)?);
}
IntrospectionResult::Disabled => {
trace!("Simple introspection query blocked");
}
IntrospectionResult::Error(e) => {
debug!("Introspection test error: {}", e);
}
}
if findings.is_empty() {
match send_introspection_query(client, url, INTROSPECTION_QUERY, None).await? {
IntrospectionResult::Enabled(response_body) => {
trace!("Introspection enabled - full query succeeded");
findings.push(create_finding(
url,
"GraphQL Introspection Enabled - Full Schema",
"The GraphQL endpoint exposes the complete schema via full introspection queries.",
Severity::High,
"Disable introspection in production configuration",
Some(&response_body),
)?);
}
IntrospectionResult::Disabled | IntrospectionResult::Error(_) => {}
}
}
let sensitive_types = ["User", "Admin", "Account", "Password", "Secret", "Token"];
for type_name in &sensitive_types {
let variables = json!({ "name": type_name });
if let IntrospectionResult::Enabled(response_body) =
send_introspection_query(client, url, TYPE_QUERY, Some(variables)).await?
{
if let Ok(ref json) = serde_json::from_str::<serde_json::Value>(&response_body) {
if let Some(type_data) = json.pointer("/data/__type") {
if type_data.get("name").is_some() {
trace!("Type introspection enabled for type: {}", type_name);
findings.push(create_finding(
url,
&format!("GraphQL Type Introspection Enabled - {type_name}"),
&format!(
"The GraphQL endpoint exposes type information for sensitive type '{type_name}'."
),
Severity::Medium,
"Disable introspection or implement field-level authorization",
Some(&response_body),
)?);
break; }
}
}
}
}
debug!("Introspection test complete: {} findings", findings.len());
Ok(findings)
}
#[derive(Debug)]
pub enum IntrospectionResult {
Enabled(String),
Disabled,
Error(String),
}
pub async fn send_introspection_query(
client: &ScanClient,
url: &str,
query: &str,
variables: Option<serde_json::Value>,
) -> Result<IntrospectionResult> {
let body = if let Some(vars) = variables {
json!({
"query": query,
"variables": vars,
})
} else {
json!({
"query": query,
})
};
let request = client
.request(scanclient::reqwest::Method::POST, url)
.header(CONTENT_TYPE, "application/json")
.body(body.to_string());
let response = client.execute(request).await;
match response {
Ok(resp) => {
let status = resp.status();
let body_text = resp.body_text().unwrap_or_default().to_string();
if !status.is_success() {
return Ok(IntrospectionResult::Disabled);
}
let parsed = serde_json::from_str::<serde_json::Value>(&body_text);
if let Ok(ref json) = parsed {
let has_schema_data = json.pointer("/data/__schema").is_some();
let has_type_data = json.pointer("/data/__type").is_some();
if has_schema_data || has_type_data {
return Ok(IntrospectionResult::Enabled(body_text));
}
if let Some(errors) = json.get("errors").and_then(|e| e.as_array()) {
let errors_str = serde_json::to_string(errors)
.unwrap_or_default()
.to_lowercase();
if errors_str.contains("introspection")
|| errors_str.contains("forbidden")
|| errors_str.contains("unauthorized")
|| errors_str.contains("denied")
|| errors_str.contains("disabled")
|| errors_str.contains("not allowed")
{
return Ok(IntrospectionResult::Disabled);
}
}
}
Ok(IntrospectionResult::Disabled)
}
Err(e) => Ok(IntrospectionResult::Error(e.to_string())),
}
}
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::Misconfiguration)
.tag("graphql")
.tag("introspection")
.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()?)
}