use anyhow::Result;
use scanclient::ScanClient;
use secfinding::{Finding, Severity};
use tracing::debug;
use crate::baseline::EndpointBaseline;
use crate::context::ScanContext;
use crate::schema::SchemaGraph;
pub const SENSITIVE_QUERIES: &[&str] = &[
"admin", "users", "allUsers", "secrets", "payments", "internal", "system",
];
pub const SENSITIVE_MUTATIONS: &[&str] = &[
"deleteUser",
"updateUser",
"createAdmin",
"deleteAll",
"resetPassword",
"changeRole",
];
pub const BYPASS_TOKENS: &[&str] = &[
"null",
"",
"undefined",
"None",
"Bearer null",
"Bearer ",
"Bearer undefined",
"eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlRlc3QifQ.",
];
pub async fn test_with_context(client: &ScanClient, ctx: &ScanContext) -> Result<Vec<Finding>> {
test_inner(client, ctx.url(), ctx.schema.as_ref(), &ctx.baseline).await
}
#[allow(clippy::too_many_lines)]
pub async fn test(client: &ScanClient, url: &str) -> Result<Vec<Finding>> {
test_inner(client, url, None, &EndpointBaseline::default()).await
}
#[allow(clippy::too_many_lines)]
async fn test_inner(
client: &ScanClient,
url: &str,
schema: Option<&SchemaGraph>,
baseline: &EndpointBaseline,
) -> Result<Vec<Finding>> {
let mut findings = Vec::new();
debug!("Testing authentication bypass on {}", url);
let mut query_targets: Vec<String> = schema
.map(|s| {
s.query_fields
.iter()
.filter(|f| {
crate::schema::is_sensitive_field_name(&f.name) || f.marked_requires_auth
})
.map(|f| f.name.clone())
.collect::<Vec<_>>()
})
.unwrap_or_default();
if query_targets.is_empty() {
query_targets = SENSITIVE_QUERIES.iter().map(|s| (*s).to_string()).collect();
}
let mut mutation_targets: Vec<String> = schema
.map(|s| {
s.mutation_fields
.iter()
.filter(|f| {
crate::schema::is_sensitive_field_name(&f.name) || f.marked_requires_auth
})
.map(|f| f.name.clone())
.collect::<Vec<_>>()
})
.unwrap_or_default();
if mutation_targets.is_empty() {
mutation_targets = SENSITIVE_MUTATIONS
.iter()
.map(|s| (*s).to_string())
.collect();
}
for query_name in &query_targets {
match test_unauthenticated_query(client, url, query_name, baseline).await? {
AuthTestResult::Accessible(response) => {
findings.push(create_finding(
url,
&format!("Unauthenticated Access to Sensitive Query: {query_name}"),
&format!(
"The sensitive query '{query_name}' returned data without any authentication token. \
This may allow unauthorized access to privileged information."
),
Severity::High,
&format!(
"Require authentication for all '{query_name}' queries. Implement field-level authorization."
),
Some(&response),
)?);
break; }
AuthTestResult::Protected => {}
AuthTestResult::Error(e) => {
debug!("Auth test error for query '{}': {}", query_name, e);
}
}
}
for mutation_name in &mutation_targets {
match test_unauthenticated_mutation_safe(client, url, mutation_name, baseline).await? {
AuthTestResult::Accessible(response) => {
findings.push(create_finding(
url,
&format!(
"Unauthenticated Access to Sensitive Mutation: {mutation_name}"
),
&format!(
"The sensitive mutation '{mutation_name}' was accepted without authentication. \
This may allow unauthorized state changes."
),
Severity::Critical,
&format!(
"Require authentication for all '{mutation_name}' mutations. Validate permissions before execution."
),
Some(&response),
)?);
break;
}
AuthTestResult::Protected => {}
AuthTestResult::Error(e) => {
debug!("Auth test error for mutation '{}': {}", mutation_name, e);
}
}
}
let is_public = baseline.appears_public
|| matches!(
test_baseline_public(client, url).await?,
AuthTestResult::Accessible(_)
);
if is_public {
debug!("Endpoint appears to be public; skipping token bypass tests");
} else {
for token in BYPASS_TOKENS {
match test_token_bypass(client, url, token).await? {
AuthTestResult::Accessible(response) => {
findings.push(create_finding(
url,
"GraphQL JWT/Token Bypass Possible",
&{
let safe_token = if token.len() > 20 {
format!("{}...[truncated]", &token[..20])
} else if token.is_empty() {
"(empty)".to_string()
} else {
(*token).to_string()
};
format!(
"The GraphQL endpoint accepted a malformed/bypass authentication token: '{safe_token}'. \
This indicates weak token validation."
)
},
Severity::Critical,
"Properly validate JWT signatures, reject 'none' algorithm, and reject null/empty tokens.",
Some(&response),
)?);
break;
}
AuthTestResult::Protected => {}
AuthTestResult::Error(e) => {
debug!("Token bypass test error: {}", e);
}
}
}
}
match test_introspection_auth_leak(client, url).await? {
AuthTestResult::Accessible(response) => {
findings.push(create_finding(
url,
"GraphQL Introspection Leaks Authentication Requirements",
"The GraphQL schema introspection reveals fields marked as requiring authentication. \
While this is common, it aids attackers in identifying privileged operations.",
Severity::Low,
"Consider removing auth-related metadata from public introspection, or disable introspection in production.",
Some(&response),
)?);
}
AuthTestResult::Protected | AuthTestResult::Error(_) => {}
}
debug!(
"Authentication bypass test complete: {} findings",
findings.len()
);
Ok(findings)
}
mod probes;
use probes::test_baseline_public;
pub use probes::{
create_finding, test_introspection_auth_leak, test_token_bypass,
test_unauthenticated_mutation_safe, test_unauthenticated_query, AuthTestResult,
};