use anyhow::Result;
use scanclient::reqwest::header::CONTENT_TYPE;
use scanclient::ScanClient;
use secfinding::{Evidence, Finding, FindingKind, Severity};
use serde_json::json;
use tracing::debug;
use crate::context::ScanContext;
use crate::schema::SchemaGraph;
const TEST_ALIAS_COUNTS: [usize; 4] = [25, 50, 100, 200];
const MAX_ACCEPTABLE_ALIASES: usize = 50;
pub fn generate_alias_abuse_query(count: usize, field: &str) -> String {
let mut query = String::with_capacity(count * 24 + 24);
query.push_str("query AliasAbuse{");
for i in 0..count {
query.push_str(&format!(
"a{i}:{field}(id:\"__gqlprobe_alias_{i}\"){{__typename}}"
));
}
query.push('}');
query
}
pub fn generate_alias_abuse_query_legacy(count: usize) -> String {
generate_alias_abuse_query(count, "user")
}
pub async fn test_with_context(client: &ScanClient, ctx: &ScanContext) -> Result<Vec<Finding>> {
test(client, ctx.url(), ctx.schema.as_ref()).await
}
pub async fn test(
client: &ScanClient,
url: &str,
schema: Option<&SchemaGraph>,
) -> Result<Vec<Finding>> {
let field = schema
.and_then(|s| s.query_fields.first())
.map(|f| f.name.as_str())
.unwrap_or("user");
debug!("Testing alias abuse on {} (field={})", url, field);
let mut findings = Vec::new();
let mut max_accepted = 0usize;
for &count in &TEST_ALIAS_COUNTS {
let query = generate_alias_abuse_query(count, field);
let body = json!({ "query": query });
let request = client
.request(scanclient::reqwest::Method::POST, url)
.header(CONTENT_TYPE, "application/json")
.body(body.to_string());
match client.execute(request).await {
Ok(resp) if resp.status().is_success() => {
let text = resp.body_text().unwrap_or("");
if text.contains("\"data\"") && !text.to_lowercase().contains("too many aliases") {
max_accepted = count;
}
}
_ => break,
}
}
if max_accepted > MAX_ACCEPTABLE_ALIASES {
findings.push(create_finding(
url,
"GraphQL Alias Abuse Allowed",
&format!(
"The endpoint processed a query with {max_accepted} field aliases without rejection. \
Alias amplification can bypass rate limits and cause resolver exhaustion."
),
Severity::High,
"Enforce alias limits and query complexity analysis (max aliases, cost analysis).",
None,
)?);
}
Ok(findings)
}
fn create_finding(
url: &str,
title: &str,
detail: &str,
severity: Severity,
remediation: &str,
evidence_body: Option<&str>,
) -> Result<Finding> {
let mut builder = Finding::builder("gqlprobe", url, severity)
.title(title)
.detail(detail)
.kind(FindingKind::Misconfiguration)
.tag("graphql")
.tag("alias-abuse")
.cwe("CWE-400")
.remediation(remediation);
if let Some(body) = evidence_body {
let excerpt = if body.len() > 1000 {
format!("{}...[truncated]", &body[..1000])
} else {
body.to_string()
};
builder = builder.evidence(Evidence::raw(excerpt));
}
Ok(builder.build()?)
}