gqlprobe 1.0.0

Fast GraphQL security scanner - schema-aware introspection, injection, DoS, CSRF, auth bypass, SARIF
Documentation
//! Authentication bypass detection module (GQL-010).
//!
//! Detects missing authentication on sensitive operations and
//! common JWT/token bypass patterns in GraphQL endpoints.
//!
//! # Attack Description
//!
//! 1. Sensitive mutations accessible without authentication
//! 2. Introspection reveals auth-required fields
//! 3. JWT bypass via null/empty tokens or algorithm confusion
//!
//! # Detection Method
//!
//! 1. Test sensitive queries without authentication
//! 2. Check introspection for auth field metadata
//! 3. Test common token bypass patterns
//!
//! # Remediation
//!
//! - Enforce authentication on all sensitive operations
//! - Don't leak auth requirements through introspection
//! - Properly validate JWT signatures and algorithms
//! - Reject null/empty authentication tokens

use anyhow::Result;
use scanclient::ScanClient;
use secfinding::{Finding, Severity};
use tracing::debug;

use crate::baseline::EndpointBaseline;
use crate::context::ScanContext;
use crate::schema::SchemaGraph;

/// Sensitive query names that typically require authentication.
pub const SENSITIVE_QUERIES: &[&str] = &[
    "admin", "users", "allUsers", "secrets", "payments", "internal", "system",
];

/// Sensitive mutation names that typically require authentication.
pub const SENSITIVE_MUTATIONS: &[&str] = &[
    "deleteUser",
    "updateUser",
    "createAdmin",
    "deleteAll",
    "resetPassword",
    "changeRole",
];

/// JWT bypass tokens to test.
pub const BYPASS_TOKENS: &[&str] = &[
    "null",
    "",
    "undefined",
    "None",
    "Bearer null",
    "Bearer ",
    "Bearer undefined",
    // JWT with "none" algorithm (alg: none)
    "eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlRlc3QifQ.",
];

/// Test for authentication bypass vulnerabilities.
///
/// Tests for unauthenticated access to sensitive operations and common
/// token bypass patterns.
///
/// # Arguments
///
/// * `client` - The HTTP client for making requests
/// * `url` - The target GraphQL endpoint URL
///
/// # Returns
///
/// Returns findings if authentication bypass is possible.
///
/// # Errors
///
/// Returns an error if HTTP requests fail critically.
/// Run auth bypass checks using shared scan context (schema + baseline).
pub async fn test_with_context(client: &ScanClient, ctx: &ScanContext) -> Result<Vec<Finding>> {
    test_inner(client, ctx.url(), ctx.schema.as_ref(), &ctx.baseline).await
}

/// Test for authentication bypass vulnerabilities.
#[allow(clippy::too_many_lines)]
pub async fn test(client: &ScanClient, url: &str) -> Result<Vec<Finding>> {
    test_inner(client, url, None, &EndpointBaseline::default()).await
}

