These are the notes for Cybersecurity Fundamentals (defensive), episode 50. Episode 49 covered the first three risks of the OWASP API Security Top 10 (2023): broken object level authorization (BOLA), broken authentication, and broken object property level authorization (BOPLA). Today we cover the other seven, API4 to API10, and then the defences that sit in front of every API: the API gateway, the web application firewall (WAF), schema validation from an OpenAPI file, and depth and cost limits for GraphQL. Every term is explained the first time it appears; the Glossary at the end defines them all again.
Neha, Asha, the shop and every value are made up. Host names use the reserved example domains (RFC 2606) or private addresses. The "network" in the SSRF demo is a Python dictionary, the hacked "partner" is a function, and the "bot" is a list. Nothing outside the machine is contacted. Python samples run on 12 Nov 2026 with Python 3.13; every output below is copied from a real run (the random reference id differs each run).
The problems you'll solve
| Problem | OWASP API risk (2023) | Idea it teaches |
|---|---|---|
| One request returns 24 MB; OTP texts cost Rs 25,000 | API4 Unrestricted Resource Consumption | size caps, pagination limits, cursors, quotas, spending limits |
| A customer's token deletes users | API5 Broken Function Level Authorization (BFLA) | roles per function, deny by default |
| A bot buys all 100 phones with valid requests | API6 Unrestricted Access to Sensitive Business Flows | business flows, bot signals, human checks |
| A photo URL reads cloud keys and an admin page | API7 Server Side Request Forgery (SSRF) | URL parser, allowlists, no redirects |
| An error page prints the database password | API8 Security Misconfiguration | debug off, generic errors, Cache-Control, hardening |
| APIs nobody knew were running | API9 Improper Inventory Management | inventory, shadow and zombie APIs, versioning, retirement |
| A partner's data marks every order paid | API10 Unsafe Consumption of APIs | validate third-party data, parameterise, TLS, redirects |
| Bad requests reach our code at all | (defence in depth) | API gateway, WAF, schema validation with OpenAPI |
| One GraphQL query asks for a trillion rows | API4 again, for GraphQL | depth limits, cost (complexity) limits, introspection off |
Basic words first
- An API (application programming interface) is the door one program uses to talk to another. Example: the shop's mobile app sends
GET /api/ordersto the server and gets your orders back as JSON. - An endpoint is one address of an API plus a method, e.g.
GET /api/ordersorDELETE /api/admin/users. - An HTTP method (episode 21) says what you want to do:
GETreads,POSTcreates,PUT/PATCHchange,DELETEremoves. - A status code is the server's short answer:
200OK,400bad request,401not logged in,403forbidden,404not found,429too many requests,500server error. - The OWASP API Security Top 10 is a list of the ten most critical API security risks from OWASP, the Open Worldwide Application Security Project. The 2023 edition is the second edition, released four years after the first (2019). Its ten items: API1 Broken Object Level Authorization, API2 Broken Authentication, API3 Broken Object Property Level Authorization, API4 Unrestricted Resource Consumption, API5 Broken Function Level Authorization, API6 Unrestricted Access to Sensitive Business Flows, API7 Server Side Request Forgery, API8 Security Misconfiguration, API9 Improper Inventory Management, API10 Unsafe Consumption of APIs. API6 and API10 were new in 2023.
API4: Unrestricted Resource Consumption
OWASP: "Satisfying API requests requires resources such as network bandwidth, CPU, memory, and storage." Some requests also cost money, because the API calls a paid third-party service such as an SMS gateway. Unrestricted resource consumption means a client can make the API use as much of these as it likes: a huge page of results, a giant upload, thousands of paid text messages. The result is a denial of service (real users can't get in) or a big bill.
- Pagination means sending results one page at a time (e.g. 50 orders) instead of all of them. Real-life example: a waiter brings one plate at a time, not the whole kitchen.
- A pagination limit (page-size cap) is the largest page the server will send, whatever the client asks for.
?limit=1000000becomes 50. - A cursor is a pointer to where the next page starts (here simply a position; real APIs often use an opaque string). The response includes
"next", and the client sends it back to get the next page. - A quota is the most a client may use in a period, e.g. 5 OTP texts per phone number per day. Real-life example: a ration card gives 5 kg of rice a month however often you visit.
- Rate limiting (episode 48) limits how often a client may call, e.g. 10 requests a minute per IP address. A quota limits how much in total over a longer period.
- A spending limit (or billing alert) with every paid provider stops a runaway bill even if the other limits fail.
OWASP's API4 scenarios include a forgot-password SMS flow called "tens of thousands of times", and its fixes: maximum sizes on all parameters and payloads, rate limiting, limits on how often one client can run one operation (such as OTP validation or password recovery), server-side validation of the parameters that control how many records are returned, and spending limits.
Demo 1: one request, 24 MB
# GET /api/orders?limit=... and POST /api/otp (sends a paid SMS)
import json
ORDERS = [{"id": i, "item": "masala chai", "rs": 20}
for i in range(1, 500_001)] # half a million orders
SMS_RS = 0.25 # what each SMS costs us
def orders_v1(limit): # trusts the client
return json.dumps(ORDERS[:limit])
def orders_v2(limit, cursor=0): # a page at a time
limit = max(1, min(limit, 50)) # server-side cap
page = ORDERS[cursor:cursor + limit]
nxt = cursor + limit if cursor + limit < len(ORDERS) else None
return json.dumps({"items": page, "next": nxt})
print(f"v1 limit=1000000 -> {len(orders_v1(1_000_000)):,} bytes")
print(f"v2 limit=1000000 -> {len(orders_v2(1_000_000)):,} bytes")
QUOTA = 5 # OTP SMS per number per day
sent = {}
def otp_v2(phone):
if sent.get(phone, 0) >= QUOTA: return False
sent[phone] = sent.get(phone, 0) + 1; return True
print(f"v1: 100,000 OTP requests cost Rs {100_000 * SMS_RS:,.0f}")
ok = sum(otp_v2("98xxxxxx01") for _ in range(100_000))
print(f"v2: {ok} SMS sent, cost Rs {ok * SMS_RS:,.2f}")
Real output:
v1 limit=1000000 -> 24,388,895 bytes
v2 limit=1000000 -> 2,264 bytes
v1: 100,000 OTP requests cost Rs 25,000
v2: 5 SMS sent, cost Rs 1.25
Why it failed: the client chose the size of the work. Fix: caps on the server for every size (page, string, array, upload), pagination with a cursor, quotas per operation, rate limits, and spending limits.
API5: Broken Function Level Authorization (BFLA)
- Authorization (episode 30) decides what an authenticated user may do.
- Object level authorization (API1, episode 49) asks: which record may you touch? Your hotel card opens room 204 but not 205.
- Function level authorization asks: which action may you call at all? A guest's card should never open the manager's office.
- BFLA happens when the server checks only "are you logged in?" and not "may your role call this function?". OWASP: exploitation means sending "legitimate API calls to an API endpoint that they should not have access to", for example by changing
GETtoDELETE, or guessing/api/admin/.... - A role is a named group of permissions, e.g.
customeroradmin(role-based access control, episode 30). - Deny by default: anything not explicitly allowed is refused. OWASP: "The enforcement mechanism(s) should deny all access by default, requiring explicit grants to specific roles for access to every function."
Demo 2: a customer calls admin functions
# Which FUNCTIONS may each user call? (ep 49 asked: which OBJECTS?)
USERS = {"tok-neha": {"name": "neha", "role": "customer"},
"tok-asha": {"name": "asha", "role": "admin"}}
def call_v1(token, method, path): # only checks: logged in?
if token not in USERS: return 401
return 200
RULES = {("GET", "/api/orders"): {"customer", "admin"},
("GET", "/api/admin/users"): {"admin"},
("DELETE", "/api/admin/users"): {"admin"}}
def call_v2(token, method, path):
user = USERS.get(token)
if user is None: return 401 # who are you?
allowed = RULES.get((method, path), set()) # unknown -> nobody
return 200 if user["role"] in allowed else 403
tests = [("tok-neha", "GET", "/api/orders"),
("tok-neha", "DELETE", "/api/admin/users"),
("tok-neha", "PUT", "/api/orders"),
("tok-asha", "DELETE", "/api/admin/users")]
for t in tests:
print(f"{t[1]:6} {t[2]:17} as {USERS[t[0]]['name']}:",
"v1", call_v1(*t), " v2", call_v2(*t))
Real output:
GET /api/orders as neha: v1 200 v2 200
DELETE /api/admin/users as neha: v1 200 v2 403
PUT /api/orders as neha: v1 200 v2 403
DELETE /api/admin/users as asha: v1 200 v2 200
Why it failed: hiding the admin button in the app is not protection; the server must check the role for every function. Fix: one central rule table (or an admin base controller every admin route inherits), deny by default, and tests that call every admin route as a normal user and expect 403.
API6: Unrestricted Access to Sensitive Business Flows
- A business flow is a sequence of steps the business depends on: buying, booking, signing up, posting a comment, using a referral code.
- A flow is sensitive when using it too much, or automatically, hurts the business: bots buying all stock to resell, fake sign-ups farming referral credit, bulk booking and cancelling.
- API6 is when such a flow is exposed "without appropriately restricting the access to it". There may be no code bug at all: every single request is valid. Real-life example: Tatkal train tickets open at 10:00 and scripts book the seats in seconds through the normal pages.
- A headless browser is a browser run by a program, with no screen; bots use them.
- Device fingerprinting recognises the kind of device and browser from many small signals, to deny unexpected clients such as headless browsers.
- Human detection checks that a person is present, e.g. a CAPTCHA (episode 48).
- Non-human patterns: OWASP's example is going from "add to cart" to "complete purchase" in less than one second.
Demo 3: a bot buys the whole sale
# Diwali flash sale: 100 phones. Each request: (account, device, seconds
# between "add to cart" and "buy"). The API itself has no bug at all.
import random
random.seed(7)
bot = [(f"bot{i}", "headless", 0.2) for i in range(300)] # 300 accounts
people = [(f"user{i}", "phone", random.uniform(8, 60))
for i in range(1000)]
queue = bot[:150] + people[:400] + bot[150:] + people[400:] # bot is fast
def sale(requests, check):
stock, bought = 100, {"bot": 0, "people": 0}
for acct, device, secs in requests:
if stock == 0: break
if check and (device == "headless" or secs < 1):
continue # looks automated: challenge it
stock -= 1
bought["bot" if acct.startswith("bot") else "people"] += 1
return bought
print("v1 first come, first served:", sale(queue, check=False))
print("v2 with bot checks: ", sale(queue, check=True))
Real output:
v1 first come, first served: {'bot': 100, 'people': 0}
v2 with bot checks: {'bot': 0, 'people': 100}
Why it failed: the harm was speed and scale, not a bug. Fix: first, the business decides which flows are sensitive; then engineering layers protections: device fingerprinting, human checks, non-human-pattern detection, limits per account, card, phone and delivery address, and stricter access for machine-to-machine (B2B) APIs. Real bots are better at hiding than our toy one, so no single check is enough.
API7: Server Side Request Forgery (SSRF)
SSRF (episode 43) happens "when an API is fetching a remote resource without validating the user-supplied URL". The server makes the request from inside the network, so it can reach places the attacker can't, "even when protected by a firewall or a VPN". Real-life example: an office runner with a staff badge fetches a parcel from "the locked records room" because you wrote that address on the slip.
- The cloud instance metadata service at
169.254.169.254gives a cloud server information about itself, including temporary credentials (episode 43; IMDSv2 adds a session token). localhost(127.0.0.1) means "this same machine": internal admin panels often listen there.- In a URL, anything before
@in the host part is a username, sohttps://img.example.com@localhost:8080/really goes tolocalhost. String checks likeurl.startswith("https://img.example.com")are fooled; a real URL parser is not.
Demo 4: a photo URL that reads secrets
# POST /api/products/9/photo {"url": ...}: the SERVER fetches the URL.
from urllib.parse import urlsplit
FAKE_NET = { # a pretend network, nothing real is contacted
"img.example.com": "<jpeg bytes>",
"169.254.169.254": "role=shop-app key=toy-key-123 secret=toy-secret",
"localhost:8080": "admin panel: 3 users"}
def fetch(url): # stand-in for a real HTTP get
return FAKE_NET.get(urlsplit(url).netloc.split("@")[-1], "404")
def photo_v1(url):
return fetch(url) # any URL at all
ALLOWED = {"img.example.com"}
def photo_v2(url):
u = urlsplit(url) # a real parser, not string tricks
if u.scheme != "https" or u.hostname not in ALLOWED or u.port:
return "rejected: not an allowed image host"
return fetch(url) # + no redirects, image types only
for url in ["https://img.example.com/cup.jpg",
"http://169.254.169.254/latest/meta-data/",
"https://img.example.com@localhost:8080/"]:
print(url)
print(" v1:", photo_v1(url)); print(" v2:", photo_v2(url))
Real output:
https://img.example.com/cup.jpg
v1: <jpeg bytes>
v2: <jpeg bytes>
http://169.254.169.254/latest/meta-data/
v1: role=shop-app key=toy-key-123 secret=toy-secret
v2: rejected: not an allowed image host
https://img.example.com@localhost:8080/
v1: admin panel: 3 users
v2: rejected: not an allowed image host
Fix (OWASP API7): isolate the fetching mechanism in its own network; allowlist remote origins, URL schemes and ports, and accepted media types; "Disable HTTP redirections."; "Use a well-tested and maintained URL parser"; validate all client input; "Do not send raw responses to clients." Real code must also check the IP address the host name resolves to (DNS rebinding, episode 43) and use IMDSv2.
API8: Security Misconfiguration
Security misconfiguration means the code may be fine but a setting is wrong, anywhere in the stack: the app, the web server, the cloud. OWASP lists, among others: missing hardening or patches, "Unnecessary features are enabled (e.g. HTTP verbs, logging features)", missing TLS (episode 22), "Security or cache control directives are not sent to clients", a missing or wrong CORS policy (episode 36), and "Error messages include stack traces".
- Debug mode is a developer setting that shows full error details. Left on in production, it tells attackers how the app works.
- A stack trace is the list of functions that were running when a program crashed, with file names and line numbers.
Cache-Control: no-storetells browsers and proxies never to keep a copy of the response. OWASP's example: private messages cached on disk because the header was missing.- Hardening means turning off everything not needed and locking settings down; a hardening process does it the same way every time, and an automated check confirms it stays that way (episode 46).
Demo 5: an error page that leaks
# GET /api/messages/7 -> our handler crashes. What does the client see?
import traceback, secrets
CONFIG = {"debug": True, "db": "postgres://shop:Pa55w0rd@10.0.0.5/shop"}
def handler():
return {"messages": []}["msgs"] # a bug: wrong key
def respond_v1(): # debug mode left on in production
try: return 200, {}, handler()
except Exception as e:
where = traceback.extract_tb(e.__traceback__)[-1]
return 500, {}, (f"{e!r} in {where.name}() line {where.lineno}"
f"\nconfig: {CONFIG}")
def respond_v2():
hdrs = {"Cache-Control": "no-store"} # never cache private data
try: return 200, hdrs, handler()
except Exception:
ref = secrets.token_hex(4) # full details go to OUR log only
return 500, hdrs, {"error": "internal error", "ref": ref}
for fn in (respond_v1, respond_v2):
status, headers, body = fn()
print(f"--- {fn.__name__}: {status} {headers}\n{body}")
Real output:
--- respond_v1: 500 {}
KeyError('msgs') in handler() line 6
config: {'debug': True, 'db': 'postgres://shop:Pa55w0rd@10.0.0.5/shop'}
--- respond_v2: 500 {'Cache-Control': 'no-store'}
{'error': 'internal error', 'ref': 'a4c59847'}
Fix: debug off in production; a generic error body with a reference id (details only in your own logs, without secrets, episode 48); Cache-Control: no-store on private data; only the HTTP methods each endpoint needs; TLS everywhere, including between internal services; a strict CORS policy and security headers (episode 41); a schema for every response, including errors; and an automated, repeatable hardening process.
API9: Improper Inventory Management
APIs have many hosts and versions, so OWASP says proper, up-to-date documentation is "highly important". Improper inventory management means you don't know exactly which APIs are running, where, in which version, and who may reach them.
- An API inventory is the team's list of every API host and version: its environment (production, staging, test, development), who should have network access (public, internal, partners), its owner and its retirement date.
- Production is the real system customers use; staging is a copy for final testing; test and development are for building.
- A shadow API is running but was never documented, so nobody protects or watches it: a beta host, a forgotten debug port. Real-life example: a side gate in a housing society that nobody remembers.
- A zombie API is an old version that was retired on paper but still answers. Real-life example: the old gate "closed in March" whose lock was never fitted.
- API versioning means running a new version (
/v2/...) next to the old one (/v1/...) so old apps keep working while they move. Deprecation announces that a version will go away; retirement (sunset) actually turns it off.
OWASP's scenario: a beta host ran the same API without the production rate limiting, so a researcher brute-forced password-reset tokens there and could take over accounts.
Demo 6: shadow and zombie APIs
# Which APIs are REALLY running? Compare the inventory with the traffic.
INVENTORY = { # what the team documented (the OpenAPI files)
("api.shop.example", "v2"): {"env": "prod", "owner": "orders team",
"retire": None},
("api.shop.example", "v1"): {"env": "prod", "owner": "orders team",
"retire": "2026-03-31"}}
SEEN = [ # hosts and versions that answered requests last week
("api.shop.example", "v2", 182_000), ("api.shop.example", "v1", 3_400),
("beta-api.shop.example", "v2", 260), ("10.0.0.7:9000", "debug", 41)]
TODAY = "2026-11-12"
for host, ver, hits in SEEN:
doc = INVENTORY.get((host, ver))
if doc is None:
print(f"SHADOW {host} {ver}: {hits} hits, nobody documented it")
elif doc["retire"] and doc["retire"] < TODAY:
print(f"ZOMBIE {host} {ver}: {hits:,} hits, retired "
f"{doc['retire']} but still answering")
else:
print(f"ok {host} {ver}: {hits:,} hits, owner {doc['owner']}")
Real output:
ok api.shop.example v2: 182,000 hits, owner orders team
ZOMBIE api.shop.example v1: 3,400 hits, retired 2026-03-31 but still answering
SHADOW beta-api.shop.example v2: 260 hits, nobody documented it
SHADOW 10.0.0.7:9000 debug: 41 hits, nobody documented it
Fix (OWASP API9): inventory all API hosts with environment, network access and version; inventory integrated services and their data flows; generate documentation automatically from open standards in the CI/CD pipeline; show docs only to those allowed to use the API; protect all exposed versions, not just the current production one; don't use production data in non-production deployments; give every version a retirement plan, and actually retire it.
API10: Unsafe Consumption of APIs
OWASP: "Developers tend to trust data received from third-party APIs more than user input", so attackers go after a weaker third-party API (one run by another company, e.g. a pincode lookup) and let its data attack you. Unsafe consumption means using that data without validation: injection payloads, huge values, or redirects to the attacker's server. Real-life example: a restaurant trusts its vegetable supplier so much it stops washing the vegetables.
Demo 7: a partner's data attacks our database
# Our API asks a partner's pincode API for the city, then saves it.
import sqlite3, re
def partner_lookup(pincode): # the partner was hacked (toy)
return {"pincode": pincode, "city": "Pune', paid = 1 --"}
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders(id INT, city TEXT, paid INT)")
db.executemany("INSERT INTO orders VALUES(?, '', 0)", [(1,), (2,), (3,)])
def save_v1(order_id, data): # trusts the partner's data
db.execute(f"UPDATE orders SET city = '{data['city']}' "
f"WHERE id = {order_id}")
def save_v2(order_id, data): # validate, then parameterise
city = data.get("city")
if not (isinstance(city, str) and re.fullmatch(r"[A-Za-z .-]{1,40}",
city)):
return print("v2 rejected partner data:", repr(city)[:30])
db.execute("UPDATE orders SET city = ? WHERE id = ?",
(city, order_id))
save_v1(1, partner_lookup("411001"))
print("v1 rows now:", db.execute("SELECT * FROM orders").fetchall())
db.execute("UPDATE orders SET city = '', paid = 0")
save_v2(1, partner_lookup("411001"))
print("v2 rows now:", db.execute("SELECT * FROM orders").fetchall())
Real output:
v1 rows now: [(1, 'Pune', 1), (2, 'Pune', 1), (3, 'Pune', 1)]
v2 rejected partner data: "Pune', paid = 1 --"
v2 rows now: [(1, '', 0), (2, '', 0), (3, '', 0)]
The v1 query became UPDATE orders SET city = 'Pune', paid = 1 --' WHERE id = 1. The -- starts an SQL comment, so the WHERE clause vanished and every order was marked paid (SQL injection, episode 38).
Fix (OWASP API10): assess a provider's API security before integrating; use TLS for all API interactions; "Always validate and properly sanitize data received from integrated APIs before using it"; parameterised queries; size and time limits on what you accept; keep an allowlist of locations their API may redirect you to: "do not blindly follow redirects."
The front door: API gateway, WAF and schema validation
- An API gateway is one front door in front of all your APIs. It checks tokens, applies rate limits and quotas, logs requests, and routes each request to the right service. Real-life example: a mall's single entrance with a guard who checks passes and counts people.
- A web application firewall (WAF) inspects HTTP requests and blocks known attack patterns (e.g. a typical SQL injection string). Real-life example: the mall's metal detector. It can't know your business rules (it would not stop BFLA or a bot buying stock with valid requests), so it is one layer, never the fix.
- Schema validation checks that each request has exactly the allowed shape: field names, types, lengths, ranges, no extra fields. Real-life example: a bank deposit slip with fixed boxes.
- OpenAPI ("the OpenAPI Specification") "is a standard for describing an API", written in YAML or JSON (current versions 3.1 and 3.2). It lists every endpoint, parameter, request and response with their types, so one file can drive the documentation, the inventory (API9) and validation at the gateway.
additionalProperties: falsein a schema means "no fields other than the listed ones", which also blocks mass assignment (episode 49).
Demo 8: schema validation at the gateway
# The OpenAPI file says what POST /api/orders accepts. The gateway checks
# every request against it BEFORE our code runs.
SCHEMA = {"type": "object", "additionalProperties": False,
"required": ["item", "qty"],
"properties": {"item": {"type": "string", "maxLength": 40},
"qty": {"type": "integer", "minimum": 1,
"maximum": 10}}}
TYPES = {"string": str, "integer": int, "object": dict}
def validate(body, s=SCHEMA):
if type(body) is not TYPES[s["type"]]: return "wrong type"
for k in s.get("required", []):
if k not in body: return f"missing {k}"
for k, v in body.items():
p = s["properties"].get(k)
if p is None: return f"unknown field {k!r}" # no extras
if type(v) is not TYPES[p["type"]]: return f"{k}: wrong type"
if len(str(v)) > p.get("maxLength", 10**9): return f"{k}: too long"
if not p.get("minimum", v) <= v <= p.get("maximum", v):
return f"{k}: out of range"
return "ok"
for body in [{"item": "chai", "qty": 2}, {"item": "chai", "qty": -5},
{"item": "chai", "qty": 2, "price": 1},
{"item": "x" * 5000, "qty": 1}, {"item": "chai", "qty": "2"}]:
print(f"{str(body)[:38]:40} -> {validate(body)}")
Real output:
{'item': 'chai', 'qty': 2} -> ok
{'item': 'chai', 'qty': -5} -> qty: out of range
{'item': 'chai', 'qty': 2, 'price': 1} -> unknown field 'price'
{'item': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx -> item: too long
{'item': 'chai', 'qty': '2'} -> qty: wrong type
In real projects use a maintained validator (for example the jsonschema package in Python, or your gateway's built-in OpenAPI validation) rather than writing your own.
GraphQL: depth limits, cost (complexity) limits and introspection
- GraphQL (episode 49) is a kind of API where the client sends one query asking for exactly the fields it wants, nested inside each other:
{ me { friends { name } } }. - Query depth is how many levels deep a query nests. A depth limit rejects queries deeper than, say, 5 (the GraphQL.js docs show
depthLimit(10)). - Query cost, also called query complexity, is an estimate of how much work a query will take, worked out before running it. Each field has a cost, and list fields multiply it. A cost limit rejects queries over a budget.
- Rate limits count requests, so one expensive request slips through them; batching many operations into one request does the same (an OWASP API4 scenario), so cap batch size too.
- Introspection is GraphQL's built-in way for a client to ask the API to describe itself, using special fields such as
__schema: every type and field. It is very useful while building, but in production it hands attackers a map. The GraphQL.js docs: "You can disable introspection in production, or only for unauthenticated users." The GraphQL golden path guide adds that "First-party APIs rarely need introspection in production", and warns that "Disabling introspection can break tooling and codegen", so publish the schema to your own developers another way.
Demo 9: depth and cost limits
# GraphQL: ONE request can ask for friends of friends of friends...
import re
def shape(query): # depth, and how many rows it asks for
depth = rows = 0; level = []; mult = 1
for tok in re.findall(r"\w+|[{}]", query):
if tok == "{":
level.append(mult); depth = max(depth, len(level))
elif tok == "}":
mult = level.pop()
elif tok == "friends": # every user has ~100 friends
mult = level[-1] * 100; rows += mult
return depth, rows
def run(query, prod=True, max_depth=5, max_rows=10_000):
if prod and "__schema" in query:
return "rejected: introspection is off in production"
depth, rows = shape(query)
if depth > max_depth: return f"rejected: depth {depth} > {max_depth}"
if rows > max_rows: return f"rejected: cost {rows:,} > {max_rows:,}"
return f"ok (depth {depth}, {rows:,} rows)"
def nest(n): return "{ me " + "{ friends " * n + "{ name" + " }" * (n + 2)
d, rows = shape(nest(6))
print(nest(6)); print(f"depth {d}, rows asked for: {rows:,}")
for q in (nest(1), nest(3), nest(6), "{ __schema { types { name } } }"):
print(f"{q[:26]:28} -> {run(q)}")
Real output:
{ me { friends { friends { friends { friends { friends { friends { name } } } } } } } }
depth 8, rows asked for: 1,010,101,010,100
{ me { friends { name } } -> ok (depth 3, 100 rows)
{ me { friends { friends { -> rejected: cost 1,010,100 > 10,000
{ me { friends { friends { -> rejected: depth 8 > 5
{ __schema { types { name -> rejected: introspection is off in production
Three levels of friends passes the depth limit but still asks for about a million rows, which is why you need both a depth limit and a cost limit.
The whole chain
- One request built 24 MB, and OTPs cost Rs 25,000 → server-side caps, pagination with a cursor, quotas, rate and spending limits (API4).
- A customer called admin functions → roles per function, deny by default (API5).
- A bot bought the whole sale with valid requests → protect sensitive business flows (API6).
- A photo URL reached cloud keys and an admin page → URL parser, allowlists, no redirects (API7).
- An error page leaked the password → debug off, generic errors, no-store, hardening (API8).
- Forgotten APIs kept answering → inventory, versions with end dates, protect every version (API9).
- A partner's data marked every order paid → validate third-party data, parameterise (API10). - At the front door: an API gateway, a WAF and OpenAPI schema validation; for GraphQL, depth and cost limits and no introspection in production.
Common mistakes (and what they cause)
| Mistake | Real message / result | Why it's wrong | Fix |
|---|---|---|---|
ORDERS[:limit] with the client's limit |
v1 limit=1000000 -> 24,388,895 bytes |
the client picks the work | min(limit, 50) + cursor |
| No quota on a paid action | v1: 100,000 OTP requests cost Rs 25,000 |
money and SMS spam | per-number quota, rate limit, spending limit |
| Only checking "logged in" | DELETE /api/admin/users as neha: v1 200 |
no role check per function | deny-by-default rule table |
| Unknown methods allowed | PUT /api/orders as neha: v1 200 |
extra verbs reach code | only the methods each route needs |
| First come, first served for scarce stock | v1 first come, first served: {'bot': 100, 'people': 0} |
bots win every time | bot signals, human checks, per-account limits |
| Fetching any user URL | v1: role=shop-app key=toy-key-123 secret=toy-secret |
server reaches inside | urlsplit + host/scheme/port allowlist |
startswith checks on URLs |
https://img.example.com@localhost:8080/ reached admin panel: 3 users |
@ makes the start a username |
a real URL parser, check hostname |
| Debug mode in production | config: {'debug': True, 'db': 'postgres://shop:Pa55w0rd@10.0.0.5/shop'} |
secrets in errors | generic error + reference id |
| Old version never turned off | ZOMBIE api.shop.example v1: 3,400 hits ... |
unprotected old code | retire for real, protect all versions |
| Undocumented hosts | SHADOW beta-api.shop.example v2: 260 hits ... |
nobody watches them | inventory from traffic + OpenAPI |
| Trusting a partner's data | v1 rows now: [(1, 'Pune', 1), (2, 'Pune', 1), (3, 'Pune', 1)] |
partner data is input | validate + parameterise |
| Only a depth limit in GraphQL | nest(3) passes depth 5 but asks for 1,010,100 rows |
shallow can be expensive | depth and cost limits |
| Introspection on in production | (the whole schema to anyone) | a free map for attackers | off for production or unauthenticated users |
Mini project: a tiny API gateway
A gateway that checks, in order: the route is in the inventory, the token, the role (deny by default), the body against a schema, a daily quota, and a page-size cap.
# Mini project: a tiny API gateway in front of the shop's orders API.
# Order of checks: known route -> token -> role -> schema -> quota -> handler.
import json
USERS = {"tok-neha": ("neha", "customer"), "tok-asha": ("asha", "admin")}
ROUTES = { # the inventory: anything not listed here does not exist
("GET", "/v2/orders"): {"roles": {"customer", "admin"}, "schema": None},
("POST", "/v2/orders"): {"roles": {"customer"},
"schema": {"item": (str, 40), "qty": (int, 10)}},
("DELETE", "/v2/admin/users"): {"roles": {"admin"}, "schema": None}}
QUOTA_PER_DAY, used = 3, {}
ORDERS = [{"id": i, "item": "chai"} for i in range(1, 1001)]
def check_body(body, schema):
if set(body) != set(schema): return "fields must be " + ", ".join(schema)
for k, (typ, limit) in schema.items():
v = body[k]
if type(v) is not typ: return f"{k}: wrong type"
if (len(v) if typ is str else v) > limit or (typ is int and v < 1):
return f"{k}: out of range"
return None
def gateway(method, path, token=None, body=None, limit=50, cursor=0):
route = ROUTES.get((method, path))
if route is None: return 404, "unknown route (not in inventory)"
if token not in USERS: return 401, "who are you?"
name, role = USERS[token]
if role not in route["roles"]: return 403, "forbidden for " + role
if route["schema"]:
err = check_body(body or {}, route["schema"])
if err: return 400, err
used[name] = used.get(name, 0) + 1
if used[name] > QUOTA_PER_DAY: return 429, "daily quota used up"
if path == "/v2/orders" and method == "GET":
limit = max(1, min(limit, 50))
page = ORDERS[cursor:cursor + limit]
return 200, {"count": len(page), "next": cursor + limit}
return 200, "done"
for args in [("GET", "/v1/orders", "tok-neha"),
("GET", "/v2/orders", None),
("DELETE", "/v2/admin/users", "tok-neha"),
("POST", "/v2/orders", "tok-neha", {"item": "chai", "qty": 99}),
("POST", "/v2/orders", "tok-neha", {"item": "chai", "qty": 2}),
("GET", "/v2/orders", "tok-neha", None, 1_000_000),
("GET", "/v2/orders", "tok-neha"),
("GET", "/v2/orders", "tok-neha")]:
status, out = gateway(*args)
print(f"{args[0]:6} {args[1]:16} -> {status} {json.dumps(out)}")
Real output:
GET /v1/orders -> 404 "unknown route (not in inventory)"
GET /v2/orders -> 401 "who are you?"
DELETE /v2/admin/users -> 403 "forbidden for customer"
POST /v2/orders -> 400 "qty: out of range"
POST /v2/orders -> 200 "done"
GET /v2/orders -> 200 {"count": 50, "next": 50}
GET /v2/orders -> 200 {"count": 50, "next": 50}
GET /v2/orders -> 429 "daily quota used up"
The retired /v1 route answers 404 because it isn't in the inventory, the customer can't reach the admin function, a bad body never reaches the handler, the request for a million orders gets 50, and the fourth call of the day is refused with 429 Too Many Requests. Extend it: add a per-IP rate limit and a next: null on the last page.
Practice
- Add a per-IP rate limit to
otp_v2, so a script that cycles through 1,000 different phone numbers from one IP is still slowed down. - Give
shape()a cost per field, where list fields (friends,orders) multiply the cost of everything inside them. - Make
validate()check nested objects and arrays (an order with a list of lines). - For each, name the OWASP API risk: (a)
GET /api/export?rows=alltakes the database down; (b) a referral code is farmed by 5,000 fake sign-ups; (c)/api/v1/still runs without the new rate limit; (d)POST /api/admin/refundworks with a customer token; (e) a webhook test returns the response fromhttp://10.0.0.5/.
Practice 1 solution
# Practice 1 solution: OTP quota per phone number AND a rate limit per IP
PER_PHONE_PER_DAY, PER_IP_PER_MIN = 5, 10
sent_phone, ip_hits = {}, {}
def otp_v3(phone, ip, now):
window = [t for t in ip_hits.get(ip, []) if now - t < 60] # last 60 s
if len(window) >= PER_IP_PER_MIN:
ip_hits[ip] = window; return "429 slow down (IP)"
ip_hits[ip] = window + [now]
if sent_phone.get(phone, 0) >= PER_PHONE_PER_DAY:
return "429 daily SMS limit for this number"
sent_phone[phone] = sent_phone.get(phone, 0) + 1
return "SMS sent"
# one script, one IP, cycling through 1,000 different phone numbers
results = [otp_v3(f"98000{i:05}", "203.0.113.9", now=i * 0.1)
for i in range(1000)]
print("sent:", results.count("SMS sent"), "of", len(results))
print("first refusal:", next(r for r in results if r != "SMS sent"))
Real output:
sent: 20 of 1000
first refusal: 429 slow down (IP)
The script ran for 100 seconds, so it got two windows of 10 messages. A real attacker uses many IPs, so keep the per-number quota, add a global spending limit and an alert on SMS volume.
Practice 2 solution
# Practice 2 solution: a cost per field, and list fields multiply the cost
import re
LIST_SIZE = {"friends": 100, "orders": 20} # how many items a list returns
def cost(query):
total, mult = 0, [1]
tokens = re.findall(r"\w+|[{}]", query)
for i, tok in enumerate(tokens):
if tok == "{":
prev = tokens[i - 1] if i else ""
mult.append(mult[-1] * LIST_SIZE.get(prev, 1))
elif tok == "}":
mult.pop()
else:
total += mult[-1] # each field costs 1 per item
return total
for q in ["{ me { name } }",
"{ me { name orders { id total } } }",
"{ me { friends { name orders { id total } } } }"]:
print(f"{cost(q):>7,} {q}")
Real output:
2 { me { name } }
43 { me { name orders { id total } } }
4,202 { me { friends { name orders { id total } } } }
Real GraphQL servers use the schema (and arguments such as first: 20) to know list sizes; libraries for query cost analysis exist for most GraphQL servers.
Practice 3 solution
# Practice 3 solution: validate() that also checks nested objects and arrays
def validate(v, s, path="body"):
t = s["type"]
if t == "object":
if type(v) is not dict: return f"{path}: wrong type"
for k in s.get("required", []):
if k not in v: return f"{path}.{k}: missing"
for k, x in v.items():
if k not in s["properties"]: return f"{path}.{k}: unknown field"
err = validate(x, s["properties"][k], f"{path}.{k}")
if err: return err
elif t == "array":
if type(v) is not list: return f"{path}: wrong type"
if len(v) > s.get("maxItems", 100): return f"{path}: too many items"
for i, x in enumerate(v):
err = validate(x, s["items"], f"{path}[{i}]")
if err: return err
elif t == "integer":
if type(v) is not int: return f"{path}: wrong type"
if not s.get("minimum", v) <= v <= s.get("maximum", v):
return f"{path}: out of range"
elif t == "string":
if type(v) is not str: return f"{path}: wrong type"
if len(v) > s.get("maxLength", 1000): return f"{path}: too long"
return None
LINE = {"type": "object", "required": ["item", "qty"],
"properties": {"item": {"type": "string", "maxLength": 40},
"qty": {"type": "integer", "minimum": 1, "maximum": 10}}}
ORDER = {"type": "object", "required": ["lines"],
"properties": {"lines": {"type": "array", "maxItems": 20, "items": LINE}}}
for body in [{"lines": [{"item": "chai", "qty": 2}]},
{"lines": [{"item": "chai", "qty": 2}, {"item": "vada", "qty": 0}]},
{"lines": [{"item": "chai", "qty": 1, "price": 0}]},
{"lines": [{"item": "chai", "qty": 1}] * 500}]:
print(validate(body, ORDER) or "ok")
Real output:
ok
body.lines[1].qty: out of range
body.lines[0].price: unknown field
body.lines: too many items
maxItems is the array version of a page-size cap (API4).
Practice 4 answers
(a) API4 Unrestricted Resource Consumption. (b) API6 Unrestricted Access to Sensitive Business Flows. (c) API9 Improper Inventory Management (a zombie version). (d) API5 Broken Function Level Authorization. (e) API7 Server Side Request Forgery.
Quick quiz
# api.shop.example/v2 -> rate limit 5 OTP tries
# api.shop.example/v1 -> retired in March,
# still running, no limit
POST /v1/verify-otp (tried 1,000,000 times)
Which API risk is the root cause? A: API5 broken function level authorization. B: API9 improper inventory management. C: API7 server side request forgery. D: API10 unsafe consumption of APIs.
Answer
B. The attacker skips the protected v2 and uses a retired v1 that was never turned off: a zombie API. Inventory every version, protect every exposed version the same way, and really retire old ones. (The missing limit is also API4, but the root cause is the forgotten version.)
Interview questions
- BOLA vs BFLA? BOLA (API1): you may call the function but not on this object (another user's order). BFLA (API5): you may not call this function at all (a customer calling an admin delete). Fix both on the server, deny by default.
- How do you stop an API from being used to exhaust resources? Server-side caps on every size (page, payload, string, array, upload), pagination with cursors, rate limits per client and per operation, quotas, timeouts, container limits on CPU and memory, and spending limits with paid providers.
- What makes a business flow "sensitive", and how do you protect it without a code fix? Its excessive or automated use harms the business (scalping, fake sign-ups). Identify such flows with the business, then layer device fingerprinting, human checks, non-human-pattern detection, and per-account/card/address limits.
- What is SSRF in an API and how do you prevent it? The server fetches a user-supplied URL and reaches internal services or metadata. Isolate the fetcher, allowlist hosts, schemes, ports and media types, disable redirects, use a real URL parser, check resolved IPs, never return raw responses.
- Give five API security misconfigurations. Debug mode/stack traces in errors, unneeded HTTP methods, no TLS between services, missing
Cache-Controlon private data, permissive CORS, default credentials, unpatched components. - What are shadow and zombie APIs, and how do you find them? Shadow: running but undocumented. Zombie: retired but still running. Compare traffic logs and DNS/cloud asset lists with the OpenAPI inventory; give every version an owner and an end date.
- Why is data from a third-party API dangerous? It is input from outside your trust boundary; a compromised partner can send injection payloads, huge values or redirects. Validate, parameterise, use TLS, don't follow redirects blindly.
- What does an API gateway do, and is a WAF enough? A gateway centralises authentication, rate limits, quotas, logging, routing and schema validation. A WAF blocks known attack patterns but can't understand business logic or authorization, so it is one layer, never the only defence.
- How do you secure a GraphQL API? Depth limits and cost (complexity) analysis, limits on batching and aliases, pagination on list fields, authorization in resolvers, and introspection off in production (or only for authenticated developers).
Glossary
| Term | Meaning, with an example |
|---|---|
| API | The door one program uses to talk to another, e.g. the app calling GET /api/orders. |
| Endpoint | One API address plus method, e.g. DELETE /api/admin/users. |
| HTTP method / verb | What a request wants to do: GET, POST, PUT, DELETE (episode 21). |
| Status code | The server's short answer, e.g. 403 forbidden, 429 too many requests. |
| OWASP API Security Top 10 (2023) | OWASP's list of the ten most critical API risks; second edition, after 2019. |
| API4 Unrestricted Resource Consumption | A client can make the API use unlimited bandwidth, CPU, memory, storage or paid services. |
| Resource | Something a request uses up: bandwidth, CPU time, memory, storage, money. |
| Denial of service | Making a service unavailable to its real users. |
| Pagination | Sending results one page at a time, e.g. 50 orders plus a pointer to the next page. |
| Pagination limit (page-size cap) | The largest page the server sends, whatever the client asks, e.g. ?limit=1000000 → 50. |
| Cursor | A pointer to where the next page starts, returned as next. |
| Quota | The most a client may use in a period, e.g. 5 OTP texts per number per day. |
| Rate limiting | Limiting how often a client may call, e.g. 10 requests a minute per IP. |
| Spending limit | A cap (or alert) on what a paid provider may bill you. |
| OTP | One-time password, e.g. a 6-digit code sent by SMS (episode 29). |
| API5 BFLA | Broken Function Level Authorization: a user can call a function their role must not, e.g. a customer deleting users. |
| Role | A named set of permissions, e.g. customer, admin. |
| Deny by default | Anything not explicitly allowed is refused. |
| API6 Unrestricted Access to Sensitive Business Flows | A business flow that hurts the business when automated is left unprotected, e.g. bots buying all stock. |
| Business flow | A sequence of steps the business depends on: buying, booking, signing up. |
| Headless browser | A browser run by a program with no screen, used by bots. |
| Device fingerprinting | Recognising the kind of device and browser from many signals, to deny unexpected clients. |
| CAPTCHA | A test easy for people and hard for bots (episode 48). |
| API7 SSRF | Server side request forgery: the server fetches a user-chosen URL and reaches internal places. |
| Cloud metadata service | 169.254.169.254: tells a cloud server about itself, including temporary keys (episode 43). |
| URL parser | Code that splits a URL into scheme, user, host, port and path correctly, e.g. urllib.parse.urlsplit. |
| Allowlist | A list of the only things allowed, e.g. the one image host we fetch from. |
| API8 Security Misconfiguration | A wrong or missing setting anywhere in the API stack, e.g. debug mode in production. |
| Debug mode | A developer setting that shows full error details. |
| Stack trace | The list of functions running when a program crashed, with files and lines. |
| Cache-Control: no-store | A response header telling browsers and proxies never to keep a copy. |
| CORS | Cross-origin resource sharing: rules for which websites may call an API from a browser (episode 36). |
| TLS | The encryption behind HTTPS (episode 22). |
| Hardening | Turning off what isn't needed and locking settings down, the same way every time. |
| API9 Improper Inventory Management | Not knowing exactly which API hosts and versions run, where, and who may reach them. |
| API inventory | The list of every API host and version with environment, access, owner and end date. |
| Environment | Where a copy runs: production (real users), staging, test, development. |
| Shadow API | An API that runs but was never documented, e.g. a forgotten beta host. |
| Zombie API | A retired version that still answers, e.g. /v1 "retired" in March. |
| API versioning | Running /v2 next to /v1 so old clients keep working while they move. |
| Deprecation / retirement | Announcing a version will go away / actually turning it off. |
| API10 Unsafe Consumption of APIs | Trusting data from third-party APIs without validating it. |
| Third-party API | An API run by another company, e.g. a pincode lookup. |
| SQL injection | Data that changes the meaning of an SQL query (episode 38). |
| Parameterised query | SQL with ? placeholders so data is never code. |
| API gateway | One front door for all APIs: auth, rate limits, quotas, logging, routing, validation. |
| WAF | Web application firewall: blocks known attack patterns in HTTP traffic; one layer, not the fix. |
| Schema validation | Checking a request has exactly the allowed fields, types, lengths and ranges. |
| OpenAPI | A standard for describing an API in YAML or JSON (versions 3.1, 3.2). |
| additionalProperties: false | A schema rule: no fields other than the listed ones. |
| Mass assignment | Copying every client field into an object, so "role": "admin" sneaks in (episode 49). |
| GraphQL | An API style where one query asks for exactly the nested fields it wants. |
| Query depth / depth limit | How many levels a query nests / rejecting queries deeper than a limit. |
| Query cost (complexity) / cost limit | An estimate of a query's work before running it / rejecting queries over a budget. |
| Batching | Many operations in one request; can slip past request-count rate limits. |
| Introspection | GraphQL's built-in self-description (__schema); turn it off in production. |
Summary
- API4: every request costs something. Cap sizes on the server, paginate with cursors, set quotas, rate limits and spending limits.
- API5: logged in is not allowed. Check the role for every function and deny by default.
- API6: valid requests can still harm the business. Protect sensitive flows with bot signals, human checks and limits.
- API7: never fetch a user's URL blindly. Parse it, allowlist host, scheme, port and type, and don't follow redirects.
- API8: good code with bad settings is still vulnerable. Debug off, generic errors,
no-store, TLS, strict CORS, hardening. - API9: you can't protect what you don't know. Keep an inventory, give every version an end date, and retire for real.
- API10: partner data is input. Validate it, parameterise it, use TLS, don't follow redirects blindly.
- Front door: an API gateway, a WAF and OpenAPI schema validation are layers; GraphQL needs depth and cost limits and no introspection in production.
Next episode: Secure coding fundamentals across languages: trust boundaries, taint, input validation, canonicalisation, output encoding, safe errors, OWASP ASVS, the OWASP Cheat Sheet Series, SEI CERT and the CWE Top 25.