Module 3 · GraphQL Security

Manish Garg
Manish Garg Associate of (ISC)² · RingSafe
Apr 22, 2026
14 min read
Read as

Last updated: May 1, 2026

100% Free

No signup. No paywall. No catch. One of our 10 most-requested practitioner modules — published in full so anyone can learn for free. We earn through consulting, not by gating knowledge.

See all 10 free modules →

Introspection, depth/complexity attacks, aliasing brute force, mutation safety, persisted queries, subscriptions.

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

  1. Is introspection enabled in production? (Should be disabled)
  2. What’s the query depth limit? Test with 100-deep query — is it rejected?
  3. Query complexity limit? Test with high-cost query
  4. Aliasing brute force — try a high-rep aliased query against an OTP/password endpoint
  5. Authorization on every nested resolver, not just top-level
  6. Mass assignment on mutations
  7. Subscription auth re-checked per message
  8. Error responses sanitized (no stack traces, no internal paths)
  9. Persisted queries used in production?
  10. 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.

🧠
Check your understanding

Module Quiz · 15 questions

Pass with 80%+ to mark this module complete. Unlimited retries. Each question shows an explanation.


⚙ Optimisation · Performance · Security — extended

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:

1Query depth limit: reject queries deeper than 7-10 levels.
2Query complexity scoring: every field has a cost; queries above threshold are rejected. graphql-cost-analysis for Node, similar libs for Python/Java.
3Persisted queries: only pre-registered queries by hash are allowed; clients send the hash, not the query text. Eliminates arbitrary-query attacks entirely.
4Pagination required: lists default to first-N; reject unbounded requests.
5Timeout: hard kill at the resolver layer.
6Rate limit per cost: not just per-request — a 100-cost query counts as 100 against quota. For Indian fintech / e-commerce: GraphQL DoS is a documented attack class; rate-limit-by-cost defends against it without breaking legitimate clients.

GraphQL security checklist

1Disable introspection in production — attackers cannot map the schema unless you publish it.
2Disable verbose errors — typed errors leak field types and existence.
3Authorisation on every resolver, not just at the entry — GraphQL fans out, each leaf needs its own check.
4Avoid mass-assignment: input types should not let users set fields they should not.
5CSRF defence if mutations are sent over POST with cookies — same origin / token check.
6Subscription auth: WebSocket auth at handshake, re-validated per subscription.
7Batch queries limit: many GraphQL servers accept arrays of queries; cap the array size.
8Audit log every mutation with user-id + variables. Tooling: graphql-shield for rule-based authz; graphql-armor for the DoS / introspection / depth defences.

Detection and India context

Signals that catch GraphQL attacks:

1Sudden spike in introspection-style queries.
2Queries with depth >10.
3Queries returning unusual byte volumes.
4Repeat-mutation patterns from one user.
5Subscription connections that never disconnect. Logging: log query hash, depth, complexity, byte size, response time per request — gives a behavioural baseline. For Indian apps: GraphQL is now common in fintech and e-commerce mobile back-ends; the regulatory mapping is the same as REST APIs (DPDP for PII, RBI for financial data), but the audit techniques differ. Indian VAPT reports increasingly include GraphQL-specific findings.

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.

1Avoid global root queries like users(filter: ...); prefer scoped me { friends } patterns.
2Make IDs opaque — global Relay-style IDs encode type + ownership; opaque to client; cannot be enumerated by ID-guessing.
3Limit nesting depth at the schema — types like User { friends: [User] } allow infinite depth; depth-limit middleware caps practical impact.
4Field-level deprecations — fields are easy to add, hard to remove; use @deprecated aggressively to retire risky fields.
5Separate public and admin schemas — different gateways, different authn models, different attack surfaces. For Indian fintech: when GraphQL fronts an account aggregator or open-banking integration, schema design directly impacts what consent the user must give; tight schemas align with DPDP’s purpose-limitation principle.

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:

1Cross-subgraph authorisation gaps — subgraph A trusts that subgraph B has authorised the request; both think the other did it.
2Gateway-side query planner exposing introspection of internal subgraphs that would otherwise be private.
3Batch-query attacks — a single client query expanding to N subgraph fetches, multiplied by depth — DoS by amplification.
4Reference-resolver fan-out — one entity reference (id only) triggers a full fetch across subgraphs. Defence patterns: (a) Authentication and authorisation enforced at every subgraph independently — no trust transitivity. (b) Query-cost analysis at the gateway covering the full federated plan, not just per-subgraph. (c) Persisted queries for production clients — only registered query hashes pass; arbitrary queries blocked. (d) Subgraph network isolation — only the gateway can reach subgraphs; never directly internet-exposed. (e) Per-subgraph rate-limiting on top of gateway-level. Indian SaaS reality: federation is increasingly common in larger Indian product teams; the federation model needs explicit threat-modelling because authz becomes a distributed concern.

Caching responses safely — what to cache and what to never cache

GraphQL caching is harder than REST because every query is potentially different. Strategies:

1Persisted-query CDN cache — only registered queries are cacheable; the cache key is (query-hash, variables). Works well for public read queries.
2Field-level cache — cache resolver outputs per field; tools like DataLoader + Redis cache reuse across queries.
3Client-side cache — Apollo Client / Relay normalised cache; reduces server requests but server must still authorise on miss. What to never cache: anything user-specific without including user-id in the cache key; anything containing PII or financial data without explicit Cache-Control: private; mutation responses (always uncacheable). Cache invalidation: subscription / event-driven invalidation; tag-based eviction (Apollo Cache Hints, Redis tags). For Indian e-commerce: aggressive read-side caching is essential for performance at scale; review cache keys to ensure no cross-user leakage. The bug class is “personalised data cached as public” — same root as cache-deception in REST.

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.

Want this for your team?

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.

Book team training call Replies in 4 working hrs · India-only · Senior consultants