gqlprobe 1.0.0

Fast GraphQL security scanner - schema-aware introspection, injection, DoS, CSRF, auth bypass, SARIF
Documentation
//! GraphQL schema discovery and permission metadata from introspection.

use std::collections::HashMap;

use anyhow::Result;
use scanclient::ScanClient;
use serde_json::Value;
use tracing::debug;

use crate::modules::introspection::{
    send_introspection_query, IntrospectionResult, SIMPLE_INTROSPECTION_QUERY,
};

/// Lightweight schema map used to drive targeted security tests.
#[derive(Debug, Clone, Default)]
pub struct SchemaGraph {
    /// Root query type name (usually `Query`).
    pub query_type: Option<String>,
    /// Root mutation type name, if present.
    pub mutation_type: Option<String>,
    /// Fields on the root query type.
    pub query_fields: Vec<SchemaField>,
    /// Fields on the root mutation type.
    pub mutation_fields: Vec<SchemaField>,
    /// Nested object fields useful for depth/alias tests: `(parent_type, field_name)`.
    pub nested_object_fields: Vec<(String, String)>,
    /// String/ID arguments on query fields for injection probes.
    pub injectable_args: Vec<InjectableArg>,
    /// ID/Int arguments suitable for IDOR/BOLA probes.
    pub id_lookup_args: Vec<IdLookupArg>,
}

/// A field on a GraphQL type with optional auth metadata.
#[derive(Debug, Clone)]
pub struct SchemaField {
    /// Field name.
    pub name: String,
    /// Owning GraphQL type.
    pub parent_type: String,
    /// True when introspection lists auth-related directives.
    pub marked_requires_auth: bool,
}

/// An ID-like argument on a query/mutation field (IDOR/BOLA probes).
#[derive(Debug, Clone)]
pub struct IdLookupArg {
    /// Root field name.
    pub field: String,
    /// Argument name (e.g. `id`, `userId`).
    pub arg: String,
    /// Whether the field lives on the mutation root.
    pub is_mutation: bool,
    /// Inferred scalar type name.
    pub type_name: String,
}

/// An argument suitable for injection testing.
#[derive(Debug, Clone)]
pub struct InjectableArg {
    /// Root field name (query or mutation).
    pub field: String,
    /// Argument name.
    pub arg: String,
    /// Whether the field lives on the mutation root.
    pub is_mutation: bool,
    /// Inferred scalar type name.
    pub type_name: String,
}

const SCHEMA_DISCOVERY_QUERY: &str = r"
query GqlprobeSchemaDiscovery {
  __schema {
    queryType { name }
    mutationType { name }
    types {
      kind
      name
      fields {
        name
        args {
          name
          type {
            kind
            name
            ofType { kind name ofType { kind name } }
          }
        }
      }
    }
  }
}
";

/// Discover schema via introspection. Returns `None` when introspection is disabled.
pub async fn discover(client: &ScanClient, url: &str) -> Result<Option<SchemaGraph>> {
    debug!("Discovering GraphQL schema for {}", url);

    let result = send_introspection_query(client, url, SCHEMA_DISCOVERY_QUERY, None).await?;

    match result {
        IntrospectionResult::Enabled(body) => Ok(Some(parse_schema_response(&body)?)),
        IntrospectionResult::Disabled | IntrospectionResult::Error(_) => {
            // Fallback: minimal query type probe
            let fallback =
                send_introspection_query(client, url, SIMPLE_INTROSPECTION_QUERY, None).await?;
            match fallback {
                IntrospectionResult::Enabled(body) => {
                    if let Ok(json) = serde_json::from_str::<Value>(&body) {
                        let query_type = json
                            .pointer("/data/__schema/queryType/name")
                            .and_then(|v| v.as_str())
                            .map(str::to_string);
                        return Ok(Some(SchemaGraph {
                            query_type,
                            ..SchemaGraph::default()
                        }));
                    }
                    Ok(None)
                }
                _ => Ok(None),
            }
        }
    }
}

