OWASP API Security Top 10 2023 and Rate Limiting
Most of what a modern application does happens through APIs: the single-page front end, the mobile app, partner integrations and internal microservices all talk JSON over HTTP. APIs share the web's vulnerabilities, but their shape changes which ones matter most. They expose object ids in every path (so object-level authorization tops the list), return whole objects (so property-level leaks are common), are called by programs rather than people (so missing rate limits hurt more), and multiply faster than anyone documents them (so old, forgotten versions stay online). OWASP publishes a separate API Security Top 10; its current edition is from 2023. This lesson maps each entry to the lessons of this course, then builds the control behind API4, a rate limiter, and runs it against a synthetic burst.
The list, mapped to this course
| # | Category (2023) | In one sentence | Where in this course |
|---|---|---|---|
| API1 | Broken Object Level Authorization | the API serves any object id it is given | IDOR and BOLA |
| API2 | Broken Authentication | weak login, token and session handling | password login, JWT pitfalls, OAuth flaws |
| API3 | Broken Object Property Level Authorization | clients read or write properties they shouldn't (excessive exposure, mass assignment) | mass assignment |
| API4 | Unrestricted Resource Consumption | no limits on requests, sizes, pages, or costly operations (SMS, e-mail, compute) | this lesson |
| API5 | Broken Function Level Authorization | ordinary users reach admin functions | function-level access control |
| API6 | Unrestricted Access to Sensitive Business Flows | automation abuses a legitimate flow (buying all tickets, mass sign-ups, scraping) | business logic |
| API7 | Server Side Request Forgery | the API fetches attacker-chosen URLs | SSRF |
| API8 | Security Misconfiguration | verbose errors, missing headers, permissive CORS, unpatched components | HTTP messages, CORS, headers |
| API9 | Improper Inventory Management | undocumented, old or test API versions still exposed | below |
| API10 | Unsafe Consumption of APIs | trusting data from third-party APIs more than user input | second-order injection, deserialization |
Compared with the 2019 edition, "excessive data exposure" and "mass assignment" merged into API3, injection and "insufficient logging and monitoring" left the list as categories of their own (injection is still a risk, covered by the others and by the web Top 10), and API6, API7 and API10 are new.
API4: a token-bucket rate limiter
A token bucket gives each client a bucket of capacity tokens that refills at rate tokens per second; each request takes one token, and a request that finds the bucket empty gets 429 Too Many Requests with a Retry-After header. It allows short bursts (up to capacity) while capping the average rate. The simulation replays a synthetic log on a virtual clock: a normal user, and a script hammering the login endpoint with 50 requests in 5 seconds.
from collections import defaultdict
class TokenBucket:
def __init__(self, capacity, rate):
self.capacity, self.rate = capacity, rate
self.tokens = defaultdict(lambda: capacity)
self.last = {}
def allow(self, key, now):
if key in self.last:
self.tokens[key] = min(self.capacity, self.tokens[key] + (now - self.last[key]) * self.rate)
self.last[key] = now
if self.tokens[key] >= 1:
self.tokens[key] -= 1
return True, 0
return False, (1 - self.tokens[key]) / self.rate # seconds until the next token
limiter = TokenBucket(capacity=5, rate=0.5) # bursts of 5, then 1 request every 2 s
events = [(t * 1.5, "203.0.113.7") for t in range(8)] # a person: one request every 1.5 s
events += [(1.0 + i * 0.1, "198.51.100.66") for i in range(50)] # a script: 10 requests per second
events.sort()
stats = defaultdict(lambda: {"ok": 0, "429": 0})
first_429 = {}
for now, client in events:
ok, retry = limiter.allow(client, now)
stats[client]["ok" if ok else "429"] += 1
if not ok and client not in first_429:
first_429[client] = (now, retry)
for client, s in stats.items():
extra = f", first 429 at t={first_429[client][0]:.1f}s with Retry-After {first_429[client][1]:.0f}s" if client in first_429 else ""
print(f"{client:15} allowed {s['ok']:2}, refused {s['429']:2}{extra}")203.0.113.7 allowed 8, refused 0
198.51.100.66 allowed 7, refused 43, first 429 at t=1.5s with Retry-After 2s
The person never notices the limiter: a burst allowance of five absorbs their pace. The script got its first five requests through, two more as tokens trickled back during its five seconds, and 43 of its 50 requests were refused with 429 and a Retry-After it can respect or ignore. The key choice is the bucket's key: per source address (shown here) stops one noisy client but not a botnet, per account stops password guessing against one user but not spraying, and per expensive resource (SMS sent per phone number, password resets per e-mail) stops abuse that costs money. Real systems combine several keys and keep the counters in a shared store (Redis) so every server instance sees the same buckets.
API4 is more than request rates
Unrestricted resource consumption also covers: page sizes (?limit=1000000), upload and body sizes, GraphQL query cost (GraphQL lesson), batch endpoints (/batch with 10,000 operations), regular expressions on user input (ReDoS), and third-party costs triggered per request (SMS, e-mail, paid APIs). Each needs its own limit, enforced on the server, and a budget alert on the bill.
API9: knowing what you expose
APIs live longer than their documentation. Detection here is an inventory: an OpenAPI specification generated from the code, compared with what the gateway actually routes and what traffic logs show; scans of your own hosts for /v1/, /beta/, /internal/, /swagger.json, /graphql; and a lifecycle (deprecation date, removal) for every version. An old /api/v1/users/{id} that predates the BOLA fix is as exposed as the day it shipped.
How API weaknesses are detected
- Testing: an authorised API assessment walks the list above per endpoint, with two user accounts and one admin (for API1, API3, API5), unauthenticated calls, oversized and repeated requests (API4, within agreed limits so testing doesn't become an outage), and the OpenAPI spec or GraphQL schema as the map (API9).
- Logs and metrics: per-key request rates and 429 counts, response sizes, distinct object ids per user, endpoints receiving traffic that are not in the spec, upstream call failures and unexpected data from third-party APIs (API10).
How they are fixed
An API gateway or middleware enforcing authentication, rate limits, size limits and schema validation (request and response) for every route; authorization in the service on every object and property; an inventory with an owner and a retirement date for each API version; and third-party responses validated like user input.
Pitfalls
- Rate limits only at the edge keyed on the proxy's own address (every request seems to come from the load balancer): read the client address from your trusted proxy's header only.
- Limits that count successful requests only, letting failures (wrong passwords) run free.
- "Internal" APIs without authentication reachable through SSRF or a misrouted gateway.
Practice
1. With capacity 5 and rate 0.5 per second, how many requests can a client make in the first minute if it starts with a full bucket?
5 from the full bucket plus 0.5 × 60 = 30 refilled tokens, about 35 requests.
2. A password-reset endpoint sends an SMS per request and is rate-limited per IP address. What abuse remains, and which key fixes it?
An attacker with many IP addresses can still send unlimited SMS to one victim (harassment and cost) or to many numbers (SMS pumping fraud). Add limits per phone number and per account, plus a global budget with alerts.
Test yourself
Which category tops the OWASP API Security Top 10 2023?
- Injection
- Broken Object Level Authorization
- SSRF
- Security Misconfiguration
What does a token bucket with capacity 5 and rate 0.5/s allow?
- Exactly 5 requests ever
- Bursts of up to 5 requests, and on average one request every 2 seconds
- 0.5 requests per minute
- Unlimited requests
Which category covers an old /v1 endpoint nobody remembers, still online?
- API1
- API4
- API9 Improper Inventory Management
- API10
Why is rate limiting per IP alone not enough against password spraying?
- IPs are encrypted
- Attackers spread attempts over many IPs and many accounts, staying under per-IP limits
- Spraying uses GET
- It is enough