gqlprobe 1.0.0

Fast GraphQL security scanner - schema-aware introspection, injection, DoS, CSRF, auth bypass, SARIF
Documentation
//! Introspection detection module.
//!
//! Detects if GraphQL introspection is enabled by sending standard
//! introspection queries. Introspection allows clients to query the
//! schema structure, which can expose sensitive type information.
//!
//! # Attack Description
//!
//! GraphQL introspection is a feature that allows querying the schema
//! itself. When enabled in production, attackers can discover all
//! types, fields, queries, mutations, and subscriptions without
//! authentication.
//!
//! # Detection Method
//!
//! 1. Send standard introspection query for `__schema`
//! 2. Send `__type` query for sensitive types (User, Admin, etc.)
//! 3. Check if responses contain schema information
//!
//! # Remediation
//!
//! Disable introspection in production using:
//! - graphql-ruby: `introspection false`
//! - apollo-server: `introspection: false`
//! - graphene: middleware to block `__schema` and `__type`

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};

/// Standard GraphQL introspection query for full schema.
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
          }
        }
      }
    }
  }
}
";

/// Simplified introspection probe.
pub const SIMPLE_INTROSPECTION_QUERY: &str = r"
{
  __schema {
    queryType {
      name
    }
  }
}
";

/// Type name introspection query.
pub const TYPE_QUERY: &str = r"
query TypeQuery($name: String!) {
  __type(name: $name) {
    name
    kind
    fields {
      name
      type {
        name
      }
    }
  }
}
";

/// Test if GraphQL introspection is enabled.
///
/// Sends multiple introspection probes and returns findings if
/// any of them succeed.
///
/// # Arguments
///
/// * `client` - The HTTP client for making requests
/// * `url` - The target GraphQL endpoint URL
///
/// # Returns
///
/// Returns a vector of findings. Empty if introspection is disabled.
///
/// # Errors
///
/// Returns an error if HTTP requests fail critically.
///
/// # Example
///
/// ```rust,no_run
/// use gqlprobe::modules::introspection;
/// use scanclient::ScanClient;
///
/// # async fn example() -> anyhow::Result<()> {
/// let resolver = std::sync::Arc::new(hickory_resolver::TokioResolver::builder_tokio()?.build());
/// let client = ScanClient::new(Default::default(), resolver)?;
/// let findings = introspection::test(&client, "https://api.example.com/graphql").await?;
/// # Ok(())
/// # }
/// ```
/// Run introspection checks using shared scan context.
pub async fn test_with_context(client: &ScanClient, ctx: &ScanContext) -> Result<Vec<Finding>> {
    test(client, ctx.url()).await
}

/// Test if GraphQL introspection is enabled.
pub async fn test(client: &ScanClient, url: &str) -> Result<Vec<Finding>> {
    let mut findings = Vec::new();

    debug!("Testing introspection on {}", url);

    // Test 1: Simple introspection query
    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);
        }
    }

    // Test 2: Full introspection query (only if simple didn't trigger)
    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(_) => {}
        }
    }

    // Test 3: Type introspection (check for sensitive types)
    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?
        {
            // Verify the response actually contains type data, not just the type name in an error
            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; // Found one, no need to continue
                    }
                }
            }
        }
    }

    debug!("Introspection test complete: {} findings", findings.len());
    Ok(findings)
}

/// Result of a single introspection probe.
///
/// Represents whether the GraphQL server accepted, rejected, or failed
/// to process an introspection query. This enum drives the decision of
/// whether to emit a security finding.
#[derive(Debug)]
pub enum IntrospectionResult {
    /// The server returned schema or type data, confirming introspection is enabled.
    ///
    /// Triggered when the HTTP response is successful and the JSON body
    /// contains `/data/__schema` or `/data/__type`. The wrapped string
    /// holds the full response text for use as evidence.
    Enabled(String),
    /// The server blocked the introspection query.
    ///
    /// Returned when the HTTP status is non-success, or the JSON body
    /// contains GraphQL errors with keywords such as `introspection`,
    /// `forbidden`, `unauthorized`, `denied`, `disabled`, or `not allowed`.
    Disabled,
    /// The probe encountered a network or transport error.
    ///
    /// Preserves the error message so the scanner can log the failure
    /// without terminating the entire introspection test suite.
    Error(String),
}

/// Transmit an introspection query and classify the server's response.
///
/// Sends the query as a JSON POST request to the target URL. On success,
/// the response body is parsed to distinguish between actual schema data
/// (indicating introspection is enabled) and authorization errors
/// (indicating it is disabled). This function is the single chokepoint
/// for all introspection probes, ensuring consistent detection logic.
///
/// # Arguments
///
/// * `client` - The HTTP client used to issue requests.
/// * `url` - The target GraphQL endpoint.
/// * `query` - The introspection query string (e.g., [`INTROSPECTION_QUERY`]).
/// * `variables` - Optional JSON variables for parameterized queries such
///   as [`TYPE_QUERY`].
///
/// # Returns
///
/// - `Enabled` when the response contains introspection data under
///   `data.__schema` or `data.__type`.
/// - `Disabled` when the server returns an error status or GraphQL errors
///   indicating introspection is blocked.
/// - `Error` when the HTTP request itself fails.
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);
            }

            // Parse response as JSON to distinguish actual introspection data from errors
            let parsed = serde_json::from_str::<serde_json::Value>(&body_text);

            if let Ok(ref json) = parsed {
                // Check for actual introspection data at data.__schema or data.__type
                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));
                }

                // Check for errors that indicate introspection is disabled
                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())),
    }
}

/// Build a standardized `Finding` for an introspection misconfiguration.
///
/// Assigns the GQL-ID `gqlprobe`, tags the finding with `graphql`
/// and `introspection`, and maps it to CWE-200 (Information Exposure).
/// Introspection findings are always raised as [`FindingKind::Misconfiguration`]
/// because they represent a deliberate but dangerous server setting rather
/// than an implementation bug. Severity varies by probe depth:
/// - `High` for full schema introspection (complete attack-surface exposure).
/// - `Medium` for individual type introspection (partial but sensitive leakage).
///
/// Evidence bodies longer than 1000 characters are truncated to keep
/// reports concise while retaining proof of exposure.
///
/// # Arguments
///
/// * `url` - The target endpoint where introspection was observed.
/// * `title` - Short human-readable title for the report.
/// * `detail` - Description of the schema leakage risk.
/// * `severity` - Impact level based on the breadth of exposed schema data.
/// * `remediation` - Recommended configuration change.
/// * `evidence_body` - Optional raw JSON response proving introspection is active.
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") // Information Exposure
        .remediation(remediation);

    if let Some(body) = evidence_body {
        // Truncate evidence to reasonable size
        let excerpt = if body.len() > 1000 {
            format!("{}...[truncated]", &body[..1000])
        } else {
            body.to_string()
        };
        builder = builder.evidence(Evidence::raw(excerpt));
    }

    Ok(builder.build()?)
}