gqlprobe 1.0.0

Fast GraphQL security scanner - schema-aware introspection, injection, DoS, CSRF, auth bypass, SARIF
Documentation
use crate::baseline::{has_auth_errors, has_meaningful_field_data, EndpointBaseline};
use anyhow::Result;
use scanclient::reqwest::header::{AUTHORIZATION, CONTENT_TYPE};
use scanclient::ScanClient;
use secfinding::{Evidence, Finding, FindingKind, Severity};
use serde_json::{json, Value};

/// Outcome of an authentication bypass probe.
///
/// Each variant represents a discrete security state discovered while
/// testing whether a protected operation can be accessed without valid
/// credentials.
#[derive(Debug)]
pub enum AuthTestResult {
    /// The operation returned data without requiring authentication.
    ///
    /// This variant is returned when the server responds with HTTP 200,
    /// a non-null `data` key, and no auth-related error messages. It is
    /// the primary indicator of an authentication bypass and is reported
    /// as a finding because unauthorized callers can read or mutate
    /// resources that should be restricted.
    Accessible(String),
    /// The operation is correctly protected and refused the unauthenticated request.
    ///
    /// This variant is returned when the server responds with an auth
    /// error (e.g., "unauthorized", "forbidden") or returns null/empty
    /// data. This is the desired outcome; no finding is generated.
    Protected,
    /// The probe could not complete due to a transport or parsing failure.
    ///
    /// This variant is returned when the HTTP request fails or the
    /// response cannot be parsed. Errors are logged for diagnostics but
    /// are not reported as findings to avoid false positives from
    /// transient network failures.
    Error(String),
}

/// Probe whether a sensitive query returns data without any authentication token.
///
/// GraphQL queries such as `admin`, `users`, or `payments` often expose
/// privileged data. If the endpoint serves these fields to an
/// unauthenticated client, the API lacks proper access control.
///
/// Returns `AuthTestResult::Accessible` when the server responds with
/// HTTP 200, a non-null `data` object, and no error message containing
/// auth-related keywords. Returns `Protected` when auth errors or null
/// data are detected. Returns `Error` on network or parse failures.
pub async fn test_unauthenticated_query(
    client: &ScanClient,
    url: &str,
    query_name: &str,
    _baseline: &EndpointBaseline,
) -> Result<AuthTestResult> {
    let query = format!("query {{ {query_name} {{ __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_string();
            let parsed = serde_json::from_str::<Value>(&body_text).ok();

            if let Some(ref json) = parsed {
                if resp.status().is_success()
                    && has_meaningful_field_data(json, query_name)
                    && !has_auth_errors(json)
                {
                    return Ok(AuthTestResult::Accessible(body_text.to_lowercase()));
                }
            }

            Ok(AuthTestResult::Protected)
        }
        Err(e) => Ok(AuthTestResult::Error(e.to_string())),
    }
}

/// Probe whether a sensitive mutation is accepted without authentication.
///
/// Mutations such as `deleteUser` or `resetPassword` modify state and
/// must always be guarded. The probe sends a mutation with the safe
/// placeholder ID `__gqlprobe_test__` to avoid accidental data loss.
///
/// Returns `AuthTestResult::Accessible` when the server accepts the
/// mutation without an auth error. Returns `Protected` when auth
/// errors are present or the response lacks a `data` key. Returns
/// `Error` on network or parse failures.
pub async fn test_unauthenticated_mutation_safe(
    client: &ScanClient,
    url: &str,
    mutation_name: &str,
    _baseline: &EndpointBaseline,
) -> Result<AuthTestResult> {
    let query =
        format!(r#"mutation {{ {mutation_name}(id: "__gqlprobe_test__") {{ __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_string();
            let parsed = serde_json::from_str::<Value>(&body_text).ok();

            if let Some(ref json) = parsed {
                if resp.status().is_success()
                    && has_meaningful_field_data(json, mutation_name)
                    && !has_auth_errors(json)
                {
                    return Ok(AuthTestResult::Accessible(body_text.to_lowercase()));
                }
            }

            Ok(AuthTestResult::Protected)
        }
        Err(e) => Ok(AuthTestResult::Error(e.to_string())),
    }
}

