Notes
All notes

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:

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

Transport and headers: the boring locks

Some controls are unglamorous, near-free, and still missing half the time:

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

QQuestionSelf-check

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.