Notes
All notes

API Keys & Management (API Design #7)

A developer pastes a stack trace into a public GitHub issue. Line 14 contains Authorization: Bearer sk_live_9f3c…. A scraper finds it within the hour — there are bots that do nothing but watch GitHub’s public event feed for strings that look like keys — and by midnight that key has run up $18,000 of compute on your paid tier.

API keys are the simplest machine credential ever devised, and their disasters are always management failures: how they were generated, scoped, stored, rotated, and revoked. This chapter covers each stage of a key’s life, with the numbers and code behind them.

By the end you will be able to design a key system where a leaked key is a minor incident — small blast radius, fast revocation — instead of a breach.

What an API key is — and isn’t

An API key is a bearer credential: whoever presents it, is it. That makes keys perfect for machine identity — a CI job, a partner’s backend, a CLI — and wrong for user identity, where you want expiry, refresh, and per-user consent (Chapter 5). Keys authenticate a client application, and by convention they double as the hook for rate limits, quotas, and billing attribution: one key, one customer, one meter.

The design goal follows from the bearer property: since possession equals power, a well-run key system minimizes what possession buys (scoping) and how long it stays bought (rotation and revocation).

Generating keys: entropy is the whole game

A key is a password you never type, so it can — and must — be unguessable. The math is brutal and simple. If an attacker can test \(r\) keys per second (say \(10^6\) against your online endpoint, or \(10^{10}\) offline against a leaked hash), the expected crack time for an \(n\)-bit key space is

\[ t = \frac{2^{n-1}}{r} \text{ seconds} \]

At \(n = 32\) (eight hex chars), an offline attacker at \(10^{10}\)/s needs about 0.2 seconds. At \(n = 128\), the same attacker needs \(10^{19}\) years. There is no middle ground: keys are either trivially enumerable or effectively infinite. Generate 128+ bits from a CSPRNG and never from random(), timestamps, or hashes of user data:

import secrets, hashlib

def issue_key(prefix: str = "sk_live") -> tuple[str, str, str]:
    secret = secrets.token_urlsafe(32)          # 256 bits, CSPRNG
    key_id = secrets.token_hex(4)               # public identifier, e.g. "a1b2c3d4"
    full = f"{prefix}_{key_id}_{secret}"        # shown to the user ONCE
    digest = hashlib.sha256(full.encode()).hexdigest()   # stored, never the key
    return full, key_id, digest

Three details in that snippet carry real weight. The prefix (sk_live_, sk_test_) tells humans and scanners what they’re looking at — GitHub’s own secret scanning, and your log redaction, pattern-match on these prefixes. The key id embedded in the key lets you look up which stored hash to compare against without revealing anything. And what you store is the SHA-256 digest, not the key: a database leak then yields hashes of 256-bit random strings, which are as useless as hashes of the universe.

Verification is the mirror image: extract the key id, look up its digest, hash the presented key, compare in constant time — and check scope before doing work:

def authenticate(header: str) -> KeyContext | None:
    # header = "sk_live_a1b2c3d4_<secret>"  →  env, key_id, secret
    env, key_id, secret = header.removeprefix("sk_").split("_", 2)
    row = db.get_key(key_id)                            # digest, scopes, rate tier
    if row is None or row.revoked:
        return None
    digest = hashlib.sha256(header.encode()).hexdigest()
    if not hmac.compare_digest(digest, row.digest):     # constant time, always
        return None
    return KeyContext(key_id=key_id, scopes=row.scopes, tier=row.tier)

Two subtleties: compare the digest (so the secret never sits in memory longer than the hash takes), and always run the comparison even when the key id is unknown — early-exit logic leaks which key ids exist via timing.

Scopes and permissions: shrink the blast radius

A key with no scopes is a master key. Scopes (Chapter 6) turn “leaked key = total compromise” into “leaked key = someone can read public product data”:

Scope Allows Who needs it
read:products GET catalog every storefront integration
write:inventory stock updates the warehouse sync job
read:orders order lookup the support tool
admin everything nobody, ever, via API key

Default to the empty scope set and make customers justify each grant — the same least-privilege rule as user authorization, applied to machines. Per-scope rate limits come along naturally: read:* at 1,000 req/min, write:* at 60 req/min, so a leaked read key can’t even be used to hammer write paths.

Rotation: expiry without downtime

Keys that live forever eventually leak forever. Rotation policy — replace every 90 days, say — runs into a practical wall: the client deploys the new key at some unknown moment, and any gap between “server rejects old” and “client uses new” is downtime. The fix is an overlap window: issue the new key while the old still works, let both authenticate during the window, then expire the old.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=1.9cm, minimum height=0.55cm, align=center, font=\rmfamily\scriptsize}]
  \draw[->, thick] (0,0) -- (10.4,0) node[right, font=\rmfamily\scriptsize] {time};
  \fill[green!35] (0.2,0.35) rectangle (6.5,0.85);
  \node[font=\rmfamily\scriptsize] at (3.3,0.6) {old key valid};
  \fill[blue!25] (4.5,1.05) rectangle (9.5,1.55);
  \node[font=\rmfamily\scriptsize] at (7.0,1.3) {new key valid};
  \fill[orange!35] (4.5,0.35) rectangle (6.5,0.85);
  \node[font=\rmfamily\scriptsize, align=center] at (5.5,-0.35) {overlap: both accepted\\client migrates here};
  \draw[dashed] (4.5,0) -- (4.5,1.6); \draw[dashed] (6.5,0) -- (6.5,1.6);
