API Security (API Design #9)
In 2021 a researcher found that a major fitness platform’s API would return any user’s private profile — weight, home city, workout maps — by incrementing one integer in the URL. No injection, no zero-day, no cryptography broken. The endpoint checked that you were logged in and never checked whose data you asked for. Millions of records, one for-loop.
That is the uncomfortable truth of API security: the worst vulnerabilities are logic bugs in your authorization and your assumptions, not exotic attacks. This chapter walks the OWASP API Security Top 10, goes deep on the two that cause the most damage — broken object-level authorization and broken authentication — and covers the supporting cast: injection, mass assignment, rate limiting, and data exposure.
By the end you will be able to audit an endpoint against the Top 10 and articulate the defense-in-depth layers that turn “one bug” into “one bug, caught.”
The OWASP API Top 10, condensed
OWASP’s API list (2023 refresh) reads like a taxonomy of this course’s chapters gone wrong:
| # | Vulnerability | The one-line version |
|---|---|---|
| 1 | Broken Object Level Authorization | you checked login, not ownership |
| 2 | Broken Authentication | weak JWT validation, no MFA, brute-forceable |
| 3 | Broken Object Property Level Authorization | mass assignment; hidden fields exposed |
| 4 | Unrestricted Resource Consumption | no rate limits → DoS and runaway bills |
| 5 | Broken Function Level Authorization | admin endpoints reachable by anyone |
| 6 | Unrestricted Access to Sensitive Business Flows | scalpers botting your checkout |
| 7 | Server-Side Request Forgery | “fetch this URL for me” → internal network |
| 8 | Security Misconfiguration | debug on, default creds, permissive CORS |
| 9 | Improper Inventory Management | the forgotten v1 endpoint from 2021 |
| 10 | Unsafe Consumption of APIs | trusting third-party responses blindly |
Notice the pattern: eight of ten are design and operations failures. A security review that only runs a scanner against crypto and injection misses exactly where APIs actually bleed.
BOLA: the number one, in code
Broken Object Level Authorization (BOLA/IDOR) is Chapter 6’s warning made flesh: the check must include the resource term. The vulnerable version looks innocent:
@app.get("/invoices/{iid}")
def get_invoice(iid: int, user=Depends(authenticate)):
return db.get(Invoice, iid) # authenticated? yes. authorized? never checked.
Any logged-in user loops iid from 1 to \(N\) and downloads every invoice you have. The fix is to make the object-level check structural, not optional:
@app.get("/invoices/{iid}")
def get_invoice(iid: int, user=Depends(authenticate)):
inv = db.get(Invoice, iid)
if inv is None or inv.account_id != user.account_id:
raise HTTPException(404) # not 403: don't confirm the id exists
return inv
Two details matter. Checking inv.account_id != user.account_id ties the resource to the caller — this is the check BOLA skips. And returning 404 instead of 403 avoids confirming that invoice 99999 exists at all; a 403 tells an enumerator “keep guessing, this one is real.”
Broken authentication and the rate-limit floor
Chapter 5’s failure modes live here: accepting alg: none JWTs, confusing the RSA public key for an HMAC secret, access tokens that live for weeks, login endpoints with no throttling. The authentication floor for any public API:
- verify signature with a pinned algorithm and the correct key type;
- validate
exp,iss,aud— a token minted for another service is not for you; - throttle credential endpoints hard (per-account and per-IP), because password guessing at 10,000 req/s is otherwise your problem;
- rotate signing keys with kid headers, so rotation isn’t a flag day (same overlap idea as Chapter 7).
Rate limiting deserves its own mention because Unrestricted Resource Consumption (#4) is broader than login brute force: any expensive endpoint without limits is a DoS vector or a bill vector. Your /search doing a fuzzy scan, your export endpoint generating PDFs, your LLM-backed summary route at $0.02 per call — each needs per-key quotas (Chapter 10 builds the token bucket). The security framing of risk applies:
\[ \text{risk} = \text{likelihood} \times \text{impact} \]
An expensive endpoint that is unlikely to be found still ranks high when impact is “a $50k invoice overnight” — which is why quotas ship with the API, not after the first incident.
Mass assignment and property-level exposure
Mass assignment (#3) is the write-side twin of data exposure. Frameworks that bind request bodies straight to models make this one-liner possible:
class Invoice(BaseModel):
total: int
status: str = "draft"
account_id: int | None = None # server-controlled... but bindable?
@app.post("/invoices")
def create(inv: Invoice):
return db.insert(inv) # client just set account_id and status="paid"
The client sends {"total": 5, "status": "paid", "account_id": 1} and writes fields they should never touch. The read-side version is returning the whole ORM object — including internal_notes and tax_id — because the serializer defaults to “everything.” The fix is the same on both sides: explicit schemas in, explicit schemas out. Accept a CreateInvoice with three fields; return an InvoiceView with the ten you chose. “Bind everything, filter later” always ends with the filter forgotten.
Injection, SSRF, and the supporting cast
- Injection survives wherever input reaches an interpreter — SQL, shell, template, LDAP. Parameterized queries and ORMs solved SQL injection a decade ago; it persists in the places people hand-build strings: raw
ORDER BYfrom a?sort=param (Chapter 3), search filters, report generators. - SSRF (#7) is the modern climber: any feature that fetches a user-supplied URL — webhook testers, “import from URL,” avatar fetching — lets attackers point your server at
http://169.254.169.254/(cloud metadata) or internal admin panels. Allowlist schemes and hosts, resolve and pin DNS, and block private ranges at the egress proxy. - Inventory (#9) is unglamorous and lethal: the deprecated
/v1/usersendpoint, still deployed, built before object-level checks existed. Version sunset (Chapter 14) is a security control; an endpoint you forgot exists cannot be patched.
Transport and headers: the boring locks
Some controls are unglamorous, near-free, and still missing half the time:
- TLS everywhere, HSTS on.
Strict-Transport-Securitytells browsers to never speak plain HTTP to you again, killing downgrade attacks and cookie-leak-on-port-80. X-Content-Type-Options: nosniff. Stops browsers from interpreting a JSON response as HTML — a content-type confusion that has turned error pages into XSS.- No stack traces in responses. A 500 that returns your framework’s traceback hands attackers a map of your dependencies and file layout. Log the trace (Chapter 13); return a problem+json with a reference id (Chapter 14).
- Security misconfiguration is a Top-10 item (#8) precisely because defaults ship open: debug consoles enabled in production, directory listings on, default credentials on admin panels,
Access-Control-Allow-Origin: *echoing credentials. A quarterly config review against a baseline catches what code review never sees.
Defense in depth
No single layer holds; the point is that no single layer has to:
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=4pt, minimum width=6.6cm, minimum height=0.62cm, align=center, font=\rmfamily\small}]
\node[b, fill=blue!10] at (0,0) {edge: TLS, WAF, bot filtering};
\node[b, fill=green!12] at (0,-0.9) {gateway: authn verify, scopes, rate limits};
\node[b, fill=orange!16] at (0,-1.8) {service: authz per object, schemas in/out};
\node[b, fill=gray!12] at (0,-2.7) {data: least-privilege DB user, encryption};
\node[b, dashed] at (0,-3.6) {observability: anomaly alerts (Chapter 13) — the layer that tells you};
\end{tikzpicture}
Each layer assumes the one above it fails. The gateway’s rate limiter assumes TLS didn’t stop the bot; the object-level check assumes a valid token was stolen; the least-privilege database user assumes the service is fully compromised (an attacker with SELECT-only on one schema can’t DROP anything). And the observability layer exists because prevention is probabilistic — detection is how “breach” becomes “incident.”
The pre-launch checklist
Compress the chapter into the review you actually run before an endpoint ships:
| Question | Top-10 item |
|---|---|
| Does every object access re-check ownership (404 on mismatch)? | #1 BOLA |
Are JWT signature, algorithm, exp, iss, aud all verified? |
#2 authn |
| Do input/output schemas whitelist fields explicitly? | #3 mass assignment |
| Is there a rate limit tiered by key scope? | #4 resource consumption |
| Are admin routes gated by function-level authz, not obscurity? | #5 BFLA |
| Are user-supplied URLs allowlisted and egress-restricted? | #7 SSRF |
| Is debug off, CORS exact, are error bodies problem+json? | #8 misconfig |
| Is this route in the inventory (and vN−1 scheduled to die)? | #9 inventory |
Eight questions, five minutes per endpoint, and you’ve audited against the list that actually gets APIs breached. Run it in design review; run it again in the contract tests (Chapter 12 makes several of these executable).
Pitfalls
- Authenticated ≠ authorized. Checking the token and returning
db.get(id)is BOLA, the #1 API vulnerability. Every object access re-checks ownership. - 403 for other people’s resources. It confirms existence to enumerators. Return 404 for resources the caller may not see.
- Binding request bodies to models. Mass assignment sets
is_admin,account_id,statusstraight from the client. Accept narrow input schemas; return narrow output schemas. - Rate limits only on login. Every expensive endpoint is a DoS/bill vector — search, exports, LLM calls. Quotas everywhere, tiered by key scope.
- Trusting user-supplied URLs. “Fetch this for me” is SSRF into your internal network and cloud metadata. Allowlist hosts; block private ranges at egress.
- Zombie endpoints. Unsunset v1 routes run last year’s auth logic. Inventory your routes; kill the forgotten ones.
An endpoint verifies a valid JWT and returns the requested order — which Top-10 item does it still fail, and what two-line fix (with status code) closes it? Why is alg pinning part of authentication security? Your “import invoice from URL” feature is popular — what attack does it invite, and what are the two controls?
ASolution
Broken Object Level Authorization: the token proves who called, not that the order is theirs. Fetch the order, compare its account_id to the caller’s, and return 404 (not 403) on mismatch so id enumeration learns nothing. Without a pinned algorithm, an attacker can flip alg to none (no signature needed) or exploit RS256→HS256 confusion to sign tokens with your public key; pinning makes the verifier accept exactly one algorithm with the right key type. URL-import invites SSRF — attackers point your server at internal admin panels or the cloud metadata endpoint; control it with an allowlist of schemes/hosts (plus DNS pinning) and an egress rule blocking private IP ranges.
Next: API Performance (API Design #10) — measuring what matters, caching, load balancing, rate limiting, and async work.