#[allow(clippy::too_many_lines)]
async fn test_inner(
    client: &ScanClient,
    url: &str,
    schema: Option<&SchemaGraph>,
    baseline: &EndpointBaseline,
) -> Result<Vec<Finding>> {
    let mut findings = Vec::new();

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

    let mut query_targets: Vec<String> = schema
        .map(|s| {
            s.query_fields
                .iter()
                .filter(|f| {
                    crate::schema::is_sensitive_field_name(&f.name) || f.marked_requires_auth
                })
                .map(|f| f.name.clone())
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    if query_targets.is_empty() {
        query_targets = SENSITIVE_QUERIES.iter().map(|s| (*s).to_string()).collect();
    }

    let mut mutation_targets: Vec<String> = schema
        .map(|s| {
            s.mutation_fields
                .iter()
                .filter(|f| {
                    crate::schema::is_sensitive_field_name(&f.name) || f.marked_requires_auth
                })
                .map(|f| f.name.clone())
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    if mutation_targets.is_empty() {
        mutation_targets = SENSITIVE_MUTATIONS
            .iter()
            .map(|s| (*s).to_string())
            .collect();
    }

    // Test 1: Unauthenticated access to sensitive queries
    for query_name in &query_targets {
        match test_unauthenticated_query(client, url, query_name, baseline).await? {
            AuthTestResult::Accessible(response) => {
                findings.push(create_finding(
                    url,
                    &format!("Unauthenticated Access to Sensitive Query: {query_name}"),
                    &format!(
                        "The sensitive query '{query_name}' returned data without any authentication token. \
                         This may allow unauthorized access to privileged information."
                    ),
                    Severity::High,
                    &format!(
                        "Require authentication for all '{query_name}' queries. Implement field-level authorization."
                    ),
                    Some(&response),
                )?);
                break; // One finding is enough to flag the issue
            }
            AuthTestResult::Protected => {}
            AuthTestResult::Error(e) => {
                debug!("Auth test error for query '{}': {}", query_name, e);
            }
        }
    }

    // Test 2: Unauthenticated access to sensitive mutations
    for mutation_name in &mutation_targets {
        match test_unauthenticated_mutation_safe(client, url, mutation_name, baseline).await? {
            AuthTestResult::Accessible(response) => {
                findings.push(create_finding(
                    url,
                    &format!(
                        "Unauthenticated Access to Sensitive Mutation: {mutation_name}"
                    ),
                    &format!(
                        "The sensitive mutation '{mutation_name}' was accepted without authentication. \
                         This may allow unauthorized state changes."
                    ),
                    Severity::Critical,
                    &format!(
                        "Require authentication for all '{mutation_name}' mutations. Validate permissions before execution."
                    ),
                    Some(&response),
                )?);
                break;
            }
            AuthTestResult::Protected => {}
            AuthTestResult::Error(e) => {
                debug!("Auth test error for mutation '{}': {}", mutation_name, e);
            }
        }
    }

    // Baseline: check if the endpoint is publicly accessible without any auth.
    // If so, skip token bypass tests to avoid false positives on public APIs.
    let is_public = baseline.appears_public
        || matches!(
            test_baseline_public(client, url).await?,
            AuthTestResult::Accessible(_)
        );

    // Test 3: JWT/token bypass patterns
    if is_public {
        debug!("Endpoint appears to be public; skipping token bypass tests");
    } else {
        for token in BYPASS_TOKENS {
            match test_token_bypass(client, url, token).await? {
                AuthTestResult::Accessible(response) => {
                    findings.push(create_finding(
                        url,
                        "GraphQL JWT/Token Bypass Possible",
                        &{
                            let safe_token = if token.len() > 20 {
                                format!("{}...[truncated]", &token[..20])
                            } else if token.is_empty() {
                                "(empty)".to_string()
                            } else {
                                (*token).to_string()
                            };
                            format!(
                                "The GraphQL endpoint accepted a malformed/bypass authentication token: '{safe_token}'. \
                                 This indicates weak token validation."
                            )
                        },
                        Severity::Critical,
                        "Properly validate JWT signatures, reject 'none' algorithm, and reject null/empty tokens.",
                        Some(&response),
                    )?);
                    break;
                }
                AuthTestResult::Protected => {}
                AuthTestResult::Error(e) => {
                    debug!("Token bypass test error: {}", e);
                }
            }
        }
    }

    // Test 4: Introspection for auth metadata leakage
    match test_introspection_auth_leak(client, url).await? {
        AuthTestResult::Accessible(response) => {
            findings.push(create_finding(
                url,
                "GraphQL Introspection Leaks Authentication Requirements",
                "The GraphQL schema introspection reveals fields marked as requiring authentication. \
                 While this is common, it aids attackers in identifying privileged operations.",
                Severity::Low,
                "Consider removing auth-related metadata from public introspection, or disable introspection in production.",
                Some(&response),
            )?);
        }
        AuthTestResult::Protected | AuthTestResult::Error(_) => {}
    }

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

mod probes;
// Re-export at the `auth_bypass` path to preserve the public API these probes
// had before they were split into the `probes` submodule (integration/regression
// tests call e.g. `auth_bypass::test_token_bypass`).
use probes::test_baseline_public;
pub use probes::{
    create_finding, test_introspection_auth_leak, test_token_bypass,
    test_unauthenticated_mutation_safe, test_unauthenticated_query, AuthTestResult,
};