gqlprobe 1.0.0

Fast GraphQL security scanner - schema-aware introspection, injection, DoS, CSRF, auth bypass, SARIF
Documentation
//! CLI layer for the gqlprobe binary.

use anyhow::{Context, Result};
use clap::{Parser, ValueEnum};
use secfinding::Finding;
use tracing::{info, warn};

use crate::scanner::{ScanConfig, ScannerBuilder};

/// GraphQL security scanner
#[derive(Parser, Debug)]
#[command(
    name = "gqlprobe",
    about = "GraphQL security scanner - schema-aware introspection, injection, DoS, CSRF, SARIF",
    long_about = "gqlprobe maps your GraphQL schema via introspection, calibrates baseline behavior, \
                  then runs 14 concurrent security modules. Output: human, JSON, JSONL, or SARIF.\n\n\
                  Authorized testing only.",
    version,
    after_help = "Module IDs: GQL-001 introspection … GQL-014 rate-limit. Run --list-modules for details."
)]
pub struct Cli {
    /// Target GraphQL endpoint URL
    #[arg(value_name = "URL", help = "Target GraphQL endpoint URL")]
    pub target: Option<String>,

    /// Print built-in module IDs and exit
    #[arg(long, help = "List detection modules and exit")]
    pub list_modules: bool,

    /// Output format
    #[arg(
        short,
        long,
        value_enum,
        default_value = "human",
        help = "Output format for findings"
    )]
    pub output: OutputFormat,

    /// Global timeout in seconds
    #[arg(
        short,
        long,
        default_value = "300",
        help = "Maximum time for the entire scan (seconds)"
    )]
    pub timeout: u64,

    /// Module timeout in seconds
    #[arg(
        long,
        default_value = "60",
        help = "Maximum time for any single test module (seconds)"
    )]
    pub module_timeout: u64,

    /// Maximum concurrent modules
    #[arg(
        short,
        long,
        default_value = "5",
        help = "Maximum number of concurrent test modules"
    )]
    pub concurrency: usize,

    /// HTTP timeout in seconds
    #[arg(long, default_value = "10", help = "HTTP request timeout (seconds)")]
    pub http_timeout: u64,

    /// Disable TLS certificate verification
    #[arg(long, help = "Disable TLS certificate verification (insecure)")]
    pub insecure: bool,

    /// Custom HTTP headers (format: "Key: Value")
    #[arg(
        short = 'H',
        long,
        help = "Add custom HTTP header (format: 'Key: Value')"
    )]
    pub header: Vec<String>,

    /// Proxy URL
    #[arg(short, long, help = "Proxy URL (e.g., http://127.0.0.1:8080)")]
    pub proxy: Option<String>,

    /// Enable verbose logging
    #[arg(short, long, help = "Enable verbose logging")]
    pub verbose: bool,

    /// Enable debug logging
    #[arg(long, help = "Enable debug logging")]
    pub debug: bool,

    /// Run only these modules (e.g. GQL-001,GQL-006). Default: all modules.
    #[arg(
        long,
        value_delimiter = ',',
        help = "Comma-separated module IDs to run (e.g. GQL-001,GQL-006)"
    )]
    pub modules: Option<Vec<String>>,

    /// Skip introspection-based schema discovery (faster, generic probes only).
    #[arg(long, help = "Skip schema discovery via introspection")]
    pub skip_schema: bool,
}

/// Output format options
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum OutputFormat {
    /// Human-readable format with colors
    Human,
    /// JSON format
    Json,
    /// Compact JSON format (one finding per line)
    Jsonl,
    /// SARIF v2.1.0 report
    Sarif,
}

/// Initialize tracing logger.
pub fn init_logging(verbose: bool, debug: bool) {
    let filter = if debug {
        "gqlprobe=debug,scanclient=debug,secfinding=debug"
    } else if verbose {
        "gqlprobe=info,scanclient=warn,secfinding=warn"
    } else {
        "gqlprobe=warn,scanclient=error,secfinding=error"
    };

    if let Err(e) = tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_target(false)
        .with_thread_ids(false)
        .with_file(false)
        .with_line_number(false)
        .try_init()
    {
        use std::io::Write;
        let _ = writeln!(
            std::io::stderr(),
            "Warning: could not initialize logger: {e}"
        );
    }
}

