gqlprobe 1.0.0

Fast GraphQL security scanner - schema-aware introspection, injection, DoS, CSRF, auth bypass, SARIF
Documentation
//! Alias abuse detection module (GQL-011).
//!
//! Tests whether the server accepts queries with excessive field aliases,
//! which can amplify resolver work in a single HTTP request.

use anyhow::Result;
use scanclient::reqwest::header::CONTENT_TYPE;
use scanclient::ScanClient;
use secfinding::{Evidence, Finding, FindingKind, Severity};
use serde_json::json;
use tracing::debug;

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

/// Alias counts to probe (increasing).
const TEST_ALIAS_COUNTS: [usize; 4] = [25, 50, 100, 200];

/// Maximum acceptable alias count before flagging.
const MAX_ACCEPTABLE_ALIASES: usize = 50;

/// Build an alias-heavy query using a schema field when available.
pub fn generate_alias_abuse_query(count: usize, field: &str) -> String {
    let mut query = String::with_capacity(count * 24 + 24);
    query.push_str("query AliasAbuse{");
    for i in 0..count {
        query.push_str(&format!(
            "a{i}:{field}(id:\"__gqlprobe_alias_{i}\"){{__typename}}"
        ));
    }
    query.push('}');
    query
}

/// Legacy helper used by batching tests.
pub fn generate_alias_abuse_query_legacy(count: usize) -> String {
    generate_alias_abuse_query(count, "user")
}

/// Run alias abuse detection with scan context.
pub async fn test_with_context(client: &ScanClient, ctx: &ScanContext) -> Result<Vec<Finding>> {
    test(client, ctx.url(), ctx.schema.as_ref()).await
}

/// Run alias abuse detection.
pub async fn test(
    client: &ScanClient,
    url: &str,
    schema: Option<&SchemaGraph>,
) -> Result<Vec<Finding>> {
    let field = schema
        .and_then(|s| s.query_fields.first())
        .map(|f| f.name.as_str())
        .unwrap_or("user");

    debug!("Testing alias abuse on {} (field={})", url, field);

    let mut findings = Vec::new();
    let mut max_accepted = 0usize;

    for &count in &TEST_ALIAS_COUNTS {
        let query = generate_alias_abuse_query(count, field);
        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 text = resp.body_text().unwrap_or("");
                if text.contains("\"data\"") && !text.to_lowercase().contains("too many aliases") {
                    max_accepted = count;
                }
            }
            _ => break,
        }
    }

    if max_accepted > MAX_ACCEPTABLE_ALIASES {
        findings.push(create_finding(
            url,
            "GraphQL Alias Abuse Allowed",
            &format!(
                "The endpoint processed a query with {max_accepted} field aliases without rejection. \
                 Alias amplification can bypass rate limits and cause resolver exhaustion."
            ),
            Severity::High,
            "Enforce alias limits and query complexity analysis (max aliases, cost analysis).",
            None,
        )?);
    }

    Ok(findings)
}

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::Misconfiguration)
        .tag("graphql")
        .tag("alias-abuse")
        .cwe("CWE-400")
        .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()?)
}