gqlprobe 1.0.0

Fast GraphQL security scanner - schema-aware introspection, injection, DoS, CSRF, auth bypass, SARIF
Documentation
//! Response parsers for GraphQL security scanning.
//!
//! Provides structured parsing for common GraphQL response types
//! used across detection modules.

use anyhow::Result;
use serde_json::Value;

/// Parse an introspection response and return the JSON value.
pub fn parse_introspection_response(response: &str) -> Result<Value> {
    let json: Value = serde_json::from_str(response)?;
    Ok(json)
}

/// Parse a batch response and return the individual response values.
pub fn parse_batch_response(response: &str) -> Result<Vec<Value>> {
    let responses: Vec<Value> = serde_json::from_str(response)?;
    Ok(responses)
}

/// Parse an error response and extract error messages.
pub fn parse_error_response(response: &str) -> Result<Vec<String>> {
    let json: Value = serde_json::from_str(response)?;
    let mut messages = Vec::new();
    if let Some(errors) = json.get("errors").and_then(|e| e.as_array()) {
        for error in errors {
            if let Some(msg) = error.get("message").and_then(|m| m.as_str()) {
                messages.push(msg.to_string());
            }
        }
    }
    Ok(messages)
}

/// Parse a deeply nested JSON response and compute the maximum nesting depth.
pub fn parse_depth_response(response: &str) -> Result<usize> {
    match serde_json::from_str::<Value>(response) {
        Ok(json) => Ok(max_depth(&json)),
        Err(e) if is_recursion_limit_error(&e) => Ok(compute_depth_nonrecursive(response)?),
        Err(e) => Err(e.into()),
    }
}

fn is_recursion_limit_error(e: &serde_json::Error) -> bool {
    e.to_string().contains("recursion limit exceeded")
}

#[allow(clippy::similar_names)]
fn max_depth(value: &Value) -> usize {
    let mut max = 0usize;
    let mut stack = vec![(value, 1usize)];

    while let Some((current, depth)) = stack.pop() {
        if depth > max {
            max = depth;
        }
        match current {
            Value::Object(map) => {
                for v in map.values() {
                    stack.push((v, depth.saturating_add(1)));
                }
            }
            Value::Array(arr) => {
                for v in arr {
                    stack.push((v, depth.saturating_add(1)));
                }
            }
            _ => {}
        }
    }

    max
}

/// Non-recursive depth calculator for JSON that exceeds `serde_json`'s recursion limit.
#[allow(clippy::too_many_lines)]
fn compute_depth_nonrecursive(response: &str) -> Result<usize> {
    let mut max = 0usize;
    let mut in_string = false;
    let mut escape = false;
    let mut stack: Vec<(char, bool)> = Vec::new(); // (opening brace, has_children)
    let mut needs_value = false;
    let mut in_value = false;

    for ch in response.chars() {
        if in_string {
            if escape {
                escape = false;
            } else if ch == '\\' {
                escape = true;
            } else if ch == '"' {
                in_string = false;
                if let Some((_, has_children)) = stack.last_mut() {
                    if needs_value {
                        *has_children = true;
                        needs_value = false;
                    }
                }
            }
        } else {
            match ch {
                '{' | '[' => {
                    if let Some((_, has_children)) = stack.last_mut() {
                        if needs_value {
                            *has_children = true;
                        }
                    }
                    let current_depth = stack.len() + 1;
                    if current_depth > max {
                        max = current_depth;
                    }
                    stack.push((ch, false));
                    needs_value = ch == '[';
                    in_value = false;
                }
                '}' => {
                    in_value = false;
                    let (open, has_children) = stack
                        .pop()
                        .ok_or_else(|| anyhow::anyhow!("unexpected }}"))?;
                    if open != '{' {
                        anyhow::bail!("mismatched brace. Fix: ensure every opening brace has a matching closing brace in the query");
                    }
                    let current_depth = stack.len() + 1;
                    if has_children {
                        max = max.max(current_depth + 1);
                    } else {
                        max = max.max(current_depth);
                    }
                    needs_value = false;
                }
                ']' => {
                    in_value = false;
                    let (open, has_children) =
                        stack.pop().ok_or_else(|| anyhow::anyhow!("unexpected ]"))?;
                    if open != '[' {
                        anyhow::bail!("mismatched bracket. Fix: ensure every opening bracket has a matching closing bracket in the query");
                    }
                    let current_depth = stack.len() + 1;
                    if has_children {
                        max = max.max(current_depth + 1);
                    } else {
                        max = max.max(current_depth);
                    }
                    needs_value = false;
                }
                '"' => {
                    in_string = true;
                    in_value = false;
                }
                ':' => {
                    if stack.last().map(|(c, _)| *c) != Some('{') {
                        anyhow::bail!(
                            ": outside object. Fix: use ':' only inside an object selection set"
                        );
                    }
                    needs_value = true;
                    in_value = false;
                }
                ',' => {
                    in_value = false;
                    if let Some((open, _)) = stack.last() {
                        needs_value = *open == '[';
                    } else {
                        anyhow::bail!(
                            ", outside container. Fix: use ',' only inside an object or list"
                        );
                    }
                }
                c if c.is_whitespace() => {
                    in_value = false;
                }
                _ => {
                    if !in_value {
                        if let Some((_, has_children)) = stack.last_mut() {
                            if needs_value {
                                *has_children = true;
                                needs_value = false;
                            }
                        }
                        in_value = true;
                    }
                }
            }
        }
    }

    if in_string {
        anyhow::bail!("unclosed string. Fix: close every quote in the query");
    }
    if !stack.is_empty() {
        anyhow::bail!("unclosed container. Fix: close every opening brace or bracket in the query");
    }

    Ok(max)
}