use std::collections::HashMap;
use anyhow::Result;
use scanclient::ScanClient;
use serde_json::Value;
use tracing::debug;
use crate::modules::introspection::{
send_introspection_query, IntrospectionResult, SIMPLE_INTROSPECTION_QUERY,
};
#[derive(Debug, Clone, Default)]
pub struct SchemaGraph {
pub query_type: Option<String>,
pub mutation_type: Option<String>,
pub query_fields: Vec<SchemaField>,
pub mutation_fields: Vec<SchemaField>,
pub nested_object_fields: Vec<(String, String)>,
pub injectable_args: Vec<InjectableArg>,
pub id_lookup_args: Vec<IdLookupArg>,
}
#[derive(Debug, Clone)]
pub struct SchemaField {
pub name: String,
pub parent_type: String,
pub marked_requires_auth: bool,
}
#[derive(Debug, Clone)]
pub struct IdLookupArg {
pub field: String,
pub arg: String,
pub is_mutation: bool,
pub type_name: String,
}
#[derive(Debug, Clone)]
pub struct InjectableArg {
pub field: String,
pub arg: String,
pub is_mutation: bool,
pub type_name: String,
}
const SCHEMA_DISCOVERY_QUERY: &str = r"
query GqlprobeSchemaDiscovery {
__schema {
queryType { name }
mutationType { name }
types {
kind
name
fields {
name
args {
name
type {
kind
name
ofType { kind name ofType { kind name } }
}
}
}
}
}
}
";
pub async fn discover(client: &ScanClient, url: &str) -> Result<Option<SchemaGraph>> {
debug!("Discovering GraphQL schema for {}", url);
let result = send_introspection_query(client, url, SCHEMA_DISCOVERY_QUERY, None).await?;
match result {
IntrospectionResult::Enabled(body) => Ok(Some(parse_schema_response(&body)?)),
IntrospectionResult::Disabled | IntrospectionResult::Error(_) => {
let fallback =
send_introspection_query(client, url, SIMPLE_INTROSPECTION_QUERY, None).await?;
match fallback {
IntrospectionResult::Enabled(body) => {
if let Ok(json) = serde_json::from_str::<Value>(&body) {
let query_type = json
.pointer("/data/__schema/queryType/name")
.and_then(|v| v.as_str())
.map(str::to_string);
return Ok(Some(SchemaGraph {
query_type,
..SchemaGraph::default()
}));
}
Ok(None)
}
_ => Ok(None),
}
}
}
}
pub fn parse_schema_response(body: &str) -> Result<SchemaGraph> {
let json: Value = serde_json::from_str(body)?;
let schema = json
.pointer("/data/__schema")
.ok_or_else(|| anyhow::anyhow!("missing __schema in introspection response"))?;
let query_type = schema
.pointer("/queryType/name")
.and_then(|v| v.as_str())
.map(str::to_string);
let mutation_type = schema
.pointer("/mutationType/name")
.and_then(|v| v.as_str())
.map(str::to_string);
let types = schema
.get("types")
.and_then(|t| t.as_array())
.cloned()
.unwrap_or_default();
let type_fields: HashMap<String, Vec<(String, Vec<Value>, bool)>> = types
.iter()
.filter_map(|t| {
let name = t.get("name")?.as_str()?;
let fields = t.get("fields")?.as_array()?;
let mut parsed = Vec::new();
for f in fields {
let fname = f.get("name")?.as_str()?;
let args = f
.get("args")
.and_then(|a| a.as_array())
.cloned()
.unwrap_or_default();
let marked = field_marked_requires_auth(f);
parsed.push((fname.to_string(), args, marked));
}
Some((name.to_string(), parsed))
})
.collect();
let mut graph = SchemaGraph {
query_type: query_type.clone(),
mutation_type: mutation_type.clone(),
..SchemaGraph::default()
};
if let Some(ref qt) = query_type {
if let Some(fields) = type_fields.get(qt) {
for (name, args, marked) in fields {
graph.query_fields.push(SchemaField {
name: name.clone(),
parent_type: qt.clone(),
marked_requires_auth: *marked,
});
collect_injectable(&mut graph, &name, args, false);
}
}
}
if let Some(ref mt) = mutation_type {
if let Some(fields) = type_fields.get(mt) {
for (name, args, marked) in fields {
graph.mutation_fields.push(SchemaField {
name: name.clone(),
parent_type: mt.clone(),
marked_requires_auth: *marked,
});
collect_injectable(&mut graph, &name, args, true);
}
}
}
for (type_name, fields) in &type_fields {
if type_name.starts_with("__") {
continue;
}
for (field_name, _, _) in fields {
graph
.nested_object_fields
.push((type_name.clone(), field_name.clone()));
if graph.nested_object_fields.len() >= 32 {
break;
}
}
if graph.nested_object_fields.len() >= 32 {
break;
}
}
Ok(graph)
}
fn collect_injectable(graph: &mut SchemaGraph, field: &str, args: &[Value], is_mutation: bool) {
for arg in args {
let Some(arg_name) = arg.get("name").and_then(|n| n.as_str()) else {
continue;
};
let type_name = resolve_type_name(arg.get("type"));
if is_string_like(&type_name) {
graph.injectable_args.push(InjectableArg {
field: field.to_string(),
arg: arg_name.to_string(),
is_mutation,
type_name: type_name.clone(),
});
}
if is_id_lookup(&type_name, arg_name) {
graph.id_lookup_args.push(IdLookupArg {
field: field.to_string(),
arg: arg_name.to_string(),
is_mutation,
type_name,
});
}
}
}
fn is_id_lookup(type_name: &str, arg_name: &str) -> bool {
let tn = type_name.to_uppercase();
let scalar_ok = matches!(tn.as_str(), "ID" | "INT" | "INTEGER" | "UUID");
if !scalar_ok {
return false;
}
let a = arg_name.to_lowercase();
a == "id"
|| a.ends_with("id")
|| a.contains("uuid")
|| a == "uid"
|| a == "accountid"
|| a == "userid"
}
fn resolve_type_name(type_node: Option<&Value>) -> String {
let Some(node) = type_node else {
return "Unknown".to_string();
};
if let Some(name) = node.get("name").and_then(|n| n.as_str()) {
return name.to_string();
}
if let Some(inner) = node.get("ofType") {
return resolve_type_name(Some(inner));
}
"Unknown".to_string()
}
fn is_string_like(type_name: &str) -> bool {
matches!(
type_name,
"String" | "ID" | "UUID" | "Email" | "Url" | "JSON" | "JSONObject"
)
}
fn field_marked_requires_auth(field: &Value) -> bool {
let text = field.to_string().to_lowercase();
text.contains("requiresauth")
|| text.contains("isauthenticated")
|| text.contains("@auth")
|| text.contains("authenticated")
|| text.contains("requires_auth")
|| text.contains("loginrequired")
}
pub fn is_sensitive_field_name(name: &str) -> bool {
let n = name.to_lowercase();
n.contains("admin")
|| n.contains("secret")
|| n.contains("password")
|| n.contains("token")
|| n.contains("payment")
|| n.contains("internal")
|| n == "users"
|| n == "user"
|| n.contains("private")
}
pub fn selection_for_field(field: &SchemaField) -> &'static str {
if field.name.ends_with('s') {
"{ id }"
} else {
"{ id }"
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_minimal_schema_extracts_query_fields() {
let body = r#"{
"data": {
"__schema": {
"queryType": { "name": "Query" },
"mutationType": { "name": "Mutation" },
"types": [
{
"kind": "OBJECT",
"name": "Query",
"fields": [
{
"name": "users",
"args": [{ "name": "filter", "type": { "kind": "SCALAR", "name": "String" } }]
}
]
},
{
"kind": "OBJECT",
"name": "Mutation",
"fields": [
{ "name": "deleteUser", "args": [{ "name": "id", "type": { "kind": "SCALAR", "name": "ID" } }] }
]
}
]
}
}
}"#;
let graph = parse_schema_response(body).unwrap();
assert_eq!(graph.query_type.as_deref(), Some("Query"));
assert_eq!(graph.query_fields.len(), 1);
assert_eq!(graph.mutation_fields.len(), 1);
assert!(!graph.injectable_args.is_empty());
assert!(!graph.id_lookup_args.is_empty());
}
}