use std::collections::HashSet;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use hickory_resolver::TokioResolver;
use scanclient::{HttpConfig, ScanClient};
use secfinding::Finding;
use tokio::sync::Semaphore;
use tokio::time::timeout;
use tracing::{debug, error, info, warn};
use crate::baseline;
use crate::context::{ModuleRun, ScanContext};
use crate::modules::attack::{default_registry, registry_for_ids, AttackModule};
use crate::schema;
#[derive(Debug, Clone)]
pub struct ScanConfig {
pub global_timeout_secs: u64,
pub module_timeout_secs: u64,
pub max_concurrency: usize,
pub http_config: HttpConfig,
pub skip_schema_discovery: bool,
}
impl Default for ScanConfig {
fn default() -> Self {
Self {
global_timeout_secs: 300,
module_timeout_secs: 60,
max_concurrency: 5,
http_config: HttpConfig::default(),
skip_schema_discovery: false,
}
}
}
impl ScanConfig {
pub fn validate(&self) -> Result<()> {
if self.max_concurrency == 0 {
anyhow::bail!("max_concurrency must be greater than 0. Fix: set max_concurrency between 1 and 256");
}
if self.max_concurrency > 256 {
anyhow::bail!(
"max_concurrency must be at most 256. Fix: set max_concurrency between 1 and 256"
);
}
if self.global_timeout_secs == 0 {
anyhow::bail!("global_timeout_secs must be greater than 0. Fix: set global_timeout_secs to a positive number of seconds");
}
Ok(())
}
}
pub struct Scanner {
client: ScanClient,
target: String,
config: ScanConfig,
modules: Vec<Arc<dyn AttackModule>>,
}
impl Scanner {
pub fn all_module_ids() -> &'static [&'static str] {
&[
"GQL-001", "GQL-002", "GQL-003", "GQL-004", "GQL-005", "GQL-006", "GQL-007", "GQL-008",
"GQL-009", "GQL-010", "GQL-011", "GQL-012", "GQL-013", "GQL-014",
]
}
pub fn module_catalog() -> &'static [(&'static str, &'static str)] {
&[
("GQL-001", "Introspection enabled"),
("GQL-002", "Query depth DoS"),
("GQL-003", "Batching abuse"),
("GQL-004", "Field suggestion enumeration"),
("GQL-005", "Directive abuse"),
("GQL-006", "GraphQL injection"),
("GQL-007", "CSRF"),
("GQL-008", "Subscription abuse"),
("GQL-009", "Information disclosure"),
("GQL-010", "Authentication bypass"),
("GQL-011", "Alias abuse"),
("GQL-012", "Schema permission audit"),
("GQL-013", "IDOR / BOLA probe (schema-aware)"),
("GQL-014", "Rate-limit burst probe"),
]
}
pub fn new(target: impl Into<String>) -> Result<Self> {
Self::with_config(target, ScanConfig::default())
}
pub fn with_config(target: impl Into<String>, config: ScanConfig) -> Result<Self> {
config.validate()?;
let target = target.into();
let resolver = Arc::new(TokioResolver::builder_tokio()?.build());
let client = ScanClient::new(config.http_config.clone(), resolver)?;
Ok(Self {
client,
target,
config,
modules: default_registry(),
})
}
pub async fn scan(&self) -> Result<Vec<Finding>> {
info!("Starting GraphQL security scan for {}", self.target);
let setup_timeout = Duration::from_secs(self.config.module_timeout_secs)
.min(Duration::from_secs(self.config.global_timeout_secs));
let (baseline, schema) = if self.config.skip_schema_discovery {
let b =
match timeout(setup_timeout, baseline::capture(&self.client, &self.target)).await {
Ok(Ok(b)) => b,
Ok(Err(e)) => {
warn!("Baseline capture failed: {}", e);
baseline::EndpointBaseline::default()
}
Err(_) => {
warn!(
"Baseline capture timed out after {}s",
setup_timeout.as_secs()
);
baseline::EndpointBaseline::default()
}
};
(b, None)
} else {
let b = timeout(setup_timeout, baseline::capture(&self.client, &self.target));
let s = timeout(setup_timeout, schema::discover(&self.client, &self.target));
let (baseline_result, schema_result) = tokio::join!(b, s);
let baseline = match baseline_result {
Ok(Ok(b)) => b,
Ok(Err(e)) => {
warn!("Baseline capture failed: {}", e);
baseline::EndpointBaseline::default()
}
Err(_) => {
warn!(
"Baseline capture timed out after {}s",
setup_timeout.as_secs()
);
baseline::EndpointBaseline::default()
}
};
let schema = match schema_result {
Ok(Ok(s)) => s,
Ok(Err(e)) => {
warn!("Schema discovery failed: {}", e);
None
}
Err(_) => {
warn!(
"Schema discovery timed out after {}s",
setup_timeout.as_secs()
);
None
}
};
(baseline, schema)
};
let ctx = ScanContext::new(&self.target, schema, baseline);
let semaphore = Arc::new(Semaphore::new(self.config.max_concurrency));
let mut handles = Vec::new();
for module in &self.modules {
let permit = semaphore.clone().acquire_owned().await?;
let module_id = module.id().to_string();
let module_name = module.name().to_string();
let client = self.client.clone();
let ctx = ctx.clone();
let module = Arc::clone(module);
let timeout_duration = if self.config.module_timeout_secs == 0 {
Duration::from_secs(self.config.global_timeout_secs)
} else {
Duration::from_secs(self.config.module_timeout_secs)
};
let handle = tokio::spawn(async move {
let _permit = permit;
debug!("Running module {}: {}", module_id, module_name);
let run = ModuleRun {
client: &client,
ctx: &ctx,
};
let result = timeout(timeout_duration, module.detect(&run)).await;
match result {
Ok(Ok(findings)) => {
debug!(
"Module {} completed with {} findings",
module_id,
findings.len()
);
findings
}
Ok(Err(e)) => {
error!("Module {} failed: {}", module_id, e);
Vec::new()
}
Err(_) => {
error!(
"Module {} timed out after {}s",
module_id,
timeout_duration.as_secs()
);
Vec::new()
}
}
});
handles.push(handle);
}
let global_timeout = Duration::from_secs(self.config.global_timeout_secs)
.min(Duration::from_secs(u64::from(u32::MAX)));
let deadline = tokio::time::Instant::now() + global_timeout;
let mut all_findings = Vec::new();
let mut timed_out = false;
while !handles.is_empty() {
let mut i = 0;
while i < handles.len() {
if handles[i].is_finished() {
let handle = handles.remove(i);
match handle.await {
Ok(findings) => all_findings.extend(findings),
Err(e) => error!("Task join error: {}", e),
}
} else {
i += 1;
}
}
if tokio::time::Instant::now() >= deadline {
for h in handles {
h.abort();
}
timed_out = true;
break;
}
if !handles.is_empty() {
tokio::time::sleep(Duration::from_millis(50)).await;
}
}
if timed_out {
warn!(
"Global scan timeout exceeded ({}s); returning partial findings",
self.config.global_timeout_secs
);
}
let deduped = Self::deduplicate_findings(all_findings);
info!("Scan complete: {} unique findings", deduped.len());
Ok(deduped)
}
pub fn deduplicate_findings(findings: Vec<Finding>) -> Vec<Finding> {
let mut seen = HashSet::with_capacity(findings.len());
let mut unique = Vec::with_capacity(findings.len());
for finding in findings {
let key = (finding.title().to_string(), finding.target().to_string());
if seen.insert(key) {
unique.push(finding);
}
}
unique.sort_by_key(|a| std::cmp::Reverse(a.severity()));
unique
}
pub fn target(&self) -> &str {
&self.target
}
pub fn config(&self) -> &ScanConfig {
&self.config
}
pub fn module_count(&self) -> usize {
self.modules.len()
}
pub fn module_ids(&self) -> Vec<&'static str> {
self.modules.iter().map(|m| m.id()).collect()
}
}
#[derive(Default)]
pub struct ScannerBuilder {
target: Option<String>,
config: ScanConfig,
modules: Option<Vec<Arc<dyn AttackModule>>>,
}
impl std::fmt::Debug for ScannerBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ScannerBuilder")
.field("target", &self.target)
.field("config", &self.config)
.field("modules", &self.modules.as_ref().map(|m| m.len()))
.finish()
}
}
impl ScannerBuilder {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn target(mut self, target: impl Into<String>) -> Self {
self.target = Some(target.into());
self
}
#[must_use]
pub fn global_timeout(mut self, secs: u64) -> Self {
self.config.global_timeout_secs = secs;
self
}
#[must_use]
pub fn module_timeout(mut self, secs: u64) -> Self {
self.config.module_timeout_secs = secs;
self
}
#[must_use]
pub fn max_concurrency(mut self, max: usize) -> Self {
self.config.max_concurrency = max;
self
}
#[must_use]
pub fn http_config(mut self, config: HttpConfig) -> Self {
self.config.http_config = config;
self
}
#[must_use]
pub fn skip_schema_discovery(mut self, skip: bool) -> Self {
self.config.skip_schema_discovery = skip;
self
}
#[must_use]
pub fn modules(mut self, ids: &[&str]) -> Self {
self.modules = Some(registry_for_ids(ids));
self
}
pub fn build(self) -> Result<Scanner> {
self.config.validate()?;
let target = self
.target
.ok_or_else(|| anyhow::anyhow!("target is required"))?;
let mut scanner = Scanner::with_config(target, self.config)?;
if let Some(modules) = self.modules {
scanner.modules = modules;
}
Ok(scanner)
}
}