\end{tikzpicture}

Rotation done this way is a non-event; rotation done as a flag day is a pager. The same machinery handles emergency revocation — a leaked key gets its stored digest deleted, and since verification is a hash lookup, the key dies globally within one cache TTL.

Storage and handling: where keys die

Keys leak from places, not from math. The audit list:

The one-time display rule follows from digest storage: since you cannot recover a key from its hash, you show it exactly once at creation (“copy it now, we can’t show it again”). Users who lose a key rotate — which is what they should be comfortable doing anyway.

Key formats: tell humans and machines what they’re holding

A well-formed key communicates before it authenticates. The conventions worth copying:

Prefix Meaning Power
pk_live_… publishable, live safe to embed in client code; heavily restricted
sk_live_… secret, live full scoped power; server-side only
sk_test_… secret, sandbox no real money/data moves

Publishable vs secret keys separate “identity for attribution” from “identity for power”: the publishable key can live in JavaScript because it can only do harmless things (start a checkout, load public config), while the secret key never leaves your servers. Test keys get a parallel universe — separate data, separate rate limits, separate billing — so developers can break things safely and CI can run against the sandbox (Chapter 8’s “no sandbox” pitfall).

The lifecycle of any key, secret or not:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=1.9cm, minimum height=0.62cm, align=center, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=green!12] (c) at (0,0) {created\\(shown once)};
  \node[b, fill=blue!10] (a) at (3,0) {active};
  \node[b, fill=orange!16] (r) at (6,0) {rotated\\(overlap)};
  \node[b, fill=gray!15] (d) at (9,0) {expired /\\revoked};
  \draw[a] (c) -- (a); \draw[a] (a) -- (r); \draw[a] (r) -- (d);
  \draw[a, dashed, red!60!black] (a.south) to[bend right=25] node[below, font=\rmfamily\scriptsize] {leaked $\rightarrow$ revoke now} (d.south);
\end{tikzpicture}

The dashed edge is the incident path: revocation skips rotation’s politeness and kills the digest immediately.

Metering and abuse detection

Because every request carries a key, the key is the natural unit for operational signals. Track per-key request rates, error ratios, and endpoint mix; the anomalies are loud. A read-scoped key that suddenly calls write endpoints, a key active from two continents at once, a key whose traffic 100x’d at 3 a.m. — each is either abuse or a bug, and both deserve an automated response: throttle first, alert second, auto-revoke on high-confidence signals. This is also where keys feed Chapter 10’s rate limiting and Chapter 13’s observability: the same per-key counter that enforces quotas powers the abuse dashboard.

Pitfalls

QQuestionSelf-check

Why store the SHA-256 of a 256-bit key instead of encrypting the key reversibly? A customer reports a leaked sk_live key with read:products scope — walk through the blast radius and the response. Why does rotation need an overlap window rather than instant cutover?

ASolution

With 256-bit entropy, a brute-force attack on the digest is hopeless, so a fast unsalted hash is sufficient — and unlike reversible encryption there is no master decryption key whose theft unlocks everything; a database leak yields only uncrackable hashes. The leak’s blast radius is bounded by the scope: an attacker can read the product catalog at the read rate limit, but cannot write or reach orders — response is to revoke the digest (effective within one cache TTL), issue a fresh key, and review the per-key telemetry for what was accessed. Instant cutover breaks every client that hasn’t deployed the new key yet; the overlap window lets old and new authenticate simultaneously while clients migrate on their own schedule, then the old expires.

Next: API Documentation Tools (API Design #8) — OpenAPI, Swagger, Stoplight, Readme, and Postman, and how the contract becomes something humans can use.