gqlprobe 1.0.0

Fast GraphQL security scanner - schema-aware introspection, injection, DoS, CSRF, auth bypass, SARIF
Documentation
//! Information disclosure detection module (GQL-009).
//!
//! Detects information leakage through verbose error messages,
//! exposed debug endpoints, and GraphQL playgrounds in production.

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;

/// Indicators of stack traces or verbose errors in responses.
pub const STACK_TRACE_INDICATORS: &[&str] = &[
    "stack trace",
    "stacktrace",
    "traceback",
    "exception:",
    " at ",
    " in ",
    "line ",
    "file \"",
    ".rs:",
    ".py:",
    ".js:",
];

/// Debug endpoint paths to probe.
pub const DEBUG_FIELDS: &[&str] = &["/debug", "/__debug", "/graphql/debug"];

/// Playground/GraphiQL exposure indicators in response bodies.
pub const PLAYGROUND_PATHS: &[&str] = &[
    "playground",
    "graphiql",
    "graphql playground",
    "<title>graphql</title>",
    "altair",
];

/// Test for information disclosure vulnerabilities.
///
/// Checks for verbose error messages, debug endpoints, and
/// GraphQL playgrounds exposed in production.
///
/// # Arguments
///
/// * `client` - The HTTP client for making requests
/// * `url` - The target GraphQL endpoint URL
///
/// # Returns
///
/// Returns findings if information disclosure is detected.
///
/// # Errors
///
/// Returns an error if HTTP requests fail critically.
pub async fn test_with_context(client: &ScanClient, ctx: &ScanContext) -> Result<Vec<Finding>> {
    test(client, ctx.url()).await
}

/// Run information disclosure checks using shared scan context.
/// Test for information disclosure vulnerabilities.
pub async fn test(client: &ScanClient, url: &str) -> Result<Vec<Finding>> {
    let mut findings = Vec::new();

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

    // Test 1: Verbose error messages
    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);
        }
    }

    // Test 2: Debug endpoint exposure
    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);
        }
    }

    // Test 3: GraphQL playground/GraphiQL exposure
    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)
}

/// Result of an information-disclosure probe.
///
/// Each variant represents a distinct outcome from testing a single
/// disclosure vector (verbose errors, debug endpoints, or playgrounds).
#[derive(Debug)]
pub enum InfoDisclosureResult {
    /// The endpoint leaked sensitive information.
    ///
    /// Triggered when the response body contains stack-trace keywords,
    /// debug metadata, or playground markup. The first element is a
    /// human-readable summary of what was found; the second is the raw
    /// response text used as evidence.
    Leaked(String, String),
    /// The endpoint did not disclose any recognizable sensitive data.
    ///
    /// Returned when the probe completed successfully but none of the
    /// indicator patterns matched the response.
    Safe,
    /// The probe failed due to a network or parsing error.
    ///
    /// This variant preserves the error message so the caller can log
    /// it without aborting the entire scan.
    Error(String),
}

/// Probe the endpoint for verbose error messages and stack traces.
///
/// Sends a malformed GraphQL query (`{ nonexistent_field }`) and
/// inspects the response for language-specific stack-trace markers
/// (e.g., `.rs:`, `traceback`, `exception:`). Verbose errors reveal
/// implementation details, file paths, and internal line numbers that
/// help attackers map the attack surface and choose exploit payloads.
///
/// # Returns
///
/// - `Leaked` when stack-trace indicators appear in the error body.
/// - `Safe` when the error is generic or no error is returned.
/// - `Error` when the HTTP request itself fails.
pub async fn test_verbose_errors(client: &ScanClient, url: &str) -> Result<InfoDisclosureResult> {
    // Send an intentionally malformed query
    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())),
    }
}

/// Probe for exposed debug endpoints adjacent to the GraphQL URL.
///
/// Iterates over [`DEBUG_FIELDS`] (e.g., `/debug`, `/__debug`,
/// `/graphql/debug`) and checks whether any respond with HTTP 200
/// and contain `debug` or `schema` in the body. Debug endpoints
/// often expose internal state, raw schemas, or administrative
/// controls without authentication.
///
/// # Returns
///
/// - `Leaked` with the accessible URL when a debug endpoint is reachable.
/// - `Safe` when none of the probed paths returned a qualifying response.
/// - `Error` when an individual request fails (individual failures are
///   treated as `Safe` because the loop suppresses per-path errors).
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)
}

/// Probe for GraphQL IDE interfaces exposed in production.
///
/// Sends GET requests to common playground paths (`/`, `/altair`,
/// `/playground`, `/graphql/playground`) and checks the response
/// body against [`PLAYGROUND_PATHS`] for strings such as
/// `playground`, `graphiql`, or `altair`. An exposed IDE allows
/// unauthenticated attackers to interactively explore the schema,
/// craft malicious queries, and validate payloads before launching
/// an attack.
///
/// # Returns
///
/// - `Leaked` when a playground or IDE is detected in the response body.
/// - `Safe` when none of the probed paths contain playground indicators.
/// - `Error` when an individual request fails (suppressed per-path).
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)
}

/// Build a standardized `Finding` for an information-disclosure issue.
///
/// Assigns the GQL-ID `gqlprobe`, tags the finding with
/// `graphql` and `information-disclosure`, and maps it to CWE-200
/// (Information Exposure). The severity is dictated by the caller
/// based on the specific disclosure vector:
/// - `High` for debug endpoints (administrative access risk).
/// - `Medium` for verbose error messages (attack-surface mapping).
/// - `Low` for exposed playgrounds (IDE availability).
///
/// Evidence bodies longer than 1000 characters are truncated to
/// keep reports readable while preserving proof of disclosure.
///
/// # Arguments
///
/// * `url` - The target endpoint where disclosure was observed.
/// * `title` - Short human-readable title for the report.
/// * `detail` - Description of what was leaked and why it matters.
/// * `severity` - Impact level assigned by the caller.
/// * `remediation` - Recommended fix for the operator.
/// * `evidence_body` - Optional raw response excerpt proving the leak.
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") // Information Exposure
        .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()?)
}