pub(super) async fn test_baseline_public(client: &ScanClient, url: &str) -> Result<AuthTestResult> {
    let body = json!({ "query": "{ __typename }" });
    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("data")
                && !body_text.contains("errors")
            {
                return Ok(AuthTestResult::Accessible(body_text));
            }

            Ok(AuthTestResult::Protected)
        }
        Err(e) => Ok(AuthTestResult::Error(e.to_string())),
    }
}

/// Probe whether the endpoint accepts malformed, empty, or algorithm-stripped JWT tokens.
///
/// Weak token validation is a common auth bypass vector. This probe
/// sends tokens such as `null`, empty strings, and a JWT with
/// `alg: none` in the Authorization header.
///
/// Returns `AuthTestResult::Accessible` when the server processes the
/// request and returns valid GraphQL data, indicating that token
/// parsing is insufficient. Returns `Protected` when the token is
/// rejected. Returns `Error` on network or parse failures.
pub async fn test_token_bypass(
    client: &ScanClient,
    url: &str,
    token: &str,
) -> Result<AuthTestResult> {
    let body = json!({ "query": "{ __typename }" });
    let request = client
        .request(scanclient::reqwest::Method::POST, url)
        .header(CONTENT_TYPE, "application/json")
        .header(AUTHORIZATION, token)
        .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("data")
                && !body_text.contains("errors")
            {
                return Ok(AuthTestResult::Accessible(body_text));
            }

            Ok(AuthTestResult::Protected)
        }
        Err(e) => Ok(AuthTestResult::Error(e.to_string())),
    }
}

/// Probe whether the GraphQL introspection schema exposes authentication metadata.
///
/// Fields whose descriptions contain words such as "auth", "login",
/// "token", or "password" reveal privileged operations to unauthenticated
/// attackers, reducing the effort needed to plan an attack.
///
/// Returns `AuthTestResult::Accessible` when the introspection response
/// contains auth-related field descriptions. Returns `Protected` when
/// no such metadata is found or introspection is unavailable. Returns
/// `Error` on network or parse failures.
pub async fn test_introspection_auth_leak(
    client: &ScanClient,
    url: &str,
) -> Result<AuthTestResult> {
    let query = r#"
        {
            __type(name: "Query") {
                fields {
                    name
                    description
                }
            }
        }
    "#;
    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();
            let parsed = serde_json::from_str::<serde_json::Value>(&body_text);

            if let Ok(json) = parsed {
                if let Some(fields) = json.pointer("/data/__type/fields") {
                    let fields_str = fields.to_string().to_lowercase();
                    if fields_str.contains("auth")
                        || fields_str.contains("login")
                        || fields_str.contains("token")
                        || fields_str.contains("password")
                    {
                        return Ok(AuthTestResult::Accessible(body_text));
                    }
                }
            }

            Ok(AuthTestResult::Protected)
        }
        Err(e) => Ok(AuthTestResult::Error(e.to_string())),
    }
}

/// Build a standardized `Finding` for an authentication bypass result.
///
/// The finding is tagged with `graphql`, `authentication`, and
/// `auth-bypass` so that downstream reporting and dashboards can
/// filter and group results. It is mapped to `CWE-287`
/// (Improper Authentication) for compliance alignment.
///
/// `severity` is caller-supplied because impact varies:
/// unauthenticated access to a sensitive query is typically `High`,
/// while unauthenticated mutations or JWT bypasses are escalated to
/// `Critical`. Optional `evidence_body` is truncated to 1 000
/// characters and attached as raw evidence so the report contains a
/// reproducible proof-of-concept.
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::Vulnerability)
        .tag("graphql")
        .tag("authentication")
        .tag("auth-bypass")
        .cwe("CWE-287") // Improper Authentication
        .remediation(remediation);

    if let Some(body) = evidence_body {
        let excerpt = if body.chars().count() > 1000 {
            format!(
                "{}...[truncated]",
                body.chars().take(1000).collect::<String>()
            )
        } else {
            body.to_string()
        };
        builder = builder.evidence(Evidence::raw(excerpt));
    }

    Ok(builder.build()?)
}