gqlprobe 1.0.0

Fast GraphQL security scanner - schema-aware introspection, injection, DoS, CSRF, auth bypass, SARIF
Documentation
//! Field suggestion enumeration detection module.
//!
//! Detects if the GraphQL endpoint provides field suggestions in error
//! messages, which can be used to enumerate the schema even when
//! introspection is disabled.
//!
//! # Attack Description
//!
//! When a GraphQL query contains an unknown field, some implementations
//! suggest valid fields in the error message:
//! ```text
//! "Cannot query field 'nam' on type 'User'. Did you mean 'name'?"
//! ```
//!
//! Attackers can systematically send malformed queries to discover:
//! - All field names on a type
//! - All enum values
//! - Argument names
//!
//! This effectively bypasses disabled introspection.
//!
//! # Detection Method
//!
//! 1. Send queries with intentionally misspelled field names
//! 2. Check if error messages suggest valid alternatives
//! 3. Report if suggestions leak schema information
//!
//! # Remediation
//!
//! Disable field suggestions:
//! - graphql-ruby: Disable `DidYouMean` in error handling
//! - apollo-server: Custom formatError that strips suggestions
//! - Custom validation rules to disable suggestions

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

/// Common typos to test for field suggestions.
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'?"),
];

/// Test for field suggestion enumeration vulnerability.
///
/// Sends queries with intentional typos and checks if the server
/// suggests valid field names in error messages.
///
/// # Arguments
///
/// * `client` - The HTTP client for making requests
/// * `url` - The target GraphQL endpoint URL
///
/// # Returns
///
/// Returns findings if the server leaks field information via suggestions.
///
/// # 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 field suggestion checks using shared scan context.
/// Test for field suggestion enumeration vulnerability.
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);

    // Test each typo pattern
    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 we found suggestions, report the vulnerability
    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.",
        )?);
    }

    // Test for enum value suggestion
    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)
}

/// Outcome of a single typo-based field-suggestion probe.
///
/// When a GraphQL server receives a query with a misspelled field
/// name, some implementations return an error that lists valid
/// alternatives.  This enum captures whether the server leaked those
/// alternatives.
#[derive(Debug)]
pub enum TypoTestResult {
    /// The error response contained a "Did you mean" or similar
    /// suggestion block, and the listed valid field names were
    /// extracted.
    SuggestsFields(Vec<String>),
    /// None of the query variants for this typo triggered a field
    /// suggestion in the error response.
    NoSuggestion,
    /// A network or unexpected server error prevented a clear
    /// determination.
    Error(String),
}

/// Probe the endpoint with an intentionally misspelled field name.
///
/// Sends the typo in three query contexts (nested under `user`, at
/// root level, and inside a field with an argument) to maximise the
/// chance of hitting a code path that produces suggestions.
///
/// # When it returns each variant
///
/// - `SuggestsFields` - at least one query variant produced an error
///   containing valid field names that were extracted by
///   [`extract_suggestions`].
/// - `NoSuggestion`   - all variants returned errors without
///   suggestions or returned data successfully.
/// - `Error`          - an HTTP request failed before a suggestion
///   determination could be made.
pub async fn test_typo(client: &ScanClient, url: &str, typo: &str) -> Result<TypoTestResult> {
    // Try the typo in different query contexts
    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();

                // Check for suggestion patterns
                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)
}

/// Extract candidate field or enum names from a GraphQL error
/// response body.
///
/// This function implements the pattern-matching engine that turns
/// raw error text into a list of leaked schema identifiers.  Two
/// common GraphQL server behaviours are handled:
///
/// 1. **"Did you mean 'field'?"** - the function searches for the
///    `did you mean` substring, then collects single-quoted tokens
///    that follow it.  This is the default pattern used by
///    graphql-ruby and several other engines.
/// 2. **"suggestions: [field1, field2]"** - the function looks for a
///    bracketed list after the word `suggestion` and splits the
///    comma-separated contents, stripping surrounding quotes.
///
/// Each extracted token is filtered for length (< 50 chars) and
/// emptiness to avoid garbage matches.
///
/// This extraction is the core primitive that enables **field
/// enumeration**: by systematically submitting typos and harvesting
/// the suggestions returned here, an attacker can reconstruct the
/// complete set of fields on a type without ever calling the
/// introspection endpoint.
pub fn extract_suggestions(error_text: &str) -> Vec<String> {
    let mut suggestions = Vec::new();
    let lower = error_text.to_lowercase();

    // Pattern: "did you mean 'fieldname'?"
    if lower.contains("did you mean") {
        // Find position in original text (safe for ASCII; GraphQL errors are ASCII)
        if let Some(pos) = lower.find("did you mean") {
            let after = &error_text[pos..];
            // Look for single-quoted content
            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());
                }
            }
        }
    }

    // Pattern: "suggestions: [field1, field2]"
    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
}

/// Outcome of the enum-value suggestion probe.
///
/// Similar to field suggestions, some GraphQL servers leak valid enum
/// values when an invalid value is supplied, allowing full
/// enumeration of enum types even when introspection is disabled.
#[derive(Debug)]
pub enum EnumTestResult {
    /// The server returned an error that listed valid enum values,
    /// enabling schema enumeration.
    SuggestsValues(Vec<String>),
    /// The server rejected the invalid enum value without leaking
    /// valid alternatives.
    NoSuggestion,
    /// A network or unexpected server error prevented a clear
    /// determination.
    Error(String),
}

/// Probe the endpoint for enum-value suggestion leakage.
///
/// Sends a query that passes a non-existent enum value
/// (`INVALID_ENUM_VALUE`) to a filter argument.  If the server
/// responds with "did you mean" or "expected one of" patterns, the
/// valid values are extracted and reported.
///
/// # When it returns each variant
///
/// - `SuggestsValues` - the response contained a list of valid enum
///   values, proving the endpoint leaks enum metadata.
/// - `NoSuggestion`   - the server rejected the value without
///   revealing alternatives.
/// - `Error`          - the HTTP request failed.
pub async fn test_enum_suggestion(client: &ScanClient, url: &str) -> Result<EnumTestResult> {
    // Try an invalid enum value
    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();

            // Check for enum value suggestions
            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));
                }
            }

            // Check for "expected one of" pattern
            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())),
    }
}

/// Build a [`Finding`] for a field-suggestion information-disclosure
/// vulnerability.
///
/// Assigns:
/// - **Scanner ID** (`gqlprobe`) and the target `url`.
/// - **Severity** - caller-supplied (`Medium` for field suggestions,
///   `Low` for enum-value suggestions).
/// - **Kind** - [`FindingKind::InfoDisclosure`], because the issue is
///   information leakage rather than a crash or code-execution flaw.
/// - **Tags** - `graphql`, `enumeration`, `introspection-bypass`.
/// - **CWE** - `CWE-200` (Information Exposure), because suggestions
///   expose internal schema details to unauthenticated clients.
///
/// The caller provides the human-readable `title`, `detail`, and
/// `remediation` strings.
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") // Information Exposure
        .remediation(remediation)
        .build()?)
}