/// Validate that the target string is a valid HTTP(S) URL.
pub fn validate_target(target: &str) -> Result<()> {
    let url = target
        .parse::<scanclient::reqwest::Url>()
        .context("URL must be a valid HTTP or HTTPS URL")?;

    if url.scheme() != "http" && url.scheme() != "https" {
        anyhow::bail!(
            "URL scheme must be http or https. Fix: prefix the target with http:// or https://"
        );
    }

    if url.host().is_none() {
        anyhow::bail!(
            "URL must have a host. Fix: include a hostname, e.g. https://api.example.com/graphql"
        );
    }

    // Reject URLs with an empty authority section (e.g. http:///path) that
    // the WHATWG URL parser may reinterpret as host=path.
    if target.to_lowercase().starts_with("http:///")
        || target.to_lowercase().starts_with("https:///")
    {
        anyhow::bail!("URL must have a host. Fix: include a hostname between the scheme and path, e.g. https://api.example.com/graphql");
    }

    // Reject URLs with embedded credentials to prevent accidental leakage.
    if !url.username().is_empty() || url.password().is_some() {
        anyhow::bail!("URL must not contain credentials. Fix: remove the user:pass@ prefix and pass auth via --header instead");
    }

    Ok(())
}

/// Print all built-in detection modules.
pub fn print_modules() {
    use std::io::Write;
    let mut out = std::io::stdout().lock();
    let _ = writeln!(out, "gqlprobe detection modules:\n");
    for (id, name) in crate::scanner::Scanner::module_catalog() {
        let _ = writeln!(out, "  {id}  {name}");
    }
    let _ = writeln!(out, "\nRun: gqlprobe <URL> [--modules GQL-001,GQL-006]");
}

/// Run the scan based on CLI options.
pub async fn run_scan(cli: &Cli) -> Result<Vec<Finding>> {
    let target = cli
        .target
        .as_ref()
        .ok_or_else(|| anyhow::anyhow!("URL is required (or use --list-modules)"))?;
    info!("Scanning target: {}", target);

    // Build HTTP config
    let http_config = build_http_config(cli)?;

    // Build scan config
    let scan_config = ScanConfig {
        global_timeout_secs: cli.timeout,
        module_timeout_secs: cli.module_timeout,
        max_concurrency: cli.concurrency,
        http_config,
        skip_schema_discovery: cli.skip_schema,
    };

    // Create and run scanner
    let mut builder = ScannerBuilder::new()
        .target(target)
        .global_timeout(cli.timeout)
        .module_timeout(cli.module_timeout)
        .max_concurrency(cli.concurrency)
        .http_config(scan_config.http_config)
        .skip_schema_discovery(cli.skip_schema);

    if let Some(ref module_ids) = cli.modules {
        let ids: Vec<&str> = module_ids.iter().map(String::as_str).collect();
        validate_module_ids(&ids)?;
        builder = builder.modules(&ids);
    }

    let scanner = builder.build().context("Failed to create scanner")?;

    let findings = scanner.scan().await.context("Scan execution failed")?;

    info!("Scan complete: {} findings", findings.len());
    Ok(findings)
}

/// Build HTTP configuration from CLI options.
pub fn build_http_config(cli: &Cli) -> Result<scanclient::HttpConfig> {
    use scanclient::HttpConfig;

    let mut custom_headers = std::collections::HashMap::new();

    // Parse custom headers first so we can construct the struct in one shot.
    for header in &cli.header {
        if let Some((key, value)) = header.split_once(':') {
            let key = key.trim().to_string();
            if key.is_empty() {
                anyhow::bail!("Invalid header format: {header}. Header key cannot be empty. Fix: use 'Key: Value' with a non-empty key");
            }
            let value = value.trim().to_string();
            custom_headers.insert(key, value);
        } else {
            anyhow::bail!("Invalid header format: {header}. Expected 'Key: Value'. Fix: pass each header as -H 'Name: Value'");
        }
    }

    let mut config = HttpConfig {
        timeout_secs: cli.http_timeout,
        connect_timeout_secs: cli.http_timeout.clamp(1, 10),
        custom_headers,
        ..HttpConfig::default()
    };

    if cli.insecure {
        config.tls_verify = false;
        config.tls_accept_invalid_certs = true;
        config.tls_accept_invalid_hostnames = true;
        warn!("TLS certificate verification disabled - this is insecure!");
    }

    if let Some(ref proxy) = cli.proxy {
        config.proxy = Some(proxy.clone());
        info!("Using proxy: {}", proxy);
    }

    Ok(config)
}

