use anyhow::Result;
use scanclient::reqwest::header::CONTENT_TYPE;
use scanclient::ScanClient;
use secfinding::{Evidence, Finding, FindingKind, Severity};
use serde_json::{json, Value};
use tracing::debug;
use crate::baseline::{has_auth_errors, has_meaningful_field_data};
use crate::context::ScanContext;
use crate::schema::{is_sensitive_field_name, SchemaField, SchemaGraph};
pub async fn test_with_context(client: &ScanClient, ctx: &ScanContext) -> Result<Vec<Finding>> {
let Some(ref schema) = ctx.schema else {
debug!("Skipping permission audit: no schema available");
return Ok(Vec::new());
};
test(client, ctx.url(), schema, &ctx.baseline).await
}
pub async fn test(
client: &ScanClient,
url: &str,
schema: &SchemaGraph,
baseline: &crate::baseline::EndpointBaseline,
) -> Result<Vec<Finding>> {
let mut findings = Vec::new();
debug!("Running schema permission audit on {}", url);
for field in schema
.query_fields
.iter()
.chain(schema.mutation_fields.iter())
{
if field.marked_requires_auth {
if let Some(finding) = probe_auth_marked_field(client, url, field, baseline).await? {
findings.push(finding);
break;
}
} else if is_sensitive_field_name(&field.name) {
if let Some(finding) = probe_sensitive_unmarked(client, url, field, baseline).await? {
findings.push(finding);
}
}
}
if findings.is_empty() && !schema.query_fields.is_empty() {
debug!(
"Permission audit complete: {} query fields, {} mutation fields examined",
schema.query_fields.len(),
schema.mutation_fields.len()
);
}
Ok(findings)
}
async fn probe_auth_marked_field(
client: &ScanClient,
url: &str,
field: &SchemaField,
baseline: &crate::baseline::EndpointBaseline,
) -> Result<Option<Finding>> {
let op = if field.parent_type.to_lowercase().contains("mutation") {
format!("mutation {{ {} {{ __typename }} }}", field.name)
} else {
format!("query {{ {} {{ __typename }} }}", field.name)
};
let body = json!({ "query": op });
let request = client
.request(scanclient::reqwest::Method::POST, url)
.header(CONTENT_TYPE, "application/json")
.body(body.to_string());
let Ok(resp) = client.execute(request).await else {
return Ok(None);
};
let text = resp.body_text().unwrap_or("");
let Ok(json) = serde_json::from_str::<Value>(text) else {
return Ok(None);
};
if resp.status().is_success()
&& has_meaningful_field_data(&json, &field.name)
&& !has_auth_errors(&json)
&& !baseline.appears_public
{
return Ok(Some(create_finding(
url,
&format!(
"Auth-Required Field Accessible Without Credentials: {}",
field.name
),
&format!(
"Introspection marks '{}' on type '{}' as requiring authentication, \
but the field returned data without an Authorization header.",
field.name, field.parent_type
),
Severity::Critical,
"Enforce authentication consistently with schema directives and resolver guards.",
Some(text),
)?));
}
Ok(None)
}
async fn probe_sensitive_unmarked(
client: &ScanClient,
url: &str,
field: &SchemaField,
baseline: &crate::baseline::EndpointBaseline,
) -> Result<Option<Finding>> {
let query = format!("query {{ {} {{ __typename }} }}", field.name);
let body = json!({ "query": query });
let request = client
.request(scanclient::reqwest::Method::POST, url)
.header(CONTENT_TYPE, "application/json")
.body(body.to_string());
let Ok(resp) = client.execute(request).await else {
return Ok(None);
};
let text = resp.body_text().unwrap_or("");
let Ok(json) = serde_json::from_str::<Value>(text) else {
return Ok(None);
};
if resp.status().is_success()
&& has_meaningful_field_data(&json, &field.name)
&& !has_auth_errors(&json)
&& !baseline.appears_public
{
return Ok(Some(create_finding(
url,
&format!("Sensitive Field Exposed Without Auth Metadata: {}", field.name),
&format!(
"The sensitive field '{}' is reachable without authentication and has no \
auth-related directive in introspection. Review whether this field should be protected.",
field.name
),
Severity::Medium,
"Add field-level authorization and document auth requirements in the schema.",
Some(text),
)?));
}
Ok(None)
}
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("permissions")
.cwe("CWE-862")
.remediation(remediation);
if let Some(body) = evidence_body {
let excerpt = if body.chars().count() > 1000 {
format!(
"{}...[truncated]",
body.chars().take(1000).collect::<String>()
)
} else {
body.to_string()
};
builder = builder.evidence(Evidence::raw(excerpt));
}
Ok(builder.build()?)
}