How to Stop GraphQL Query Abuse in a Python API: Cap Depth, Cost, Aliases, and Introspection in Strawberry and FastAPI, Throttle Logins Per Account, and Test Every Limit
Build a small Strawberry and FastAPI GraphQL API, measure how a 152-byte request runs 222,222 SQL statements and how one request carries 100 password guesses, then add token, depth, alias and cost...
A GraphQL API gives every client one address and one query language. Instead of calling a dozen fixed endpoints, a client sends a short piece of text that names exactly the fields it wants, and the server assembles the answer. That freedom is the point of GraphQL, and it is also the risk: the client, not the developer, decides how much work one request causes. In the lab below, a 152-byte request makes a small Python server run 222,222 database statements while a second client’s health check waits about nine seconds, one HTTP request carries a hundred password guesses past a per-request rate limit, and the default error messages help a stranger guess the names of your fields.
Table Of Content
- The ideas you need before you write any code
- Prerequisites
- Step 0: Set up the project
- Step 1: Build the bookshop API
- The data, and a counter for every SQL statement
- Configuration and the login check
- The types and their resolvers
- The root types and the schema builder
- Check that the data is there
- Step 2: Serve it, and add the limit most teams already have
- Step 3: Send the first query
- Step 4: Attack one, a query that loops through the schema
- What happened
- Each hop multiplies the work
- One request freezes the server
- Step 5: Attack two, a wide query that is not deep
- Step 6: Attack three, one request with a hundred password guesses
- Step 7: What the endpoint gives away
- What each line means
- Step 8: Build the guards
- The limits, and a cost estimate for any query
- How the estimate works
- A bug the deep attack found
- The cost extension and the list of extensions
- Quiet errors, a login throttle and the hardened app
- Step 9: Pick the limits from your own queries
- Step 10: Run every attack against the hardened server
- Reading the table
- Which limit stops which attack
- Step 11: Throttle logins by account, not by request
- What to notice
- A lock has a price
- Step 12: Test the limits
- The helpers and the attack catalog
- Pinned numbers and inclusive boundaries
- The throttle and the live server
- Step 13: Check that the tests would notice a broken limit
- Check the whole thing end to end
- Common mistakes and gotchas
- Where this stops, and what to read next
- Sources and method
In this tutorial you will build that small server with Strawberry and FastAPI and attack it yourself in four ways. Then you will add the limits that stop each attack: a token limit, a depth limit, an alias limit, a cost limit, a page-size cap, a switch for introspection, quieter error messages and a login throttle that counts every guess. You will choose the numbers from your own queries instead of from a blog post, and you will finish with 28 tests and a planted-bug check that proves each limit still bites.
No GraphQL experience is assumed. Every step gives you the exact code, the output to expect, and a plain explanation of what the code does and why it is written that way. Everything runs on one computer with no database server, no account and no network access beyond installing packages.
The ideas you need before you write any code
GraphQL is a query language for APIs. A client sends one text document to one address; the server parses it (turns the text into a tree), validates it against the schema (checks that every field exists and every argument has the right type), and only then executes it. Remember that order: validation happens before any of your code has run, so it is the cheapest place to refuse a document.
The schema lists what exists. In this tutorial a bookshop has authors, each author has books, each book has reviews and an author. A query reads data; a mutation changes it or performs an action, and here the only mutation is login. A field is one named piece of data, and a resolver is the Python function that produces it. The books field of an author is a resolver that asks the database for that author’s books.
Notice the loop: an author has books and a book has an author. A client may walk around that loop as many times as it likes, and every lap multiplies the work. That is the first attack.
An alias renames a field in the answer, as in first_try: login(...). Because every alias gets its own name, the same field can appear a hundred times in one document. That is the third attack. Introspection is a built-in feature: the special fields __schema and __type let any client ask the server to describe its own schema, which is handy for tools and equally handy for an attacker.
Strawberry is a Python library for writing GraphQL servers with type hints. It leaves parsing and validation to graphql-core, the Python version of the reference GraphQL implementation. A Strawberry extension is a small plug-in that hooks into the steps of one request; the token, depth, alias and cost limits in this tutorial are extensions, or validation rules that an extension adds.
Last, FastAPI runs on an event loop: one thread that juggles many connections by switching whenever a function waits. A function that computes for nine seconds without waiting freezes everything else on that thread. You will see that happen in Step 4.
Prerequisites
- Operating system: I ran everything on Windows 11. The code is portable Python; only the command that activates the virtual environment differs on macOS and Linux.
- Python: Python 3.13.14. The packages declare Python 3.11 or newer; I did not test other versions.
- Packages: strawberry-graphql 0.341.3 (with its FastAPI extra), FastAPI 0.165.0, uvicorn 0.55.0, requests 2.34.2 and pytest 9.2.0. graphql-core 3.3.2 arrives as a dependency of Strawberry.
- Network: only to install the packages. The lab talks to itself on 127.0.0.1.
- Time and disk: about two hours to read and type. The slowest script, Step 4, takes about twelve seconds and the planted-bug check about a minute. Disk use is a few tens of megabytes for the virtual environment.
- Knowledge: Python functions, classes and dictionaries, and what an HTTP request and a status code are. Nothing about GraphQL or security is assumed.
Step 0: Set up the project
Create a folder and a virtual environment, then install the packages. Save every listing below in this folder under the file name on its first line.
mkdir gqlguard
cd gqlguard
python -m venv .venv
.venv\Scripts\activate
python -m pip install "strawberry-graphql[fastapi]==0.341.3" fastapi==0.165.0 uvicorn==0.55.0 requests==2.34.2 pytest==9.2.0
python --version
Python 3.13.14
Run every script with plain python script.py, not python -I: isolated mode removes the script’s own folder from the import path and the scripts import each other.
Step 1: Build the bookshop API
The API has four small pieces: a database that counts what it is asked, a configuration object, the schema, and a login check. The first piece is the database.
The data, and a counter for every SQL statement
# bookshop.py
"""A small GraphQL API for the tutorial: Strawberry on FastAPI, data in SQLite."""
import hashlib
import hmac
import secrets
import sqlite3
from dataclasses import dataclass
import strawberry
from graphql import GraphQLError
from strawberry.schema.config import StrawberryConfig
MAX_PAGE = 100
DEFAULT_PAGE = 20
ROUNDS = 10_000
SALT = b"bookshop-lab-salt"
PASSWORD = "sunflower42" # alice's password in this lab
SCHEMA_SQL = """
CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT NOT NULL, author_id INTEGER NOT NULL);
CREATE TABLE reviews (id INTEGER PRIMARY KEY, book_id INTEGER NOT NULL, stars INTEGER NOT NULL, text TEXT NOT NULL);
CREATE INDEX books_author ON books(author_id);
CREATE INDEX reviews_book ON reviews(book_id);
"""
class Db:
"""One in-memory SQLite database that counts every statement it runs."""
def __init__(self, authors=100, books=10, reviews=100):
self.conn = sqlite3.connect(":memory:", check_same_thread=False)
self.conn.row_factory = sqlite3.Row
self.conn.executescript(SCHEMA_SQL)
book_id = review_id = 0
for a in range(1, authors + 1):
self.conn.execute("INSERT INTO authors VALUES (?, ?)", (a, f"Author {a:03d}"))
for b in range(1, books + 1):
book_id += 1
self.conn.execute("INSERT INTO books VALUES (?, ?, ?)", (book_id, f"Book {a}-{b}", a))
rows = [(review_id + r, book_id, (book_id + r) % 5 + 1, f"Review {r} of book {book_id}")
for r in range(1, reviews + 1)]
review_id += reviews
self.conn.executemany("INSERT INTO reviews VALUES (?, ?, ?, ?)", rows)
self.conn.commit()
self.statements = 0
self.conn.set_trace_callback(self._count) # count only what the API runs
def _count(self, sql):
self.statements += 1
def reset(self):
self.statements = 0
def rows(self, sql, *args):
return self.conn.execute(sql, args).fetchall()
DB = Db()
This builds an in-memory SQLite database with 100 authors, 1,000 books (ten per author) and 100,000 reviews (one hundred per book). set_trace_callback makes Python call a function for every SQL statement that runs; it is installed after the seeding, so DB.statements counts only what the API does. That counter is how the attacks get measured: a GraphQL query that looks cheap can turn into a great many statements.
Configuration and the login check
The next piece has two parts. Config carries the settings that the resolvers read: max_page (the largest page a client may ask for; None means no cap, which is how the naive server starts) and throttle (a login throttle, or none). verify checks a password against a stored hash.
# bookshop.py (continued)
@dataclass
class Config:
max_page: int | None = None # None: no cap on "first" (the naive server)
throttle: object | None = None # a login throttle, or None
def page(self, first: int) -> int:
if self.max_page is None:
return first
if not 1 <= first <= self.max_page:
raise GraphQLError(f"first must be between 1 and {self.max_page}")
return first
def _hash(password: str) -> bytes:
return hashlib.pbkdf2_hmac("sha256", password.encode(), SALT, ROUNDS)
USERS = {"alice": _hash(PASSWORD)}
_DUMMY = _hash("not-a-real-password")
def verify(username: str, password: str) -> bool:
stored = USERS.get(username, _DUMMY) # same work for unknown users
return hmac.compare_digest(_hash(password), stored) and username in USERS
pbkdf2_hmac is a deliberately slow password hash. With 10,000 rounds each check costs a few milliseconds of CPU, which is realistic: a real login is expensive on purpose. compare_digest compares two hashes in constant time, and an unknown user name does the same work as a known one so that response time does not reveal which names exist.
The types and their resolvers
Each @strawberry.type class becomes a GraphQL type. A method decorated with @strawberry.field is a resolver, and its arguments become arguments of the field. first: int = DEFAULT_PAGE gives books an optional first argument that defaults to 20. strawberry.Private keeps author_id out of the schema, so clients cannot see it. Every resolver that reads data runs exactly one SQL statement, which keeps the counting honest.
# bookshop.py (continued)
@strawberry.type
class Review:
id: int
stars: int
text: str
@strawberry.type
class Book:
id: int
title: str
author_id: strawberry.Private[int]
@strawberry.field
def author(self) -> "Author":
row = DB.rows("SELECT id, name FROM authors WHERE id = ?", self.author_id)[0]
return Author(id=row["id"], name=row["name"])
@strawberry.field
def reviews(self, info: strawberry.Info, first: int = DEFAULT_PAGE) -> list[Review]:
n = info.context["cfg"].page(first)
rows = DB.rows("SELECT id, stars, text FROM reviews WHERE book_id = ? ORDER BY id LIMIT ?", self.id, n)
return [Review(id=r["id"], stars=r["stars"], text=r["text"]) for r in rows]
@strawberry.type
class Author:
id: int
name: str
@strawberry.field
def books(self, info: strawberry.Info, first: int = DEFAULT_PAGE) -> list[Book]:
n = info.context["cfg"].page(first)
rows = DB.rows("SELECT id, title, author_id FROM books WHERE author_id = ? ORDER BY id LIMIT ?", self.id, n)
return [Book(id=r["id"], title=r["title"], author_id=r["author_id"]) for r in rows]
The root types and the schema builder
Query lists the entry points a client may start from, and Mutation holds login. Inside login the throttle (when there is one) is asked first, the password is verified, and the outcome is recorded. Step 11 explains why that order matters. build_schema assembles everything and accepts a list of extensions and an optional batching setting; both stay empty for now.
# bookshop.py (continued)
@strawberry.type
class Query:
@strawberry.field
def author(self, id: int) -> Author | None:
rows = DB.rows("SELECT id, name FROM authors WHERE id = ?", id)
return Author(id=rows[0]["id"], name=rows[0]["name"]) if rows else None
@strawberry.field
def authors(self, info: strawberry.Info, first: int = DEFAULT_PAGE) -> list[Author]:
n = info.context["cfg"].page(first)
rows = DB.rows("SELECT id, name FROM authors ORDER BY id LIMIT ?", n)
return [Author(id=r["id"], name=r["name"]) for r in rows]
@strawberry.field
def book(self, id: int) -> Book | None:
rows = DB.rows("SELECT id, title, author_id FROM books WHERE id = ?", id)
r = rows[0] if rows else None
return Book(id=r["id"], title=r["title"], author_id=r["author_id"]) if r else None
@strawberry.type
class LoginResult:
ok: bool
token: str | None = None
@strawberry.type
class Mutation:
@strawberry.mutation
def login(self, info: strawberry.Info, username: str, password: str) -> LoginResult:
throttle = info.context["cfg"].throttle
name = username.casefold()
if throttle is not None:
throttle.check(name)
ok = verify(name, password)
if throttle is not None:
throttle.record(name, ok)
return LoginResult(ok=ok, token=secrets.token_hex(8) if ok else None)
def build_schema(extensions=(), batching=None):
config = StrawberryConfig(batching_config=batching) if batching else StrawberryConfig()
return strawberry.Schema(query=Query, mutation=Mutation, extensions=list(extensions), config=config)
Check that the data is there
Before going on, confirm that the database holds what you expect. This short script counts the rows in each table.
# step00_data.py
import bookshop
for table in ("authors", "books", "reviews"):
print(table, bookshop.DB.rows(f"SELECT COUNT(*) AS n FROM {table}")[0]["n"])
python step00_data.py
authors 100
books 1000
reviews 100000
If you see 100, 1000 and 100000, Step 1 is done. A ModuleNotFoundError here means a typo in a file name or a file saved in another folder.
Step 2: Serve it, and add the limit most teams already have
FastAPI will serve the schema through Strawberry’s router. The first part of server.py is a per-IP request limiter, the control that most teams already have in a proxy or gateway: at most 10 requests a minute from one address, then HTTP status 429.
# server.py
"""Serve the bookshop schema with FastAPI, run it in a thread, and talk to it."""
import json
import socket
import threading
import time
from dataclasses import dataclass
import requests
import uvicorn
from fastapi import FastAPI
from strawberry.fastapi import GraphQLRouter
import bookshop
class RequestLimiter:
"""A per-IP limit on HTTP requests to /graphql: the kind most teams already have."""
def __init__(self, app, max_requests, window_s, path="/graphql", clock=time.monotonic):
self.app, self.max_requests, self.window_s = app, max_requests, window_s
self.path, self.clock, self.hits = path, clock, {}
async def __call__(self, scope, receive, send):
if scope["type"] == "http" and scope["path"] == self.path:
key, now = scope["client"][0], self.clock()
recent = [t for t in self.hits.get(key, []) if now - t < self.window_s]
if len(recent) >= self.max_requests:
body = b'{"detail":"Too many requests"}'
headers = [(b"content-type", b"application/json"), (b"retry-after", str(int(self.window_s)).encode()),
(b"content-length", str(len(body)).encode())]
await send({"type": "http.response.start", "status": 429, "headers": headers})
await send({"type": "http.response.body", "body": body})
return
recent.append(now)
self.hits[key] = recent
await self.app(scope, receive, send)
The second part wires the schema into a FastAPI app. context_getter hands the configuration to every resolver. graphql_ide controls whether a browser that opens the address gets an in-browser query tool; the router’s default is on, and you will see in Step 7 why that matters. naive_server is the server as many teams first ship it: no limits except the request limiter.
# server.py (continued)
def make_app(cfg, schema, request_limit=None, ide="graphiql", router_cls=GraphQLRouter):
app = FastAPI()
async def context_getter():
return {"cfg": cfg}
app.include_router(router_cls(schema, context_getter=context_getter, graphql_ide=ide), prefix="/graphql")
@app.get("/health")
async def health():
return {"ok": True}
if request_limit:
app.add_middleware(RequestLimiter, max_requests=request_limit[0], window_s=request_limit[1])
return app
def naive_server(batching=None, request_limit=(10, 60)):
"""The server as many teams first ship it: no limits except 10 requests a minute per IP."""
app = make_app(bookshop.Config(), bookshop.build_schema(batching=batching), request_limit=request_limit)
return LiveServer(app)
The last part lets the scripts run a server inside the same process. LiveServer starts uvicorn in a background thread on a free port of 127.0.0.1 and waits until it is ready. Api.post sends one GraphQL document and returns the status, the parsed answer, the elapsed time and the byte counts. Because the server lives in the same process, a script can read bookshop.DB.statements straight after a request.
# server.py (continued)
class LiveServer:
def __init__(self, app):
probe = socket.socket()
probe.bind(("127.0.0.1", 0))
self.port = probe.getsockname()[1]
probe.close()
config = uvicorn.Config(app, host="127.0.0.1", port=self.port, log_level="warning", lifespan="off")
self.server = uvicorn.Server(config)
self.thread = threading.Thread(target=self.server.run, daemon=True)
@property
def url(self):
return f"http://127.0.0.1:{self.port}"
def __enter__(self):
self.thread.start()
t0 = time.time()
while not self.server.started:
if time.time() - t0 > 20:
raise RuntimeError("server did not start")
time.sleep(0.02)
return self
def __exit__(self, *exc):
self.server.should_exit = True
self.thread.join(15)
@dataclass
class Result:
status: int
body: dict | list | None
seconds: float
sent: int
received: int
class Api:
def __init__(self, live):
self.live, self.url = live, live.url + "/graphql"
def post(self, query, variables=None, timeout=300):
payload = {"query": query}
if variables:
payload["variables"] = variables
t0 = time.perf_counter()
r = requests.post(self.url, json=payload, timeout=timeout)
seconds = time.perf_counter() - t0
try:
body = r.json()
except ValueError:
body = None
return Result(r.status_code, body, seconds, len(r.request.body), len(r.content))
def short(value, width=100):
text = json.dumps(value) if not isinstance(value, str) else value
return text if len(text) <= width else text[: width - 3] + "..."
Step 3: Send the first query
Save and run this script. It starts the naive server, asks for one author with two of their books, and prints the answer and the number of SQL statements.
# step01_first_query.py
import bookshop
from server import Api, naive_server, short
with naive_server() as live:
api = Api(live)
bookshop.DB.reset()
r = api.post("{ author(id: 1) { name books(first: 2) { title } } }")
print("status:", r.status)
print("body: ", short(r.body, 200))
print("SQL statements run:", bookshop.DB.statements)
python step01_first_query.py
status: 200
body: {"data": {"author": {"name": "Author 001", "books": [{"title": "Book 1-1"}, {"title": "Book 1-2"}]}}}
SQL statements run: 2
Read the query as a shape: author(id: 1) picks one author, and inside the braces the client names the fields it wants. The answer has exactly that shape. Two statements ran: one for the author and one for the books. Keep that rule in mind, because every attack below is a way of making that number large.
Step 4: Attack one, a query that loops through the schema
Now the attacks. Save attacks.py; it holds every hostile query used in this tutorial, plus the first-party queries that must keep working. deep_query(hops) builds a query that walks author, books, author, books and so on; each extra hop goes through the author again.
# attacks.py
"""The queries we attack with, and the first-party queries that must keep working."""
WORDLIST = [f"guess{i:03d}" for i in range(100)]
WORDLIST[73] = "sunflower42" # the real password hides at position 73
def deep_query(hops):
"""author -> books -> author -> books ...: each hop back through the author multiplies the work."""
inner = "books { id }"
for _ in range(hops - 1):
inner = f"books {{ author {{ {inner} }} }}"
return "{ author(id: 1) { " + inner + " } }"
def alias_logins(count=100, user="alice"):
parts = [f'g{i}: login(username: "{user}", password: "{pw}") {{ ok }}' for i, pw in enumerate(WORDLIST[:count])]
return "mutation { " + " ".join(parts) + " }"
def nesting(query):
"""How many braces deep the document goes."""
depth = deepest = 0
for ch in query:
if ch == "{":
depth += 1
deepest = max(deepest, depth)
elif ch == "}":
depth -= 1
return deepest
WIDE = "{ authors(first: 100) { name books(first: 100) { title reviews(first: 100) { text } } } }"
TYPO = "{ authr(id: 1) { name } }"
INTROSPECTION = "{ __schema { types { name } } }"
BIG_FIRST = "{ authors(first: 5000) { id } }"
BIG_FIRST_VAR = ("query Page($n: Int) { authors(first: $n) { id } }", {"n": 5000})
LEGIT = {
"author_page": ("query AuthorPage($id: Int!) { author(id: $id) { id name books(first: 10) { id title "
"reviews(first: 3) { stars text } } } }", {"id": 7}),
"author_list": ("{ authors(first: 20) { id name } }", None),
"book_card": ("query BookCard($id: Int!) { book(id: $id) { title author { name } reviews(first: 5) { stars } } }",
{"id": 42}),
"compare": ("{ a: author(id: 1) { name } b: author(id: 2) { name } }", None),
"login": ("mutation Login($u: String!, $p: String!) { login(username: $u, password: $p) { ok } }",
{"u": "alice", "p": "wrong"}),
}
The first script sends that loop with 1 to 6 hops, writes down what each cost, and runs a second client that only asks the server whether it is up.
# step02_depth.py
import threading
import time
import requests
import attacks
import bookshop
from server import Api, naive_server
with naive_server() as live:
api = Api(live)
waits, stop = [], threading.Event()
def ping(): # a second client that only asks "are you up?"
while not stop.is_set():
t0 = time.perf_counter()
requests.get(live.url + "/health", timeout=120)
waits.append(time.perf_counter() - t0)
time.sleep(0.05)
print("hops braces bytes_sent sql_statements seconds response_KB")
for hops in (1, 2, 3, 4, 5, 6):
q = attacks.deep_query(hops)
bookshop.DB.reset()
if hops == 6:
pinger = threading.Thread(target=ping)
pinger.start()
time.sleep(0.3)
r = api.post(q)
if hops == 6:
stop.set()
pinger.join()
print(f"{hops:>4} {attacks.nesting(q):>6} {r.sent:>10} {bookshop.DB.statements:>14,} "
f"{r.seconds:>7.2f} {r.received / 1024:>11,.0f}")
print(f"/health pings during the 6-hop query: {len(waits)}, "
f"median {sorted(waits)[len(waits) // 2] * 1000:.0f} ms, slowest {max(waits):.2f} s")
python step02_depth.py
hops braces bytes_sent sql_statements seconds response_KB
1 3 47 2 0.01 0
2 5 68 22 0.00 1
3 7 89 222 0.01 11
4 9 110 2,222 0.07 114
5 11 131 22,222 0.71 1,138
6 13 152 222,222 9.03 11,382
/health pings during the 6-hop query: 7, median 13 ms, slowest 8.98 s
What happened
Each hop multiplies the work
Each hop multiplies the work by ten, because every author has ten books. The request for six hops is 152 bytes long and ran 222,222 SQL statements, took about nine seconds and produced an answer of roughly 11 megabytes. Your times will differ; the statement counts will not.
One request freezes the server
The last line is the dangerous one. While that single query ran, a second client that only asked /health waited as long as the query took. The resolvers here call SQLite directly, so they run on the event loop thread, and a thread that is busy cannot answer anyone else. One request from one client made the whole API unavailable for that time.
OWASP’s GraphQL Cheat Sheet describes this class of problem: depth and amount in a query “can both be unlimited which may lead to a DoS” by default, and it adds that “you should set limits on depth and amount to prevent DoS, but this usually requires a small custom implementation as it is not natively supported by GraphQL.” Strawberry ships ready-made extensions for some of the limits. The cost limit you will write yourself in Step 8.
Step 5: Attack two, a wide query that is not deep
A depth limit alone does not help against a query that is shallow but fans out. This one asks for up to 100 authors, 100 books of each and 100 reviews of each book, and it is only four braces deep.
# step03_width.py
import attacks
import bookshop
from server import Api, naive_server
with naive_server() as live:
api = Api(live)
bookshop.DB.reset()
r = api.post(attacks.WIDE)
authors = r.body["data"]["authors"]
reviews = sum(len(b["reviews"]) for a in authors for b in a["books"])
print(f"braces deep: {attacks.nesting(attacks.WIDE)}, request: {r.sent} bytes")
print(f"reviews returned: {reviews:,}")
print(f"SQL statements: {bookshop.DB.statements:,}")
print(f"time: {r.seconds:.2f} s, response: {r.received / 1024:,.0f} KB")
python step03_width.py
braces deep: 4, request: 102 bytes
reviews returned: 100,000
SQL statements: 1,101
time: 0.40 s, response: 3,241 KB
A 102-byte request returned 100,000 reviews, ran 1,101 statements and produced a 3.2 megabyte answer. The lab’s data is small, so the work here is capped by the rows that exist. On a real catalog the same shape is capped only by the size of your tables. Depth and page size are two different dials, and a defense has to cover both.
Step 6: Attack three, one request with a hundred password guesses
The naive server has a request limiter, so password guessing should be slow. This script first sends 30 separate login attempts, then sends one request that holds 100 aliased copies of the login mutation, each with a different password. The real password sits at position 73 in the word list.
# step04_aliases.py
from collections import Counter
import attacks
from server import Api, naive_server
guess = 'mutation { login(username: "alice", password: "nope") { ok } }'
with naive_server() as live: # 10 requests a minute per IP
api = Api(live)
codes = Counter(api.post(guess).status for _ in range(30))
print("30 separate requests:", dict(sorted(codes.items())))
with naive_server() as live: # a fresh limiter
api = Api(live)
r = api.post(attacks.alias_logins(100))
data = r.body["data"]
found = [name for name, value in data.items() if value["ok"]]
print(f"1 request with 100 aliases: status {r.status} in {r.seconds:.2f} s")
print("guesses evaluated:", len(data), "| correct password found at alias:", found)
python step04_aliases.py
30 separate requests: {200: 10, 429: 20}
1 request with 100 aliases: status 200 in 0.25 s
guesses evaluated: 100 | correct password found at alias: ['g73']
Thirty separate requests: ten were answered and twenty were refused with 429, exactly as the limiter intends. One request with 100 aliases: answered with status 200 in a quarter of a second, with every guess evaluated and the right password found at alias g73. The limiter counts HTTP requests, and the attacker sent one.
PortSwigger’s GraphQL guide explains the cause: “Some rate limiters work based on the number of HTTP requests received rather than the number of operations performed on the endpoint.” It adds: “Because aliases effectively enable you to send multiple queries in a single HTTP message, they can bypass this restriction.” OWASP puts it the same way: “HTTP request counts alone do not account for expensive queries or multiple operations in one request.”
Step 7: What the endpoint gives away
The last attack is about information. This script asks the naive server to describe itself, makes a deliberate typo, and then tries six unusual ways of sending a request. It also turns on Strawberry’s batching option on a second server, so you can see what that option does.
# step05_recon.py
import json
import requests
import attacks
from server import Api, naive_server, short
LOGIN = 'mutation { login(username: "alice", password: "nope") { ok } }'
def row(label, status, text):
print(f"{label:<38} {str(status):<5} {short(text, 80)}")
with naive_server(request_limit=None) as live:
api = Api(live)
url = live.url + "/graphql"
r = api.post(attacks.INTROSPECTION)
names = [t["name"] for t in r.body["data"]["__schema"]["types"]]
print("introspection:", r.status, len(names), "types, for example",
[n for n in names if not n.startswith("__")][:7])
r = api.post('{ __type(name: "Mutation") { fields { name args { name } } } }')
print("Mutation fields:", json.dumps(r.body["data"]["__type"]["fields"]))
r = api.post(attacks.TYPO)
print("typo error:", r.body["errors"][0]["message"])
print()
print(f"{'request':<38} {'code':<5} what came back")
ide = requests.get(url, headers={"Accept": "text/html"})
row("GET /graphql as a browser", ide.status_code, "the GraphiQL page" if "graphiql" in ide.text.lower() else ide.text)
row("GET with a query", requests.get(url, params={"query": "{ authors(first: 1) { id } }"}).status_code, "data")
g = requests.get(url, params={"query": LOGIN})
row("GET with a mutation", g.status_code, g.text)
f = requests.post(url, data={"query": "{ authors(first: 1) { id } }"})
row("POST as a form", f.status_code, f.text)
t = requests.post(url, data=json.dumps({"query": LOGIN}), headers={"Content-Type": "text/plain"})
row("POST JSON labelled text/plain", t.status_code, t.text)
a = requests.post(url, json=[{"query": LOGIN}] * 3)
row("POST an array of 3 (batching off)", a.status_code, a.text)
with naive_server(batching={"max_operations": 10}, request_limit=None) as live:
url = live.url + "/graphql"
a = requests.post(url, json=[{"query": LOGIN}] * 3)
row("array of 3 (max_operations 10)", a.status_code, f"{len(a.json())} results")
a = requests.post(url, json=[{"query": LOGIN}] * 11)
row("array of 11 (max_operations 10)", a.status_code, a.text)
python step05_recon.py
introspection: 200 17 types, for example ['Query', 'Author', 'Int', 'String', 'Book', 'Review', 'Mutation']
Mutation fields: [{"name": "login", "args": [{"name": "username"}, {"name": "password"}]}]
typo error: Cannot query field 'authr' on type 'Query'. Did you mean 'author' or 'authors'?
request code what came back
GET /graphql as a browser 200 the GraphiQL page
GET with a query 200 data
GET with a mutation 400 mutations are not allowed when using GET
POST as a form 400 Unsupported content type
POST JSON labelled text/plain 400 Unsupported content type
POST an array of 3 (batching off) 400 Batching is not enabled
array of 3 (max_operations 10) 200 3 results
array of 11 (max_operations 10) 400 Too many operations
What each line means
Introspection answered with 17 types, including GraphQL’s own built-in ones, and one more question listed the arguments of the login mutation. A typo, authr, produced an error that ends with “Did you mean ‘author’ or ‘authors’?”. PortSwigger notes the consequence: “Even if introspection is entirely disabled, you can sometimes use suggestions to glean information on an API’s structure.” Those hints are a way to recover field names one guess at a time.
The table shows Strawberry’s transport defaults. A browser that asks for the address gets the GraphiQL query tool, a friendly front end for the introspection you just saw, which a public production endpoint rarely needs. A query sent by GET works, but a mutation sent by GET is refused with 400. A form post and a JSON body labelled text/plain are refused with “Unsupported content type”. That matters because a web page can send those two content types to another site without a CORS preflight, and our CORS tutorial, linked at the end, measured that a no-cors POST still runs on the server. An array of operations is refused while batching is off. With batching_config set to a maximum of 10 operations, three operations are accepted and eleven are refused with “Too many operations”. Batching is a second way to put many logins into one request, which is why it stays off.
Step 8: Build the guards
Now the defenses. They live in guards.py, in four parts. The first part declares the limits. The numbers are the ones I ended up with; Step 9 shows where they came from, so skim them now.
The limits, and a cost estimate for any query
# guards.py
"""Query limits for the bookshop API (Strawberry 0.341.3, graphql-core 3.3.2)."""
import re
import time
from dataclasses import dataclass
from graphql import (
FieldNode,
FragmentDefinitionNode,
FragmentSpreadNode,
GraphQLError,
GraphQLList,
GraphQLNonNull,
InlineFragmentNode,
IntValueNode,
ValidationRule,
VariableNode,
get_named_type,
)
from strawberry.extensions import (
DisableIntrospection,
MaxAliasesLimiter,
MaxTokensLimiter,
QueryDepthLimiter,
SchemaExtension,
)
from strawberry.fastapi import GraphQLRouter
import bookshop
from server import make_app
@dataclass(frozen=True)
class Limits:
max_depth: int = 6
max_aliases: int = 5
max_tokens: int = 200
max_cost: int = 1000
max_page: int = 100
introspection: bool = False
How the estimate works
The cost estimate is the part you will not find in a library, so it deserves a slow read. It answers one question before anything runs: how many values will this query produce, at worst?
The rule is: a field costs its page size times (1 plus the cost of everything inside it). A scalar field such as id costs 1. A list field such as reviews(first: 3) { stars text } costs 3 × (1 + 2) = 9. For the first-party query author_page that adds up to 123. The page size comes from the first argument: a literal number, a number given in the request’s variables, or the schema’s default, and never more than max_page. A list field that has no first argument at all is priced at max_page, the worst case. The estimate follows named fragments and inline fragments, and it keeps track of the fragments it has already entered so that a cycle cannot send it into an endless loop.
# guards.py (continued)
# ---- cost: how many values will this query produce, at worst? ----------------------------------------
def _is_list(graphql_type):
while isinstance(graphql_type, GraphQLNonNull):
graphql_type = graphql_type.of_type
return isinstance(graphql_type, GraphQLList)
def _page_size(field_node, field_def, variables, max_page):
"""How many items a list field returns: the first argument, capped, or the worst case."""
arg = field_def.args.get("first")
if arg is None:
return max_page # a list with no page argument: assume the worst
value = arg.default_value
for given in field_node.arguments or ():
if given.name.value == "first":
node = given.value
if isinstance(node, IntValueNode):
value = int(node.value)
elif isinstance(node, VariableNode):
value = variables.get(node.name.value, value)
if not isinstance(value, int) or isinstance(value, bool):
return max_page
return max(1, min(value, max_page))
def estimate_cost(schema, document, operation, variables, max_page):
fragments = {d.name.value: d for d in document.definitions if isinstance(d, FragmentDefinitionNode)}
root = getattr(schema, f"{operation.operation.value}_type")
def walk(selection_set, parent, seen):
total = 0
for sel in selection_set.selections:
if isinstance(sel, FieldNode):
field_def = getattr(parent, "fields", {}).get(sel.name.value)
if field_def is None: # __typename and friends
total += 1
continue
children = walk(sel.selection_set, get_named_type(field_def.type), seen) if sel.selection_set else 0
size = _page_size(sel, field_def, variables, max_page) if _is_list(field_def.type) else 1
total += size * (1 + children)
elif isinstance(sel, InlineFragmentNode):
target = schema.get_type(sel.type_condition.name.value) if sel.type_condition else parent
total += walk(sel.selection_set, target, seen)
elif isinstance(sel, FragmentSpreadNode):
fragment = fragments.get(sel.name.value)
if fragment is not None and sel.name.value not in seen:
target = schema.get_type(fragment.type_condition.name.value)
total += walk(fragment.selection_set, target, seen | {sel.name.value})
return total
return walk(operation.selection_set, root, frozenset())
A bug the deep attack found
One detail came from a real failure. My first version crashed with 'NoneType' object is not iterable on any list field written without arguments, such as books { id }. graphql-core stores None, not an empty tuple, in the arguments of a field that has none, which is why the loop reads field_node.arguments or (). The deep attack from Step 4 found the crash, and the 3-hop test in Step 12 keeps it fixed.
The cost extension and the list of extensions
A validation rule is a class that graphql-core runs over the parsed document before execution. CostLimiter is a Strawberry extension whose only job is to add one such rule, and the rule reports an error when the estimate is above the limit. It reads the request’s variables from the execution context, so a client cannot hide a large page size in a variable. The second function turns the limits into a list of extensions: a token limit, a depth limit, an alias limit, the cost limit and, unless you ask for it, DisableIntrospection.
Look closely at the lambda in front of each extension. Strawberry’s documentation shows extensions passed as instances, such as QueryDepthLimiter(max_depth=10). In version 0.341.3 that works but prints a deprecation warning: “Passing an extension instance to extensions=[...] is deprecated and will be removed in a future release. Pass the class itself, or a factory callable (e.g. lambda: MyExtension(arg=...)), so that a fresh extension is constructed for each request.” A fresh extension per request is the form that warning asks for. A class such as DisableIntrospection can be passed as it is.
# guards.py (continued)
class CostLimiter(SchemaExtension):
def __init__(self, max_cost, max_page):
self.max_cost, self.max_page = max_cost, max_page
def on_operation(self):
ctx, max_cost, max_page = self.execution_context, self.max_cost, self.max_page
class CostRule(ValidationRule):
def enter_operation_definition(self, node, *_):
cost = estimate_cost(self.context.schema, self.context.document, node, ctx.variables or {}, max_page)
if cost > max_cost:
self.report_error(GraphQLError(f"Query too expensive: estimated cost {cost}, limit {max_cost}", node))
ctx.validation_rules = ctx.validation_rules + (CostRule,)
yield
def guard_extensions(limits):
"""Factories, not instances: Strawberry builds a fresh extension for every request."""
extensions = [
lambda: MaxTokensLimiter(max_token_count=limits.max_tokens),
lambda: QueryDepthLimiter(max_depth=limits.max_depth),
lambda: MaxAliasesLimiter(max_alias_count=limits.max_aliases),
lambda: CostLimiter(max_cost=limits.max_cost, max_page=limits.max_page),
]
if not limits.introspection:
extensions.append(DisableIntrospection)
return extensions
Strawberry’s own pages describe three of these limits in a sentence each. The alias limiter “adds a validator to limit the maximum number of aliases in a GraphQL document”. The token limiter makes the server answer with an error “if a client sends a query with more than 1000 tokens” (the number is whatever you configure). And the introspection page carries a warning: DisableIntrospection “does not block non-introspection fields that may expose schema information”, which is why the next part also has to deal with suggestions.
Quiet errors, a login throttle and the hardened app
QuietRouter overrides one method, process_result, which sees the final response before it is sent, and cuts the “Did you mean” sentence off every error message. LoginThrottle keeps, for each account name, the times of its recent failed logins. When an account has had max_failures failures inside the window, check raises an error, and it does so before the password is looked at, so even the right password is refused during a lock. The login resolver case-folds names, and unknown names are counted too, so the throttle does not reveal which accounts exist. hardened_app puts it all together and turns the in-browser query tool off.
# guards.py (continued)
# ---- the router hides "Did you mean" hints; the throttle counts every login attempt ----------------
SUGGESTION = re.compile(r"\s*Did you mean .*$")
class QuietRouter(GraphQLRouter):
async def process_result(self, request, result):
data = await super().process_result(request, result)
for error in data.get("errors") or []:
error["message"] = SUGGESTION.sub("", error["message"])
return data
class LoginThrottle:
"""Refuse a login once an account has had max_failures wrong passwords inside window_s seconds."""
def __init__(self, max_failures=5, window_s=900.0, clock=time.monotonic):
self.max_failures, self.window_s, self.clock = max_failures, window_s, clock
self.failures = {}
def _recent(self, name):
now = self.clock()
recent = [t for t in self.failures.get(name, []) if now - t < self.window_s]
self.failures[name] = recent
return recent
def check(self, name):
if len(self._recent(name)) >= self.max_failures:
raise GraphQLError("Too many failed logins for this account. Try again later.")
def record(self, name, ok):
if ok:
self.failures.pop(name, None)
else:
self._recent(name).append(self.clock())
LIMITS = Limits()
def hardened_app(limits=LIMITS, batching=None, throttle=None, request_limit=(60, 60)):
cfg = bookshop.Config(max_page=limits.max_page, throttle=throttle or LoginThrottle())
schema = bookshop.build_schema(guard_extensions(limits), batching=batching)
return make_app(cfg, schema, request_limit=request_limit, ide=None, router_cls=QuietRouter)
Step 9: Pick the limits from your own queries
A limit chosen by guessing is either too loose to matter or tight enough to break your own front end. The better method is to measure the queries your clients really send. The next script runs the five first-party queries from attacks.py and reports four numbers for each: the depth (using Strawberry’s own depth limiter in measuring mode), the alias count, the token count (the smallest token limit that still lets the query parse) and the cost estimate.
# step06_measure.py
"""Measure the first-party queries, so the limits come from data and not from guesses."""
import asyncio
from graphql import Visitor, parse, visit
from graphql.error import GraphQLSyntaxError
from strawberry.extensions import QueryDepthLimiter
import attacks
import bookshop
import guards
depths = {}
schema = bookshop.build_schema([lambda: QueryDepthLimiter(max_depth=100, callback=depths.update)])
context = {"cfg": bookshop.Config()}
class AliasCounter(Visitor):
def __init__(self):
super().__init__()
self.count = 0
def enter_field(self, node, *_):
if node.alias:
self.count += 1
def token_count(query):
for n in range(1, 5000): # the smallest max_tokens that still parses
try:
parse(query, max_tokens=n)
return n
except GraphQLSyntaxError:
continue
rows = []
print(f"{'query':<13} {'depth':>5} {'aliases':>7} {'tokens':>6} {'cost':>5}")
for name, (query, variables) in attacks.LEGIT.items():
depths.clear()
asyncio.run(schema.execute(query, variable_values=variables, context_value=context))
document = parse(query)
counter = AliasCounter()
visit(document, counter)
cost = guards.estimate_cost(schema._schema, document, document.definitions[0], variables or {}, 100)
rows.append((name, max(depths.values()), counter.count, token_count(query), cost))
print(f"{rows[-1][0]:<13} {rows[-1][1]:>5} {rows[-1][2]:>7} {rows[-1][3]:>6} {rows[-1][4]:>5}")
print(f"{'largest':<13} {max(r[1] for r in rows):>5} {max(r[2] for r in rows):>7} "
f"{max(r[3] for r in rows):>6} {max(r[4] for r in rows):>5}")
print(f"{'limits':<13} {guards.LIMITS.max_depth:>5} {guards.LIMITS.max_aliases:>7} "
f"{guards.LIMITS.max_tokens:>6} {guards.LIMITS.max_cost:>5}")
python step06_measure.py
query depth aliases tokens cost
author_page 3 0 42 123
author_list 1 0 12 60
book_card 2 0 34 14
compare 1 2 24 4
login 1 0 30 2
largest 3 2 42 123
limits 6 5 200 1000
The largest first-party query is three levels deep (author, books and reviews; Strawberry does not count the leaf fields), uses two aliases, has 42 tokens and costs 123. The limits in guards.py are 6, 5, 200 and 1,000. Depth is twice the largest value and aliases are a little more than twice. Tokens and cost are looser, roughly five and eight times the largest, because a query grows every time the front-end team adds a field, and a limit that breaks a release tends to get switched off. Pick your own headroom, and rerun this script whenever the front end changes.
Step 10: Run every attack against the hardened server
Now the payoff. This script starts the hardened server, sends ten queries (nine hostile ones and, as a control, a harmless two-hop loop), and prints the HTTP status, the number of SQL statements that ran, the time and the first error message. It then sends the five first-party queries to both servers and compares the answers.
# step07_hardened.py
import attacks
import bookshop
import guards
from server import Api, LiveServer, naive_server, short
CASES = [
("deep, 2 hops", attacks.deep_query(2), None),
("deep, 3 hops", attacks.deep_query(3), None),
("deep, 6 hops", attacks.deep_query(6), None),
("wide, 100 x 100 x 100", attacks.WIDE, None),
("100 aliased logins", attacks.alias_logins(100), None),
("10 aliased logins", attacks.alias_logins(10), None),
("introspection", attacks.INTROSPECTION, None),
("typo with suggestions", attacks.TYPO, None),
("first: 5000", attacks.BIG_FIRST, None),
("first: $n, n = 5000", *attacks.BIG_FIRST_VAR),
]
with LiveServer(guards.hardened_app(request_limit=None)) as live:
api = Api(live)
print(f"{'attack':<24} {'code':>4} {'sql':>4} {'sec':>6} first error")
for label, query, variables in CASES:
bookshop.DB.reset()
r = api.post(query, variables)
message = r.body["errors"][0]["message"] if r.body and r.body.get("errors") else "(answered)"
print(f"{label:<24} {r.status:>4} {bookshop.DB.statements:>4} {r.seconds:>6.3f} {short(message, 78)}")
hardened = {name: api.post(q, v).body for name, (q, v) in attacks.LEGIT.items()}
with naive_server(request_limit=None) as live:
api = Api(live)
naive = {name: api.post(q, v).body for name, (q, v) in attacks.LEGIT.items()}
print()
print("first-party queries, hardened vs naive server:")
for name in attacks.LEGIT:
same = hardened[name] == naive[name] and "errors" not in hardened[name]
print(f" {name:<12} same answer, no errors: {same}")
python step07_hardened.py
attack code sql sec first error
deep, 2 hops 200 22 0.007 (answered)
deep, 3 hops 200 0 0.004 Query too expensive: estimated cost 16841, limit 1000
deep, 6 hops 200 0 0.003 'anonymous' exceeds maximum operation depth of 6
wide, 100 x 100 x 100 200 0 0.004 Query too expensive: estimated cost 2020200, limit 1000
100 aliased logins 200 0 0.003 Syntax Error: Document contains more than 200 tokens. Parsing aborted.
10 aliased logins 200 0 0.004 10 aliases found. Allowed: 5
introspection 200 0 0.003 GraphQL introspection has been disabled, but the requested query contained ...
typo with suggestions 200 0 0.003 Cannot query field 'authr' on type 'Query'.
first: 5000 200 0 0.006 first must be between 1 and 100
first: $n, n = 5000 200 0 0.004 first must be between 1 and 100
first-party queries, hardened vs naive server:
author_page same answer, no errors: True
author_list same answer, no errors: True
book_card same answer, no errors: True
compare same answer, no errors: True
login same answer, no errors: True
Reading the table
Every hostile query ran zero SQL statements, because every one was refused before any resolver ran. The table also shows how the limits overlap:
- The 2-hop loop is answered (22 statements); the limits do not break ordinary nesting.
- The 3-hop loop is six levels deep, which the depth limit allows, but its estimated cost is 16,841 against a limit of 1,000, so the cost limit stops it. The estimate is deliberately a worst case: it prices
booksat the schema default of 20 per author even though this data has ten, because the price must depend on what the schema allows and not on what rows happen to exist today. The 6-hop loop is stopped earlier by the depth limit. - The wide query is priced at 2,020,200.
- The document with 100 aliased logins never reaches validation: it has far more than 200 tokens, so the parser refuses it. The document with 10 aliased logins is small enough to parse and is stopped by the alias limit.
- Introspection is refused, and the typo error no longer carries a suggestion.
first: 5000, in a literal and in a variable, is refused by the page cap in the resolver, which sees the real value whatever way it arrived.
All nine rejections came back with HTTP status 200 and an errors array. That is normal for GraphQL over JSON, and it means a dashboard that counts non-200 responses will not see these attacks. Log the rejections by looking inside the body.
The last five lines show that the five first-party queries return exactly what they returned on the naive server, with no errors.
Which limit stops which attack
| Limit | Runs at | Stops | Does not stop |
|---|---|---|---|
| Token limit | parsing | very large documents, such as 100 aliased logins | small documents that are expensive |
| Depth limit | validation | deep loops through the schema | wide queries |
| Alias limit | validation | one field repeated many times under different names | many operations sent as an array, or many requests |
| Cost limit | validation | deep and wide list queries | one field whose resolver is expensive on its own |
| Page cap | resolver | huge first values, however they are written |
nothing else |
| Introspection off, quiet errors | validation and response | reading the schema in one request, and hints from error messages | patient guessing of field names |
| Login throttle | resolver | password guessing by aliases, arrays or separate requests | an attacker locking out a victim on purpose |
| Request limiter | HTTP edge | floods of requests | anything that fits inside one request |
Step 11: Throttle logins by account, not by request
The request limiter could not see inside one request. A limit that can see inside one request has to live in the resolver, where each login attempt is a separate call. OWASP’s cheat sheet describes the idea: “the backend would track how many different object instances the caller has requested, so that they will be blocked after requesting too many objects even if they batch the object requests in a single network call.”
This script uses a fake clock that you can move by hand. It shows the alias limit refusing 10 aliases. Then it lifts the alias, token and cost limits on purpose, so the throttle has to do the work alone against 100 aliased guesses, and it finally shows that the lock ends when the window ends.
# step08_throttle.py
import asyncio
import attacks
import bookshop
import guards
evaluated = []
_real_verify = bookshop.verify
def counting_verify(username, password):
evaluated.append(password)
return _real_verify(username, password)
bookshop.verify = counting_verify
now = [0.0] # a fake clock we can move by hand
throttle = guards.LoginThrottle(max_failures=5, window_s=900, clock=lambda: now[0])
context = {"cfg": bookshop.Config(max_page=100, throttle=throttle)}
def run(schema, query):
return asyncio.run(schema.execute(query, context_value=context))
# 1. The alias limit alone: ten aliases never reach the login resolver.
schema = bookshop.build_schema(guards.guard_extensions(guards.LIMITS))
result = run(schema, attacks.alias_logins(10))
print("alias limit on :", result.errors[0].message, "| passwords checked:", len(evaluated))
# 2. Lift the alias limit to show the throttle on its own.
lifted = guards.Limits(max_aliases=1000, max_tokens=5000, max_cost=100000)
schema = bookshop.build_schema(guards.guard_extensions(lifted))
result = run(schema, attacks.alias_logins(100))
answered = result.data and sum(1 for v in result.data.values() if v is not None)
print("alias limit off:", f"{len(evaluated)} passwords checked, {len(result.errors)} refused,",
"password at alias 73 reached:", "sunflower42" in evaluated)
# 3. Even the right password is refused while the account is locked ...
print("right password, locked: ", run(schema, 'mutation { login(username: "alice", password: "sunflower42") { ok } }').errors[0].message)
now[0] += 901 # ... until the window has passed.
result = run(schema, 'mutation { login(username: "alice", password: "sunflower42") { ok } }')
print("right password, +901 s: ", result.data)
python step08_throttle.py
alias limit on : 10 aliases found. Allowed: 5 | passwords checked: 0
alias limit off: 5 passwords checked, 1 refused, password at alias 73 reached: False
right password, locked: Too many failed logins for this account. Try again later.
right password, +901 s: {'login': {'ok': True}}
What to notice
With the alias limit on, no password was compared at all. With it lifted, the throttle let five wrong guesses through, refused the sixth, and the right password at alias 73 was never compared. Only one refusal shows because login returns a non-null result: the error from the sixth alias empties the whole mutation, so the response holds one error and no data. That is safe, and it is also a surprise for a client that wanted a separate answer for each alias. While the account is locked even the right password is refused; 901 seconds later, with a window of 900, it works again.
A lock has a price
A per-account lock has a price: anyone can lock a victim out by guessing wrong five times. Teams soften that by counting on the account and the client address together, by slowing the answers instead of refusing them, or by asking for a second factor, and the right mix depends on your threat model. OWASP’s list of options for batching attacks is worth reading before you choose.
Step 12: Test the limits
A limit nobody tests is a limit somebody removes by accident. The tests run each hostile query against the guarded schema and check two things: the right error comes back, and nothing expensive ran (zero SQL statements, zero passwords compared). Most tests call the schema directly, which is fast; a few start a live server to check the response itself.
The helpers and the attack catalog
run builds a guarded schema with the limits you give it and executes one document. The checked fixture records every password the login resolver compares. REFUSED is the attack catalog: ten hostile queries, each with the error message it must produce.
# test_guards.py
import asyncio
import pytest
import requests
from graphql import parse
import attacks
import bookshop
import guards
from server import Api, LiveServer
LIMITS = guards.LIMITS
FRAGMENTS = """query { authors(first: 100) { ...A } }
fragment A on Author { books(first: 100) { ...B } }
fragment B on Book { reviews(first: 100) { text } }"""
INLINE = "query { authors(first: 100) { ... on Author { books(first: 100) { reviews(first: 100) { text } } } } }"
CYCLE = ("query { author(id: 1) { ...A } } fragment A on Author { books { ...B } } "
"fragment B on Book { author { ...A } }")
VARIABLE_PAGE = "query Q($n: Int) { authors(first: $n) { id name } }"
RIGHT_PASSWORD = 'mutation { login(username: "alice", password: "sunflower42") { ok } }'
def run(query, variables=None, limits=LIMITS, throttle=None):
schema = bookshop.build_schema(guards.guard_extensions(limits))
cfg = bookshop.Config(max_page=limits.max_page, throttle=throttle or guards.LoginThrottle())
return asyncio.run(schema.execute(query, variable_values=variables, context_value={"cfg": cfg}))
def messages(result):
return " | ".join(e.message for e in result.errors or [])
@pytest.fixture
def checked(monkeypatch):
"""Record every password the login resolver actually compares."""
calls, real = [], bookshop.verify
def spy(username, password):
calls.append(password)
return real(username, password)
monkeypatch.setattr(bookshop, "verify", spy)
return calls
REFUSED = [
("depth", attacks.deep_query(4), None, "exceeds maximum operation depth of 6"),
("cost_of_deep", attacks.deep_query(3), None, "Query too expensive"),
("cost_of_wide", attacks.WIDE, None, "Query too expensive"),
("fragments", FRAGMENTS, None, "Query too expensive"),
("inline_fragment", INLINE, None, "Query too expensive"),
("aliases", attacks.alias_logins(10), None, "10 aliases found. Allowed: 5"),
("tokens", attacks.alias_logins(100), None, "more than 200 tokens"),
("introspection", attacks.INTROSPECTION, None, "introspection has been disabled"),
("first_literal", attacks.BIG_FIRST, None, "first must be between 1 and 100"),
("first_variable", *attacks.BIG_FIRST_VAR, "first must be between 1 and 100"),
]
@pytest.mark.parametrize("name,query,variables,expected", REFUSED, ids=[r[0] for r in REFUSED])
def test_attack_is_refused_before_any_work(name, query, variables, expected, checked):
bookshop.DB.reset()
result = run(query, variables)
assert expected in messages(result)
assert bookshop.DB.statements == 0 and checked == []
@pytest.mark.parametrize("name", list(attacks.LEGIT))
def test_first_party_query_still_works(name):
query, variables = attacks.LEGIT[name]
result = run(query, variables)
plain = asyncio.run(bookshop.build_schema().execute(query, variable_values=variables,
context_value={"cfg": bookshop.Config()}))
assert result.errors is None and result.data == plain.data
Pinned numbers and inclusive boundaries
The next tests pin the cost estimate for every first-party query (123, 60, 14, 4 and 2), so a change to the estimator cannot go unnoticed. They also test each limit at its boundary: a query that costs exactly 123 passes at a limit of 123 and fails at 122, and the same for depth, aliases and tokens. Boundary tests are what catch an off-by-one in a comparison. The remaining tests cover page sizes given in variables, named and inline fragments, and a fragment cycle.
# test_guards.py (continued)
def test_cost_numbers_are_pinned():
schema = bookshop.build_schema()._schema
costs = {}
for name, (query, variables) in attacks.LEGIT.items():
document = parse(query)
costs[name] = guards.estimate_cost(schema, document, document.definitions[0], variables or {}, 100)
assert costs == {"author_page": 123, "author_list": 60, "book_card": 14, "compare": 4, "login": 2}
def test_limits_are_inclusive():
page, page_vars = attacks.LEGIT["author_page"] # depth 3, cost 123
compare, _ = attacks.LEGIT["compare"] # 2 aliases
listing, _ = attacks.LEGIT["author_list"] # 12 tokens
assert run(page, page_vars, guards.Limits(max_cost=123)).errors is None
assert "too expensive" in messages(run(page, page_vars, guards.Limits(max_cost=122)))
assert run(page, page_vars, guards.Limits(max_depth=3)).errors is None
assert "maximum operation depth" in messages(run(page, page_vars, guards.Limits(max_depth=2)))
assert run(compare, None, guards.Limits(max_aliases=2)).errors is None
assert "2 aliases found" in messages(run(compare, None, guards.Limits(max_aliases=1)))
assert run(listing, None, guards.Limits(max_tokens=12)).errors is None
assert "more than 11 tokens" in messages(run(listing, None, guards.Limits(max_tokens=11)))
def test_a_page_size_in_a_variable_is_priced():
tight = guards.Limits(max_cost=200)
assert run(VARIABLE_PAGE, {"n": 5}, tight).errors is None # 5 * (1 + 2) = 15
assert "too expensive" in messages(run(VARIABLE_PAGE, {"n": 100}, tight)) # 100 * 3 = 300
def test_a_fragment_cycle_is_an_error_not_a_hang():
assert "within itself" in messages(run(CYCLE))
def test_introspection_can_be_switched_on():
assert run(attacks.INTROSPECTION, limits=guards.Limits(introspection=True)).errors is None
The throttle and the live server
The throttle tests use the fake clock again: a lock after the maximum number of failures, every alias counted, a lock that ends with its window, a success that clears the failures, and account names compared without regard to case. The last tests start a real server to check the suggestion-free errors, the closed-down transport and the 429 of the request limiter.
# test_guards.py (continued)
def make_throttle(max_failures=3):
now = [0.0]
return guards.LoginThrottle(max_failures=max_failures, window_s=100, clock=lambda: now[0]), now
def login(name, password):
return f'mutation {{ login(username: "{name}", password: "{password}") {{ ok }} }}'
def test_the_throttle_locks_an_account_after_max_failures():
throttle, _ = make_throttle(3)
for _ in range(3):
assert run(login("alice", "wrong"), throttle=throttle).data == {"login": {"ok": False}}
assert "Too many failed logins" in messages(run(RIGHT_PASSWORD, throttle=throttle))
def test_the_throttle_counts_every_alias(checked):
throttle, _ = make_throttle(2)
lifted = guards.Limits(max_aliases=1000, max_tokens=5000, max_cost=10**6)
result = run(attacks.alias_logins(100), limits=lifted, throttle=throttle)
assert len(checked) == 2 and "Too many failed logins" in messages(result)
assert "sunflower42" not in checked
def test_the_lock_ends_when_the_window_ends():
throttle, now = make_throttle(2)
for _ in range(2):
run(login("alice", "wrong"), throttle=throttle)
assert "Too many" in messages(run(RIGHT_PASSWORD, throttle=throttle))
now[0] = 99
assert "Too many" in messages(run(RIGHT_PASSWORD, throttle=throttle))
now[0] = 101
assert run(RIGHT_PASSWORD, throttle=throttle).data == {"login": {"ok": True}}
def test_a_success_clears_the_failures():
throttle, _ = make_throttle(3)
for _ in range(2):
run(login("alice", "wrong"), throttle=throttle)
assert run(RIGHT_PASSWORD, throttle=throttle).data == {"login": {"ok": True}}
for _ in range(2):
assert run(login("alice", "wrong"), throttle=throttle).errors is None
def test_accounts_are_counted_by_name_ignoring_case_and_unknown_names_count_too():
throttle, _ = make_throttle(2)
run(login("Alice", "wrong"), throttle=throttle)
run(login("ALICE", "wrong"), throttle=throttle)
assert "Too many" in messages(run(login("alice", "wrong"), throttle=throttle))
assert run(login("bob", "wrong"), throttle=throttle).errors is None
run(login("nobody", "x"), throttle=throttle)
run(login("nobody", "x"), throttle=throttle)
assert "Too many" in messages(run(login("nobody", "x"), throttle=throttle))
@pytest.fixture(scope="module")
def live():
with LiveServer(guards.hardened_app(request_limit=None)) as server:
yield server
def test_error_messages_carry_no_suggestions(live):
body = Api(live).post(attacks.TYPO).body
assert body["errors"][0]["message"] == "Cannot query field 'authr' on type 'Query'."
def test_the_transport_is_closed_down(live):
url = live.url + "/graphql"
browser = requests.get(url, headers={"Accept": "text/html"})
assert "graphiql" not in browser.text.lower()
assert requests.get(url, params={"query": attacks.alias_logins(1)}).status_code == 400
batch = requests.post(url, json=[{"query": "{ authors(first: 1) { id } }"}] * 3)
assert batch.status_code == 400 and "Batching is not enabled" in batch.text
def test_the_request_limiter_answers_429():
with LiveServer(guards.hardened_app(request_limit=(3, 60))) as server:
api = Api(server)
codes = [api.post("{ authors(first: 1) { id } }").status for _ in range(4)]
assert codes == [200, 200, 200, 429]
python -m pytest -q test_guards.py
............................ [100%]
28 passed in 1.37s
Step 13: Check that the tests would notice a broken limit
Passing tests prove little unless they can fail. This script copies the lab, plants one bug at a time (a comparison turned from greater-than to greater-or-equal, a limit made a hundred times too high, a check removed) and runs the tests against each copy. A planted bug that the tests do not notice would mean a hole in the tests. The control run, with nothing planted, must pass.
# mutants.py
"""Plant one bug at a time in a copy of the lab and check that the tests notice."""
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
MUTANTS = [
("cost ignores the page size", "guards.py", "return max(1, min(value, max_page))", "return 1"),
("cost ignores a page size in a variable", "guards.py",
"value = variables.get(node.name.value, value)", "value = value"),
("cost skips named fragments", "guards.py", "elif isinstance(sel, FragmentSpreadNode):", "elif False:"),
("cost skips inline fragments", "guards.py", "elif isinstance(sel, InlineFragmentNode):", "elif False:"),
("cost follows fragment cycles", "guards.py",
"if fragment is not None and sel.name.value not in seen:", "if fragment is not None:"),
("cost limit is exclusive", "guards.py", "if cost > max_cost:", "if cost >= max_cost:"),
("depth limit 10 too high", "guards.py", "max_depth=limits.max_depth)", "max_depth=limits.max_depth + 10)"),
("alias limit 100 times too high", "guards.py",
"max_alias_count=limits.max_aliases)", "max_alias_count=limits.max_aliases * 100)"),
("token limit 100 times too high", "guards.py",
"max_token_count=limits.max_tokens)", "max_token_count=limits.max_tokens * 100)"),
("introspection left on", "guards.py", "if not limits.introspection:", "if limits.introspection:"),
("suggestions left in errors", "guards.py", 'error["message"] = SUGGESTION.sub("", error["message"])', "pass"),
("IDE left on", "guards.py", "ide=None, router_cls=QuietRouter", 'ide="graphiql", router_cls=QuietRouter'),
("plain router", "guards.py", "ide=None, router_cls=QuietRouter", "ide=None, router_cls=GraphQLRouter"),
("batching switched on", "guards.py",
"guard_extensions(limits), batching=batching)", 'guard_extensions(limits), batching={"max_operations": 1000})'),
("failures never recorded", "guards.py", "self._recent(name).append(self.clock())", "pass"),
("lock one attempt late", "guards.py",
"if len(self._recent(name)) >= self.max_failures:", "if len(self._recent(name)) > self.max_failures:"),
("failures never expire", "guards.py", "if now - t < self.window_s]", "if True]"),
("a success keeps the failures", "guards.py", "self.failures.pop(name, None)", "pass"),
("login skips the throttle check", "bookshop.py", "throttle.check(name)", "pass"),
("account name is case sensitive", "bookshop.py", "name = username.casefold()", "name = username"),
("page cap not enforced", "bookshop.py", "if not 1 <= first <= self.max_page:", "if False:"),
("request limiter lets one extra in", "server.py",
"if len(recent) >= self.max_requests:", "if len(recent) > self.max_requests:"),
]
def run_tests(folder):
env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1", PYTHONUTF8="1", COLUMNS="170")
p = subprocess.run([sys.executable, "-m", "pytest", "-x", "-q", "-p", "no:cacheprovider", "test_guards.py"],
cwd=folder, env=env, capture_output=True, text=True, timeout=180)
failed = re.search(r"^FAILED \S+::(\w+)", p.stdout, re.M)
return p.returncode, (failed.group(1) if failed else "")
def fresh_copy():
folder = Path(tempfile.mkdtemp(prefix="mutant_"))
for path in HERE.glob("*.py"):
if path.name != "mutants.py":
shutil.copy(path, folder / path.name)
return folder
code, _ = run_tests(fresh_copy())
print("control (no bug planted):", "passes" if code == 0 else "FAILS")
caught = 0
for name, filename, old, new in MUTANTS:
folder = fresh_copy()
path = folder / filename
text = path.read_text(encoding="utf-8")
assert text.count(old) == 1, (name, text.count(old))
path.write_text(text.replace(old, new), encoding="utf-8", newline="\n")
code, test = run_tests(folder)
caught += code != 0
print(f"{'caught' if code != 0 else 'MISSED':<7} {name:<40} {test}")
shutil.rmtree(folder, ignore_errors=True)
print(f"{caught} of {len(MUTANTS)} planted bugs caught")
python mutants.py
control (no bug planted): passes
caught cost ignores the page size test_attack_is_refused_before_any_work
caught cost ignores a page size in a variable test_a_page_size_in_a_variable_is_priced
caught cost skips named fragments test_attack_is_refused_before_any_work
caught cost skips inline fragments test_attack_is_refused_before_any_work
caught cost follows fragment cycles test_a_fragment_cycle_is_an_error_not_a_hang
caught cost limit is exclusive test_limits_are_inclusive
caught depth limit 10 too high test_attack_is_refused_before_any_work
caught alias limit 100 times too high test_attack_is_refused_before_any_work
caught token limit 100 times too high test_attack_is_refused_before_any_work
caught introspection left on test_attack_is_refused_before_any_work
caught suggestions left in errors test_error_messages_carry_no_suggestions
caught IDE left on test_the_transport_is_closed_down
caught plain router test_error_messages_carry_no_suggestions
caught batching switched on test_the_transport_is_closed_down
caught failures never recorded test_the_throttle_locks_an_account_after_max_failures
caught lock one attempt late test_the_throttle_locks_an_account_after_max_failures
caught failures never expire test_the_lock_ends_when_the_window_ends
caught a success keeps the failures test_a_success_clears_the_failures
caught login skips the throttle check test_the_throttle_locks_an_account_after_max_failures
caught account name is case sensitive test_accounts_are_counted_by_name_ignoring_case_and_unknown_names_count_too
caught page cap not enforced test_attack_is_refused_before_any_work
caught request limiter lets one extra in test_the_request_limiter_answers_429
22 of 22 planted bugs caught
All 22 planted bugs were caught on the first run, and the control passed. The list is also a map of what can go wrong in a hardening layer: an estimate that ignores page sizes or fragments, a limit that is off by one or far too high, an introspection switch that is left on, errors that keep their hints, a router that falls back to the default settings, a throttle that forgets failures or never expires them, a login that skips the throttle, and a request limiter that lets one extra request in.
Check the whole thing end to end
Run the scripts in order and compare what you see with the outputs above: counts must match exactly, timings only roughly.
python step01_first_query.py
python step02_depth.py
python step03_width.py
python step04_aliases.py
python step05_recon.py
python step06_measure.py
python step07_hardened.py
python step08_throttle.py
python -m pytest -q test_guards.py
python mutants.py
Success looks like this: the six-hop loop costs 222,222 statements on the naive server and zero on the hardened one, the hundred-guess request finds the password on the naive server and compares nothing on the hardened one, all five first-party queries return identical answers on both, 28 tests pass, and 22 of 22 planted bugs are caught.
Common mistakes and gotchas
- Extension instances. The documentation examples pass instances; version 0.341.3 warns about them. Use a class or a
lambdafactory. - Introspection off is not schema hiding. It blocks
__schemaand__type. Suggestions in error messages still name your fields until you remove them. - Rejections are HTTP 200. Monitor the
errorsarray, not just status codes. - Defaults to review. The FastAPI router serves GraphiQL unless
graphql_ideisNone, GET queries are allowed, and batching is off until you configure it. - Limits overlap on purpose. A document can be refused by the parser, by a validation rule or by a resolver. Expect different messages for similar attacks, and test each layer separately.
- A limit is only as good as its numbers. Measure your own queries (Step 9) and rerun the measurement when the front end changes.
Where this stops, and what to read next
These limits guard the front door. They do not make a slow resolver fast: the resolvers here still run on the event loop thread, and OWASP is blunt about timeouts, saying that “timeouts are not always effective since they may not activate until a malicious query has already consumed excessive resources”, and that GraphQL itself has no query timeouts, so custom code is needed. They do not decide who may see which object; for that, read our tutorials on broken object level authorization and mass assignment and excessive data exposure.
Good next steps, each a project of its own: a per-client budget of cost units instead of HTTP requests (OWASP advises applying GraphQL rate limits “in the business logic layer”); persisted queries, where the server accepts only documents it already knows; a loader that batches the one-statement-per-field lookups seen in Step 4; and logging every rejected document together with its estimated cost, so you can see attacks and your own front end drifting toward the limits. For the layers around this one, see our posts on building a rate limiter, hardening it against spoofed client addresses, backpressure and load shedding, timeouts and deadlines and CORS.
OWASP’s cheat sheet also offers advice before you build query cost analysis at all: “Try to crash or slow down your staging API with a nasty query and see how far you get.” That is what Steps 4 to 7 did, and I would keep the attack catalog in your test suite so the question is answered again on every release.
Sources and method
- Strawberry GraphQL documentation: Query Depth Limiter, Max Aliases Limiter, Max Tokens Limiter and Disable Introspection.
- OWASP GraphQL Cheat Sheet.
- PortSwigger Web Security Academy, GraphQL API vulnerabilities.
- The behavior of strawberry-graphql 0.341.3 and graphql-core 3.3.2 was read from their source and measured by the scripts above, including the deprecation warning for extension instances and the batching and transport responses.
Everything was run on Windows 11 with Python 3.13.14, strawberry-graphql 0.341.3, graphql-core 3.3.2, FastAPI 0.165.0, uvicorn 0.55.0, requests 2.34.2 and pytest 9.2.0. The database is a small made-up bookshop, so the absolute times will not match a production system; the statement counts, costs and limit decisions are deterministic. No attack in this tutorial was aimed at anything except the lab’s own server on 127.0.0.1.








No Comment! Be the first one.