gqlprobe 1.0.0

Fast GraphQL security scanner - schema-aware introspection, injection, DoS, CSRF, auth bypass, SARIF
Documentation
//! Subscription abuse detection module (GQL-008).
//!
//! Detects unbounded GraphQL subscriptions that can be used for
//! denial of service or data exfiltration.

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;

/// Number of rapid subscription requests to send when testing rate limits.
pub const SUBSCRIPTION_BURST_COUNT: usize = 5;

/// Test for subscription abuse vulnerabilities.
///
/// Checks if subscriptions are enabled without proper rate limiting
/// or authentication.
///
/// # Arguments
///
/// * `client` - The HTTP client for making requests
/// * `url` - The target GraphQL endpoint URL
///
/// # Returns
///
/// Returns findings if subscription abuse is possible.
///
/// # 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 subscription abuse checks using shared scan context.
/// Test for subscription abuse vulnerabilities.
pub async fn test(client: &ScanClient, url: &str) -> Result<Vec<Finding>> {
    let mut findings = Vec::new();

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

    // Test 1: Check if subscriptions are accepted over HTTP
    match test_subscription_over_http(client, url).await? {
        SubscriptionResult::Vulnerable(_detail) => {
            findings.push(create_finding(
                url,
                "GraphQL Subscriptions Enabled",
                "The GraphQL endpoint has subscriptions enabled. Subscriptions can be abused \
                 for denial of service through resource exhaustion or for unauthorized data streaming.",
                Severity::Medium,
                "Ensure subscriptions require authentication and implement rate limiting.",
            )?);
        }
        SubscriptionResult::Limited(_) => {}
        SubscriptionResult::Safe => {
            debug!("Subscriptions not enabled or properly restricted");
        }
        SubscriptionResult::Error(e) => {
            debug!("Subscription over HTTP test error: {}", e);
        }
    }

    // Test 2: Check for subscription rate limiting
    match test_subscription_rate_limit(client, url).await? {
        SubscriptionResult::Vulnerable(detail) => {
            findings.push(create_finding(
                url,
                "GraphQL Subscription Rate Limit Missing",
                &format!(
                    "The GraphQL endpoint accepts multiple subscription requests without rate limiting. {detail}"
                ),
                Severity::High,
                "Implement rate limiting on subscription creation. Limit concurrent subscriptions per client.",
            )?);
        }
        SubscriptionResult::Limited(detail) => {
            findings.push(create_finding(
                url,
                "GraphQL Subscription Rate Limit Insufficient",
                &format!(
                    "The GraphQL endpoint accepted some subscription requests before rate limiting kicked in. {detail}"
                ),
                Severity::Medium,
                "Implement stricter rate limiting on subscription creation. Limit concurrent subscriptions per client.",
            )?);
        }
        SubscriptionResult::Safe => {}
        SubscriptionResult::Error(e) => {
            debug!("Subscription rate limit test error: {}", e);
        }
    }

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

/// Outcome of a single subscription-abuse probe.
///
/// Distinguishes between a server that freely accepts subscriptions, one that
/// imposes partial or weak restrictions, one that properly blocks them, and
/// transport failures that prevent a clear verdict.
#[derive(Debug)]
pub enum SubscriptionResult {
    /// The server accepted the subscription operation without adequate
    /// safeguards. The `String` describes the exact weakness observed, such as
    /// "Subscription accepted over HTTP" or "Multiple subscriptions accepted
    /// without rate limiting". This variant is the signal to emit a security
    /// finding.
    Vulnerable(String),
    /// The server imposed some restriction, but it was insufficient or only
    /// partial. For example, a burst of rapid subscription requests was
    /// partially accepted before rate limiting kicked in. The payload contains
    /// details of how many requests slipped through, which determines whether
    /// the finding severity should be Medium rather than High.
    Limited(String),
    /// The server properly rejected the subscription operation, returned an
    /// unsupported error, or required a protocol upgrade (HTTP 426). No
    /// vulnerability is present for this probe.
    Safe,
    /// A transport or parsing error prevented a clear verdict. These are
    /// logged for debugging but do not produce findings.
    Error(String),
}

/// Probe whether the GraphQL endpoint accepts subscription operations over plain HTTP.
///
/// Subscriptions should normally run over `WebSockets` or dedicated streaming
/// transports. Accepting them over HTTP indicates the endpoint may lack
/// authentication, authorization, or rate-limiting controls that are easier
/// to enforce on persistent connections, exposing a denial-of-service or
/// data-exfiltration vector.
///
/// Sends a minimal `subscription { __typename }` query via HTTP POST.
///
/// # Returns
///
/// * `SubscriptionResult::Vulnerable` when the server returns HTTP 2xx with
///   no errors, confirming subscriptions are enabled over HTTP.
/// * `SubscriptionResult::Safe` when the response indicates subscriptions are
///   unsupported, the server returns HTTP 426 Upgrade Required, or any other
///   clear rejection.
/// * `SubscriptionResult::Error` on network failure.
pub async fn test_subscription_over_http(
    client: &ScanClient,
    url: &str,
) -> Result<SubscriptionResult> {
    let query = r"
        subscription TestSubscription {
            __typename
        }
    ";
    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("").to_lowercase();

            if resp.status().is_success() && !body_text.contains("error") {
                return Ok(SubscriptionResult::Vulnerable(
                    "Subscription accepted over HTTP".to_string(),
                ));
            }

            if body_text.contains("subscription")
                && (body_text.contains("not supported") || body_text.contains("unsupported"))
            {
                return Ok(SubscriptionResult::Safe);
            }

            if resp.status().as_u16() == 426 {
                // HTTP 426 means the server correctly rejects HTTP subscriptions
                // and requires WebSocket upgrade - this is the secure behavior.
                return Ok(SubscriptionResult::Safe);
            }

            Ok(SubscriptionResult::Safe)
        }
        Err(e) => Ok(SubscriptionResult::Error(e.to_string())),
    }
}