/// Parse introspection JSON into a [`SchemaGraph`].
pub fn parse_schema_response(body: &str) -> Result<SchemaGraph> {
    let json: Value = serde_json::from_str(body)?;
    let schema = json
        .pointer("/data/__schema")
        .ok_or_else(|| anyhow::anyhow!("missing __schema in introspection response"))?;

    let query_type = schema
        .pointer("/queryType/name")
        .and_then(|v| v.as_str())
        .map(str::to_string);
    let mutation_type = schema
        .pointer("/mutationType/name")
        .and_then(|v| v.as_str())
        .map(str::to_string);

    let types = schema
        .get("types")
        .and_then(|t| t.as_array())
        .cloned()
        .unwrap_or_default();

    let type_fields: HashMap<String, Vec<(String, Vec<Value>, bool)>> = types
        .iter()
        .filter_map(|t| {
            let name = t.get("name")?.as_str()?;
            let fields = t.get("fields")?.as_array()?;
            let mut parsed = Vec::new();
            for f in fields {
                let fname = f.get("name")?.as_str()?;
                let args = f
                    .get("args")
                    .and_then(|a| a.as_array())
                    .cloned()
                    .unwrap_or_default();
                let marked = field_marked_requires_auth(f);
                parsed.push((fname.to_string(), args, marked));
            }
            Some((name.to_string(), parsed))
        })
        .collect();

    let mut graph = SchemaGraph {
        query_type: query_type.clone(),
        mutation_type: mutation_type.clone(),
        ..SchemaGraph::default()
    };

    if let Some(ref qt) = query_type {
        if let Some(fields) = type_fields.get(qt) {
            for (name, args, marked) in fields {
                graph.query_fields.push(SchemaField {
                    name: name.clone(),
                    parent_type: qt.clone(),
                    marked_requires_auth: *marked,
                });
                collect_injectable(&mut graph, &name, args, false);
            }
        }
    }

    if let Some(ref mt) = mutation_type {
        if let Some(fields) = type_fields.get(mt) {
            for (name, args, marked) in fields {
                graph.mutation_fields.push(SchemaField {
                    name: name.clone(),
                    parent_type: mt.clone(),
                    marked_requires_auth: *marked,
                });
                collect_injectable(&mut graph, &name, args, true);
            }
        }
    }

    // Collect one level of nested object fields for depth testing
    for (type_name, fields) in &type_fields {
        if type_name.starts_with("__") {
            continue;
        }
        for (field_name, _, _) in fields {
            graph
                .nested_object_fields
                .push((type_name.clone(), field_name.clone()));
            if graph.nested_object_fields.len() >= 32 {
                break;
            }
        }
        if graph.nested_object_fields.len() >= 32 {
            break;
        }
    }

    Ok(graph)
}

fn collect_injectable(graph: &mut SchemaGraph, field: &str, args: &[Value], is_mutation: bool) {
    for arg in args {
        let Some(arg_name) = arg.get("name").and_then(|n| n.as_str()) else {
            continue;
        };
        let type_name = resolve_type_name(arg.get("type"));
        if is_string_like(&type_name) {
            graph.injectable_args.push(InjectableArg {
                field: field.to_string(),
                arg: arg_name.to_string(),
                is_mutation,
                type_name: type_name.clone(),
            });
        }
        if is_id_lookup(&type_name, arg_name) {
            graph.id_lookup_args.push(IdLookupArg {
                field: field.to_string(),
                arg: arg_name.to_string(),
                is_mutation,
                type_name,
            });
        }
    }
}

fn is_id_lookup(type_name: &str, arg_name: &str) -> bool {
    let tn = type_name.to_uppercase();
    let scalar_ok = matches!(tn.as_str(), "ID" | "INT" | "INTEGER" | "UUID");
    if !scalar_ok {
        return false;
    }
    let a = arg_name.to_lowercase();
    a == "id"
        || a.ends_with("id")
        || a.contains("uuid")
        || a == "uid"
        || a == "accountid"
        || a == "userid"
}

fn resolve_type_name(type_node: Option<&Value>) -> String {
    let Some(node) = type_node else {
        return "Unknown".to_string();
    };
    if let Some(name) = node.get("name").and_then(|n| n.as_str()) {
        return name.to_string();
    }
    if let Some(inner) = node.get("ofType") {
        return resolve_type_name(Some(inner));
    }
    "Unknown".to_string()
}

fn is_string_like(type_name: &str) -> bool {
    matches!(
        type_name,
        "String" | "ID" | "UUID" | "Email" | "Url" | "JSON" | "JSONObject"
    )
}

fn field_marked_requires_auth(field: &Value) -> bool {
    let text = field.to_string().to_lowercase();
    text.contains("requiresauth")
        || text.contains("isauthenticated")
        || text.contains("@auth")
        || text.contains("authenticated")
        || text.contains("requires_auth")
        || text.contains("loginrequired")
}

/// Sensitive field names for permission heuristics when directives are absent.
pub fn is_sensitive_field_name(name: &str) -> bool {
    let n = name.to_lowercase();
    n.contains("admin")
        || n.contains("secret")
        || n.contains("password")
        || n.contains("token")
        || n.contains("payment")
        || n.contains("internal")
        || n == "users"
        || n == "user"
        || n.contains("private")
}

/// Build a minimal selection set for a schema field (first scalar subfield or `id`).
pub fn selection_for_field(field: &SchemaField) -> &'static str {
    if field.name.ends_with('s') {
        "{ id }"
    } else {
        "{ id }"
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_minimal_schema_extracts_query_fields() {
        let body = r#"{
          "data": {
            "__schema": {
              "queryType": { "name": "Query" },
              "mutationType": { "name": "Mutation" },
              "types": [
                {
                  "kind": "OBJECT",
                  "name": "Query",
                  "fields": [
                    {
                      "name": "users",
                      "args": [{ "name": "filter", "type": { "kind": "SCALAR", "name": "String" } }]
                    }
                  ]
                },
                {
                  "kind": "OBJECT",
                  "name": "Mutation",
                  "fields": [
                    { "name": "deleteUser", "args": [{ "name": "id", "type": { "kind": "SCALAR", "name": "ID" } }] }
                  ]
                }
              ]
            }
          }
        }"#;
        let graph = parse_schema_response(body).unwrap();
        assert_eq!(graph.query_type.as_deref(), Some("Query"));
        assert_eq!(graph.query_fields.len(), 1);
        assert_eq!(graph.mutation_fields.len(), 1);
        assert!(!graph.injectable_args.is_empty());
        assert!(!graph.id_lookup_args.is_empty());
    }
}