use anyhow::{Context, Result};
use clap::{Parser, ValueEnum};
use secfinding::Finding;
use tracing::{info, warn};
use crate::scanner::{ScanConfig, ScannerBuilder};
#[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 {
#[arg(value_name = "URL", help = "Target GraphQL endpoint URL")]
pub target: Option<String>,
#[arg(long, help = "List detection modules and exit")]
pub list_modules: bool,
#[arg(
short,
long,
value_enum,
default_value = "human",
help = "Output format for findings"
)]
pub output: OutputFormat,
#[arg(
short,
long,
default_value = "300",
help = "Maximum time for the entire scan (seconds)"
)]
pub timeout: u64,
#[arg(
long,
default_value = "60",
help = "Maximum time for any single test module (seconds)"
)]
pub module_timeout: u64,
#[arg(
short,
long,
default_value = "5",
help = "Maximum number of concurrent test modules"
)]
pub concurrency: usize,
#[arg(long, default_value = "10", help = "HTTP request timeout (seconds)")]
pub http_timeout: u64,
#[arg(long, help = "Disable TLS certificate verification (insecure)")]
pub insecure: bool,
#[arg(
short = 'H',
long,
help = "Add custom HTTP header (format: 'Key: Value')"
)]
pub header: Vec<String>,
#[arg(short, long, help = "Proxy URL (e.g., http://127.0.0.1:8080)")]
pub proxy: Option<String>,
#[arg(short, long, help = "Enable verbose logging")]
pub verbose: bool,
#[arg(long, help = "Enable debug logging")]
pub debug: bool,
#[arg(
long,
value_delimiter = ',',
help = "Comma-separated module IDs to run (e.g. GQL-001,GQL-006)"
)]
pub modules: Option<Vec<String>>,
#[arg(long, help = "Skip schema discovery via introspection")]
pub skip_schema: bool,
}
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum OutputFormat {
Human,
Json,
Jsonl,
Sarif,
}
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}"
);
}
}
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"
);
}
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");
}
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(())
}
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]");
}
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);
let http_config = build_http_config(cli)?;
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,
};
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)
}
pub fn build_http_config(cli: &Cli) -> Result<scanclient::HttpConfig> {
use scanclient::HttpConfig;
let mut custom_headers = std::collections::HashMap::new();
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)
}
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(())
}
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),
}
}
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(())
}
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(())
}
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(())
}
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(())
}