/// Test whether the server enforces rate limits on subscription creation.
///
/// Sends a rapid burst of identical subscription requests to see if the
/// endpoint allows unbounded subscription channel creation. An attacker who
/// can open an arbitrary number of subscriptions can exhaust server memory,
/// CPU, or downstream database connections.
///
/// Uses `SUBSCRIPTION_BURST_COUNT` consecutive HTTP POST requests with
/// `subscription { __typename }`.
///
/// # Returns
///
/// * `SubscriptionResult::Vulnerable` when every request in the burst is
///   accepted, meaning an attacker can open an arbitrary number of
///   subscription channels and exhaust server resources.
/// * `SubscriptionResult::Limited` when some but not all requests are
///   accepted, indicating a weak or late-acting rate limit.
/// * `SubscriptionResult::Safe` when all requests are rejected immediately.
/// * `SubscriptionResult::Error` if the connection fails before the burst
///   completes.
pub async fn test_subscription_rate_limit(
    client: &ScanClient,
    url: &str,
) -> Result<SubscriptionResult> {
    // Attempt to create multiple subscriptions rapidly
    let query = r"
        subscription RateLimitTest {
            __typename
        }
    ";

    let mut accepted = 0;
    for _ in 0..SUBSCRIPTION_BURST_COUNT {
        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) => {
                if resp.status().is_success() {
                    let body_text = resp.body_text().unwrap_or_default().to_lowercase();
                    let is_rejected = body_text.contains("error")
                        || body_text.contains("limit")
                        || body_text.contains("throttled")
                        || body_text.contains("unsupported");
                    if !is_rejected {
                        accepted += 1;
                    }
                }
            }
            Err(_) => break,
        }
    }

    if accepted >= SUBSCRIPTION_BURST_COUNT {
        Ok(SubscriptionResult::Vulnerable(
            "Multiple subscriptions accepted without rate limiting".to_string(),
        ))
    } else if accepted > 0 {
        Ok(SubscriptionResult::Limited(format!(
            "Accepted {accepted} subscriptions before rate limit kicked in"
        )))
    } else {
        Ok(SubscriptionResult::Safe)
    }
}

/// Build a standardized `Finding` for subscription-abuse vulnerabilities.
///
/// Assigns the scanner ID `"gqlprobe"`, tags `"graphql"`, `"subscription"`,
/// and `"dos"`, and maps every finding to CWE-400 (Uncontrolled Resource
/// Consumption). The caller provides the `url`, `title`, `detail`,
/// `severity`, and `remediation` strings; this function wraps them in the
/// `Finding` builder so all subscription-related findings share consistent
/// metadata and can be aggregated across scans.
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::Vulnerability)
        .tag("graphql")
        .tag("subscription")
        .tag("dos")
        .cwe("CWE-400") // Uncontrolled Resource Consumption
        .remediation(remediation)
        .build()?)
}