Last updated: May 1, 2026
GraphQL is a query language and runtime that lets clients fetch exactly the data they need from a single endpoint. Powerful — and the things that make it powerful (introspection, query flexibility, batching, nested resolvers) also create distinct security challenges that REST testers miss. This module covers GraphQL-specific attacks, defenses, and tooling.
GraphQL basics
- Single endpoint (typically
/graphql) - POST request body contains the query in GraphQL query language
- Server response contains exactly the requested fields, no more
- Schema defines available types, queries, mutations, subscriptions
- Resolvers fetch data for each field
Introspection — gift to attackers
GraphQL servers can expose their full schema via introspection queries:
# Standard introspection query
query IntrospectionQuery {
__schema {
types { name fields { name type { name } } }
queryType { name }
mutationType { name }
}
}
# In production: introspection should be DISABLED.
# In dev/staging: enabled is fine for tooling like GraphiQL.
If introspection is on in production, an attacker has your full API documentation in seconds. Tools like GraphQL Voyager visualize the schema. Test cases for hidden mutations like internalAdminPasswordReset become trivial.
InQL / GraphQL-Voyager / Altair
InQL is a Burp extension that auto-introspects and generates testing UI. Altair is a standalone GraphQL client. Both are essential for GraphQL pentesting.
Query depth and complexity attacks
GraphQL’s killer feature — nested queries — is also a DoS vector:
# Cyclic query — friends of friends of friends...
query {
user(id: 1) {
friends {
friends {
friends {
friends {
friends { name }
}
}
}
}
}
}
# Each level multiplies database queries. 5 levels deep with 100 friends each
# is a billion-row scan. Server burns CPU; legitimate users impacted.
Defenses
- Query depth limiting — reject queries beyond N levels (typically 5-10)
- Query complexity scoring — assign cost to each field; reject if sum exceeds budget
- Pagination enforced on list fields with low max page size
- Persisted queries — accept only queries from a pre-approved allowlist
- Timeout on resolver execution
Authorization in GraphQL
Authorization gets harder than REST because:
- One query touches multiple resolvers; each resolver must independently auth-check
- Field-level authorization (some fields visible to admins, some to all) requires per-field logic
- Object-level (BOLA) tests must consider nested traversal: query traverses from User → Project → Tasks; auth on User isn’t enough
Common bug pattern: authorization on the top-level query field, none on nested resolvers. Attacker queries an authorized parent, traverses into unauthorized children.
# Buggy pattern: auth check on user(id), none on user.allCustomerData
query {
user(id: 1) { # auth checked: am I user 1 or admin?
allCustomerData { # NO auth check on this resolver
email
ssn
}
}
}
Batching and aliasing attacks
GraphQL allows multiple queries in one request via aliases:
# Brute force a 4-digit OTP in one HTTP request
query {
a: verify(otp: "0000") { ok }
b: verify(otp: "0001") { ok }
c: verify(otp: "0002") { ok }
# ... 9997 more aliases ...
zzzz: verify(otp: "9999") { ok }
}
# 10000 brute-force attempts in one request.
# Per-request rate limit is useless. Need per-resolver limit.
Defense: rate-limit at the resolver level, not the request level. Each invocation of verify counts against the budget regardless of how many fit in one HTTP request.
Mutation safety
Mutations modify data. Specific things to test:
- Privileged mutations (admin actions) protected by role check, not just authentication
- Mass-assignment risks — mutation accepting an entire input object may accept fields the form didn’t show
- Idempotency keys for sensitive operations (payments, signups)
- Atomic transactions where multiple resolvers must succeed together
Persisted queries — defense in depth
Persisted queries shift from “client sends query” to “client sends query ID; server has the canonical query.” Effects:
- Eliminates ad-hoc queries; production allowlists what’s possible
- Reduces network payload
- Eliminates introspection abuse (introspection’s not in the allowlist)
- Tooling: Apollo’s Persisted Queries, Relay’s persisted query manifests
Cost: development workflow changes. Many teams use persisted queries in production but allow ad-hoc queries in dev. This is fine if dev/staging credentials don’t grant prod access.
Subscriptions and WebSockets
GraphQL subscriptions use WebSockets for realtime. Auth must:
- Validate token on connection establishment
- Re-validate on token refresh
- Enforce per-user/tenant subscription scope
- Limit number of concurrent subscriptions per client
Common bug: connection authenticates but subscription resolver doesn’t re-check; attacker subscribes to other tenants’ data.
Error message leakage
GraphQL servers in dev mode return verbose errors with stack traces. In production:
- Disable stack traces in error responses
- Return generic errors for auth failures (don’t differentiate “not found” from “not authorized” — combine into 404-equivalent)
- Log detailed errors server-side for debugging; client gets sanitized version
Testing checklist for a GraphQL endpoint
- Is introspection enabled in production? (Should be disabled)
- What’s the query depth limit? Test with 100-deep query — is it rejected?
- Query complexity limit? Test with high-cost query
- Aliasing brute force — try a high-rep aliased query against an OTP/password endpoint
- Authorization on every nested resolver, not just top-level
- Mass assignment on mutations
- Subscription auth re-checked per message
- Error responses sanitized (no stack traces, no internal paths)
- Persisted queries used in production?
- Rate limits at resolver level, not just request level
GraphQL-aware DAST tools
- InQL (Burp) — schema introspection + query generation + tests
- Clairvoyance — schema discovery against introspection-disabled endpoints
- graphql-cop — automated audit checks for common misconfigurations
- graphql-armor — server-side library hardening (depth limit, alias limit, etc.); good defensive tool
What the next modules cover
Module 4 covers rate limiting and abuse — the operational layer of API defense. Module 5 covers API gateways and zero-trust patterns at scale.
Module Quiz · 15 questions
Pass with 80%+ to mark this module complete. Unlimited retries. Each question shows an explanation.
Practical depth on what to tune, what to harden, and how this maps to Indian regulatory expectations.
GraphQL performance — query complexity and the DoS reality
A single GraphQL query can request thousands of nested fields, joining many tables. Without limits, one well-crafted query can exhaust the database. Defences:
graphql-cost-analysis for Node, similar libs for Python/Java.GraphQL security checklist
graphql-shield for rule-based authz; graphql-armor for the DoS / introspection / depth defences.Detection and India context
Signals that catch GraphQL attacks:
GraphQL field-level authorisation patterns
GraphQL’s power — letting clients shape the query — is also its security curse: every leaf field is a potential authz check. Naive implementations check authz at the entry resolver and trust that downstream resolvers operate on already-authorised data. That trust breaks the moment a query nests across ownership boundaries. Pattern 1: Resolver-level guards — every resolver function explicitly checks whether the calling user is authorised for the parent context. Express via decorators (TypeGraphQL @Authorized) or middleware (graphql-shield). Pattern 2: Schema directives — @auth(role: ADMIN) baked into the schema; the gateway enforces. Pattern 3: Policy engine — externalise to OPA / Cedar; resolvers call the policy with (subject, action, resource). For complex apps this is cleanest because policies live separately from code.
What to test in pentestprobe each field with cross-tenant queries; nested queries that climb ownership chains; subscription handlers that should re-validate authz on each event.
Schema design for security — minimising attack surface
Defensive schema design reduces the cost of an authz bug.
users(filter: ...); prefer scoped me { friends } patterns.User { friends: [User] } allow infinite depth; depth-limit middleware caps practical impact.@deprecated aggressively to retire risky fields.Federation, batching, and the multi-graph attack surface
GraphQL Federation (Apollo, IntrospectionGateway-style) composes multiple subgraphs into a single client-facing schema. Each subgraph is a separate service with its own resolvers and authz. The gateway plans queries across subgraphs, calling each and stitching results. The attack surface this opens:
Caching responses safely — what to cache and what to never cache
GraphQL caching is harder than REST because every query is potentially different. Strategies:
Performance discipline that strengthens security
A practical performance discipline that applies regardless of the specific vulnerability class is to instrument every endpoint with three SLOs: latency at the 50th, 95th, and 99th percentiles. The 50th percentile reflects typical user experience, the 95th catches tail behaviour visible to a meaningful fraction of users, and the 99th captures the long-tail outliers that often hide bugs (timeouts on a stale dependency, locking contention under load, garbage-collection pauses on a hot endpoint). Every release should compare these percentiles against the previous baseline; regressions of more than ten percent on the 95th percentile are typically worth investigating before shipping. Modern observability stacks make this routine — Datadog APM, New Relic, Honeycomb, Grafana Tempo with OpenTelemetry instrumentation, and on the open-source side Jaeger plus Prometheus plus Grafana — but the discipline matters more than the tool. Indian product teams that have adopted this percentile-driven culture report fewer surprise outages and a smaller incident-response load over time, which compounds into a stronger security posture: the same instrumentation that catches a slow endpoint also catches an exploitation attempt that forces unusual code paths.
Observability that catches attacks alongside outages
Observability for security overlaps with observability for reliability but adds a few specific signals worth instrumenting. First, application-layer authentication and authorisation events should produce structured logs with the user identifier, the action attempted, the source IP, the User-Agent fingerprint, and the outcome. Second, every state-changing API call should log its idempotency key, the request body shape, and the resulting object identifier. Third, every external dependency call should log the destination, the response code, and the latency. Together these three categories produce a clean event stream that a SIEM can correlate to detect both functional regressions and active attacks. The cost is moderate — log storage in Elasticsearch or Splunk runs perhaps thirty to sixty rupees per gigabyte per year at typical Indian-tier prices — and the payoff is dramatic: incidents that previously took days to investigate are typically resolved in hours when the relevant evidence has been pre-indexed. Indian regulators increasingly expect this level of operational logging, particularly RBI under the Cyber Security Framework Annex 1 and SEBI under the CSCRF master circular.
DPDP and sectoral obligations a practitioner cannot ignore
Under India’s Digital Personal Data Protection Act 2023, the operational obligations on any web application that handles personal data extend beyond simple consent collection. Section 8 requires that data fiduciaries implement reasonable security safeguards — interpreted in practice as reflecting a documented information security programme, regular vulnerability assessment, and demonstrable controls aligned to a recognised standard such as ISO 27001 or NIST CSF. Section 9 imposes data principal rights including access, correction, and erasure, which means the application must be architected so that these requests can be fulfilled within the prescribed timeframes (currently expected to be on the order of thirty days). Section 8(6) imposes breach notification: when a personal-data breach occurs, the data fiduciary must notify the Data Protection Board and affected data principals within prescribed timeframes (the draft Rules suggest seventy-two hours for material breaches). For the practitioner this translates into specific engineering tasks: data inventory and lineage tracking, retention controls and automated deletion at end-of-purpose, audit-grade logging of every access to personal data, breach-detection telemetry, and a formal incident-response playbook with regulatory-notification templates. The 2024-2025 inspections by RBI and SEBI of regulated entities have already cited DPDP-overlay obligations, so the alignment is not theoretical; it shapes what auditors expect to see in the next inspection cycle.
A small threat-modelling routine before every release
A short threat-modelling exercise specific to this vulnerability class is worth running before each release. The classic STRIDE framework — Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege — provides a useful checklist when applied to the specific data flow at hand. Begin by drawing the data flow for the feature being changed: external actors at the edge, the trust boundaries they cross, the back-end services involved, the data stores read or written, and the third-party integrations called. For each trust boundary crossing, ask which STRIDE categories apply and what controls mitigate them. The output is a small set of testable assertions: this endpoint must not allow tenant A to read tenant B’s records, this mutation must require step-up authentication, this third-party call must validate the response signature, and so on. Convert each assertion into an automated test or a manual verification step in the release checklist. The discipline pays off in two ways: first, it catches design-level bugs before they reach code review; second, it produces an auditable record of security thinking that regulators value. Indian product teams that have institutionalised this practice report fewer security incidents and shorter mean-time-to-remediate when issues are found, which compounds into better customer trust and lower regulatory friction over time.
Further reading
Additional FAQs
Should I use REST or GraphQL for security-sensitive APIs?
Both can be secured; both have characteristic pitfalls. REST has simpler authz model (one endpoint per resource). GraphQL is more flexible but the resolver-level authz adds complexity. Choose by team familiarity and frontend needs, not by perceived security.
Is introspection always bad?
Useful in dev/staging; risky in production. Best practice: disable in production via env flag; allow in non-prod for tooling.
Custom team training + practitioner advisory
Beyond the free academy — we run private workshops, vCISO advisory, and red-team exercises tailored to your stack. For Indian SMBs scaling past their first hire.