/// Validate module IDs against the built-in registry.
pub fn validate_module_ids(ids: &[&str]) -> Result<()> {
    let known = crate::scanner::Scanner::all_module_ids();
    for id in ids {
        if !known.contains(id) {
            anyhow::bail!(
                "Unknown module ID '{id}'. Fix: pass one of the valid IDs: {}",
                known.join(", ")
            );
        }
    }
    Ok(())
}

/// Output findings in the requested format.
pub fn output_findings(findings: &[Finding], format: OutputFormat) -> Result<()> {
    let mut stdout = std::io::stdout();
    match format {
        OutputFormat::Human => output_human(findings, &mut stdout),
        OutputFormat::Json => output_json(findings, &mut stdout),
        OutputFormat::Jsonl => output_jsonl(findings, &mut stdout),
        OutputFormat::Sarif => output_sarif(findings, &mut stdout),
    }
}

/// Output findings as SARIF v2.1.0.
pub fn output_sarif(findings: &[Finding], writer: &mut dyn std::io::Write) -> Result<()> {
    use secreport::{render, Format};
    let body =
        render(findings, Format::Sarif, "gqlprobe").context("Failed to render SARIF report")?;
    writeln!(writer, "{body}")?;
    Ok(())
}

/// Output findings in human-readable format.
pub fn output_human(findings: &[Finding], writer: &mut dyn std::io::Write) -> Result<()> {
    if findings.is_empty() {
        return Ok(());
    }

    writeln!(writer, "\n{}", "=".repeat(80))?;
    writeln!(writer, "SECURITY FINDINGS")?;
    writeln!(writer, "{}", "=".repeat(80))?;

    for (i, finding) in findings.iter().enumerate() {
        writeln!(writer, "\n[{}] {}", i + 1, finding.title())?;
        writeln!(writer, "{}", "-".repeat(40))?;
        writeln!(writer, "Severity: {:?}", finding.severity())?;
        writeln!(writer, "Target:   {}", finding.target())?;
        writeln!(writer, "Type:     {:?}", finding.kind())?;

        if !finding.detail().is_empty() {
            writeln!(writer, "\nDetails:\n{}", finding.detail())?;
        }

        if let Some(remediation) = finding.remediation() {
            writeln!(writer, "\nRemediation:\n{remediation}")?;
        }

        if !finding.tags().is_empty() {
            writeln!(writer, "\nTags: {}", finding.tags().join(", "))?;
        }

        if !finding.cwe_ids().is_empty() {
            writeln!(writer, "CWE: {}", finding.cwe_ids().join(", "))?;
        }

        if i < findings.len() - 1 {
            writeln!(writer, "\n{}", "-".repeat(80))?;
        }
    }

    writeln!(writer, "\n{}", "=".repeat(80))?;
    Ok(())
}

/// Output findings as pretty-printed JSON.
pub fn output_json(findings: &[Finding], writer: &mut dyn std::io::Write) -> Result<()> {
    let json =
        serde_json::to_string_pretty(findings).context("Failed to serialize findings to JSON")?;
    writeln!(writer, "{json}")?;
    Ok(())
}

/// Output findings as one JSON object per line (JSONL).
pub fn output_jsonl(findings: &[Finding], writer: &mut dyn std::io::Write) -> Result<()> {
    for finding in findings {
        let json = serde_json::to_string(finding).context("Failed to serialize finding to JSON")?;
        writeln!(writer, "{json}")?;
    }
    Ok(())
}