gqlprobe 1.0.0

Fast GraphQL security scanner - schema-aware introspection, injection, DoS, CSRF, auth bypass, SARIF
Documentation
//! Schema-aware IDOR / BOLA probe (GQL-013).
//!
//! When introspection reveals query fields with ID-like arguments, probes whether
//! different object identifiers return data without authorization differentiation.

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

use crate::baseline::{has_auth_errors, has_meaningful_field_data};
use crate::context::ScanContext;
use crate::schema::{IdLookupArg, SchemaGraph};

/// Maximum ID lookup probes per scan (limits traffic).
pub const MAX_IDOR_PROBES: usize = 4;

/// Alternate probe values for ID/Int arguments.
const PROBE_VALUES: &[&str] = &["1", "2"];

/// Run IDOR probes when schema ID arguments are known.
pub async fn test_with_context(client: &ScanClient, ctx: &ScanContext) -> Result<Vec<Finding>> {
    let Some(ref schema) = ctx.schema else {
        debug!("Skipping IDOR probe: no schema available");
        return Ok(Vec::new());
    };
    test(client, ctx.url(), schema, &ctx.baseline).await
}

/// Probe ID-based lookups using schema metadata.
pub async fn test(
    client: &ScanClient,
    url: &str,
    schema: &SchemaGraph,
    baseline: &crate::baseline::EndpointBaseline,
) -> Result<Vec<Finding>> {
    if schema.id_lookup_args.is_empty() || baseline.appears_public {
        return Ok(Vec::new());
    }

    let mut findings = Vec::new();

    for arg in schema.id_lookup_args.iter().take(MAX_IDOR_PROBES) {
        if let Some(finding) = probe_id_pair(client, url, arg, baseline).await? {
            findings.push(finding);
            break;
        }
    }

    Ok(findings)
}

async fn probe_id_pair(
    client: &ScanClient,
    url: &str,
    lookup: &IdLookupArg,
    _baseline: &crate::baseline::EndpointBaseline,
) -> Result<Option<Finding>> {
    let mut responses = Vec::new();

    for value in PROBE_VALUES {
        let op = if lookup.is_mutation {
            format!(
                "mutation {{ {}({}: \"{}\") {{ __typename }} }}",
                lookup.field, lookup.arg, value
            )
        } else {
            format!(
                "query {{ {}({}: \"{}\") {{ __typename }} }}",
                lookup.field, lookup.arg, value
            )
        };
        let body = json!({ "query": op });
        let request = client
            .request(scanclient::reqwest::Method::POST, url)
            .header(CONTENT_TYPE, "application/json")
            .body(body.to_string());

        let Ok(resp) = client.execute(request).await else {
            return Ok(None);
        };

        let status = resp.status();
        let text = resp.body_text().unwrap_or_default().to_string();
        let Ok(json) = serde_json::from_str::<Value>(&text) else {
            return Ok(None);
        };

        if !status.is_success()
            || has_auth_errors(&json)
            || !has_meaningful_field_data(&json, &lookup.field)
        {
            return Ok(None);
        }

        responses.push((value, text, json));
    }

    if responses.len() < 2 {
        return Ok(None);
    }

    let (_, ref body_a, ref json_a) = responses[0];
    let (_, ref body_b, ref json_b) = responses[1];

    if json_a != json_b || body_a != body_b {
        return Ok(Some(create_finding(
            url,
            &format!(
                "ID-Based Object Lookup Without Auth Differentiation: {}.{}",
                lookup.field, lookup.arg
            ),
            &format!(
                "Schema exposes `{}` on `{}` with `{}` argument. Probes with values {:?} \
                 both returned data without authentication errors, suggesting missing \
                 object-level authorization checks.",
                lookup.field,
                if lookup.is_mutation { "Mutation" } else { "Query" },
                lookup.arg,
                PROBE_VALUES
            ),
            Severity::Medium,
            "Enforce object-level authorization in resolvers; validate the caller may access each ID.",
            Some(format!("{body_a}\n---\n{body_b}")),
        )?));
    }

    Ok(None)
}

fn create_finding(
    url: &str,
    title: &str,
    detail: &str,
    severity: Severity,
    remediation: &str,
    evidence: Option<String>,
) -> Result<Finding> {
    let mut builder = Finding::builder("gqlprobe", url, severity)
        .title(title)
        .detail(detail)
        .remediation(remediation)
        .kind(FindingKind::AccessControl)
        .tag("graphql")
        .tag("idor")
        .tag("bola")
        .cwe("CWE-639");

    if let Some(body) = evidence {
        builder = builder.evidence(Evidence::raw(body));
    }

    Ok(builder.build()?)
}