Shelf · Core Eng · Chapter 4

Chapter 4: Auth & application security

Authentication, authorization and the handful of attack shapes that account for most backend breaches, built from stdlib-only demos you can actually run. By the end you can explain sessions versus JWT, rotate refresh tokens safely, walk an OAuth2/OIDC flow end to end, close SQLi/SSRF/IDOR, hash a password properly, and turn all of it into tests that fail on regression.

Difficulty
Priority
ce-04-01Card 1 of 6

Authentication and authorization: sessions and JWT

MediumP1 · Must knowKnow cold14 min
authenticationauthorizationsessionsjwtrevocation

Why you care

Authentication answers "who are you"; authorization answers "what are you allowed to do", and conflating the two is why interviewers keep asking for the difference — because in real code the mix-up ships as a bug: a valid, unexpired JWT that says "user 42 is logged in" gets treated as "user 42 can touch this row", when nothing checked that user 42 owns the row. On the job this is also where "log out" secretly does nothing: a JWT nobody revoked keeps validating on every server for as long as its exp says so, even after the user hits "logout" and the session row is long gone. Get this card wrong and either your app trusts a token nobody can actually kill, or you rebuild sticky sessions and wonder why your API doesn't scale past one box.

Explain like I'm 5

A session is a coat-check ticket: the cloakroom (server) keeps your coat and hands you a numbered ticket, and the ticket means nothing without the cloakroom's record — tear up the record and the ticket is worthless paper, even if you still hold it. A JWT is a sealed, signed letter of introduction: it says who you are and until when, and any office with the same wax-seal stamp can read and trust it without calling the cloakroom back. That's faster and needs no shared room, but there is no cloakroom to raid — burn your own copy of the letter, and every other copy is still a valid letter until the date on it passes.

Core concept

  • Authentication confirms identity (login). Authorization confirms permission for a specific action on a specific object. A passed authentication check never implies a passed authorization check.
  • A session is opaque server-side state: the client holds only a random id (secrets.token_urlsafe(32), well above the roughly 64 bits of entropy OWASP's Session Management Cheat Sheet asks for a session id), and the server looks it up on every request. Revocation is instant: delete the row.
  • A JWT is self-contained: header.payload.signature, base64url-encoded, carrying claims the server can verify without a lookup. RFC 7519's registered claims include iss (issuer), sub (subject), aud (audience), exp/nbf/iat (time bounds) and jti (a unique id, useful for revocation). None of the claims are secret — they're only signed, not encrypted, so never put a password or PII there.
  • Revocation is the real trade-off: a "revoked" JWT is still cryptographically valid until exp unless you keep server-side state anyway (a deny-list keyed by jti, checked on every request) — at which point you've paid for the session model's lookup and kept the JWT's complexity.
  • Every verification checks the signature, and separately, explicitly, the claims: issuer, audience and expiry. Per RFC 8725 (the JWT security best-practices RFC), never trust the token's own alg header to decide how to verify it — pin the algorithm your server expects, or an attacker can switch RS256 to HS256 and get your library to check the RSA public key as if it were an HMAC secret, or slip in alg: none if the library allows it.
  • Object-level authorization happens after authentication, on every access, not once at login: "is this JWT valid" and "does this JWT's subject own order 4471" are two separate checks, and skipping the second is the single most common access-control bug (Application threat boundaries: SQLi, SSRF and IDOR).

Use sessions when you control the servers your users hit and want instant, simple revocation. Use JWTs when a client needs to prove identity to services you don't run, or when a shared session store would become a single dependency for every one of those services — and treat revocation as something you design for from day one, not a feature you bolt on after the first incident.

Under the hood

A JWT is three base64url segments joined by dots: header.payload.signature. The signature is HMAC-SHA256(header_b64 + "." + payload_b64, secret) (for HS256), computed over the exact transmitted bytes of the first two segments, not the decoded JSON — decode a token, re-encode it with different key order or whitespace, and the signature breaks even though the data is logically identical. This byte-exactness is also the root of the algorithm-confusion attack RFC 8725 warns about: because the header names its own algorithm and many libraries dispatch on it, an attacker holding your RSA public key can craft a token with "alg":"HS256" and hand that public key back as if it were an HMAC secret — a library that blindly follows the header's alg will check it and accept. RFC 8725's fix puts the burden on the caller: pin the expected algorithm in your verifier's configuration, and never branch on the token's own alg field.

Minimal example Sign, verify, and detect one flipped claim

PythonA hand-rolled JWT: signature holds, one changed byte breaks itruns
import base64, hashlib, hmac, json, time

def b64url(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()

def unb64url(s: str) -> bytes:
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))

def sign(header: dict, payload: dict, secret: bytes) -> str:
    signing_input = b64url(json.dumps(header, separators=(",", ":")).encode()) + "." + \
                    b64url(json.dumps(payload, separators=(",", ":")).encode())
    sig = hmac.new(secret, signing_input.encode(), hashlib.sha256).digest()
    return signing_input + "." + b64url(sig)

secret = b"server-only-secret"
header = {"alg": "HS256", "typ": "JWT"}
payload = {"sub": "user-42", "exp": int(time.time()) + 900}
token = sign(header, payload, secret)
print(token.count("."))

h, p, s = token.split(".")
recomputed = hmac.new(secret, f"{h}.{p}".encode(), hashlib.sha256).digest()
print(hmac.compare_digest(unb64url(s), recomputed))

tampered_p = b64url(json.dumps({"sub": "user-999", "exp": payload["exp"]}, separators=(",", ":")).encode())
tampered_check = hmac.new(secret, f"{h}.{tampered_p}".encode(), hashlib.sha256).digest()
print(hmac.compare_digest(unb64url(s), tampered_check))
Output
2
True
False

In production Session revocation is instant; a JWT needs a deny-list

PythonLogout kills a session immediately; a bare JWT keeps validatingruns
import base64, hashlib, hmac, json, secrets, time

SECRET = b"server-only-secret-do-not-log"
REVOKED_JTIS = set()
SESSIONS = {}  # sid -> {"user": ..., "exp": epoch}: stands in for Redis/Postgres

def b64url(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()

def unb64url(s: str) -> bytes:
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))

def issue_jwt(user: str, ttl: int = 900):
    header = {"alg": "HS256", "typ": "JWT"}
    payload = {"iss": "orders-api", "sub": user, "aud": "orders-api",
               "iat": int(time.time()), "exp": int(time.time()) + ttl,
               "jti": secrets.token_hex(8)}
    signing_input = b64url(json.dumps(header, separators=(",", ":")).encode()) + "." + \
                    b64url(json.dumps(payload, separators=(",", ":")).encode())
    sig = hmac.new(SECRET, signing_input.encode(), hashlib.sha256).digest()
    return signing_input + "." + b64url(sig), payload["jti"]

def verify_jwt(token: str, expected_aud: str):
    h, p, s = token.split(".")
    expected_sig = hmac.new(SECRET, f"{h}.{p}".encode(), hashlib.sha256).digest()
    if not hmac.compare_digest(unb64url(s), expected_sig):
        return None
    payload = json.loads(unb64url(p))
    if payload["aud"] != expected_aud or payload["exp"] < time.time():
        return None
    if payload["jti"] in REVOKED_JTIS:
        return None
    return payload

def create_session(user: str, ttl: int = 900) -> str:
    sid = secrets.token_urlsafe(32)
    SESSIONS[sid] = {"user": user, "exp": time.time() + ttl}
    return sid

def logout_session(sid: str) -> None:
    SESSIONS.pop(sid, None)

sid = create_session("user-42")
print("session valid before logout:", sid in SESSIONS)
logout_session(sid)
print("session valid after logout:", sid in SESSIONS)

token, jti = issue_jwt("user-42")
print("jwt valid before 'logout':", verify_jwt(token, "orders-api") is not None)
REVOKED_JTIS.add(jti)  # this is the server state a "stateless" token secretly needs
print("jwt valid after adding jti to deny-list:", verify_jwt(token, "orders-api") is not None)
Output
session valid before logout: True
session valid after logout: False
jwt valid before 'logout': True
jwt valid after adding jti to deny-list: False

See it happen Two requests, one lookup, one signature check

clientauth serverAPI serversession storePOST /loginwrite sid -> userSet-Cookie: sidGET /orders (Cookie: sid)lookup(sid)user-42, validGET /orders (Authorization: Bearer <jwt>)verify signature + iss/aud/exp
  1. Client authenticates once with credentials.
  2. Session model: the server creates state and remembers it.
  3. The client gets only an opaque, unguessable id.
  4. Every later request carries just the id.
  5. The API server must ask the store before it trusts anything.
  6. A revoked sid returns nothing here, instantly.
  7. JWT model: the same later request instead carries a signed claim set.
  8. No network call needed, unless the API server also keeps a jti deny-list.
Notice: the store lookup for sessions and the deny-list check for a "revocable" JWT are the same idea wearing different clothes — revocation always needs server state to live somewhere.
Scenario A

In your world

The situation

Your FastAPI service issues a JWT on login with a 12-hour exp and no jti, because "that's stateless and scales." Logout on the frontend just deletes the token from browser storage.

What actually breaks

A support laptop is compromised at 10am. The stolen JWT, copy-pasted into curl, still authenticates orders until it expires at 10pm — logout on the frontend never touched the server, and there's no way to kill that one token early without killing the shared secret for every user.

What you'd do on Monday

Add jti to every issued token and a real revoked-token table, so an incident response has something to do besides wait:

PythonRevoke by jti using a real table instead of trusting the token foreverruns
import sqlite3

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE revoked_tokens (jti TEXT PRIMARY KEY, revoked_at TEXT)")

def revoke(jti: str) -> None:
    conn.execute("INSERT OR REPLACE INTO revoked_tokens VALUES (?, datetime('now'))", (jti,))
    conn.commit()

def is_revoked(jti: str) -> bool:
    row = conn.execute("SELECT 1 FROM revoked_tokens WHERE jti = ?", (jti,)).fetchone()
    return row is not None

stolen_jti = "a1b2c3d4"
print("revoked before incident response:", is_revoked(stolen_jti))
revoke(stolen_jti)
print("revoked after incident response:", is_revoked(stolen_jti))
Output
revoked before incident response: False
revoked after incident response: True
Scenario B

Imagine you work at Okta

50M JWT verifications/day

The numbers

Illustrative: 50M verifications/day ≈ 580/s average, spiking to roughly 5,000/s at a login-heavy peak. If every verification needs a deny-list lookup against a shared store, that's 5,000 extra round trips/s to whatever holds REVOKED_JTIS.

What the Scenario-A answer does here

The Scenario A fix (jti plus a deny-list) still works, but a single shared SQL table checked on every request at 5,000 req/s adds a network hop and lock contention to the hot path of every API server — the fix that saved you from an unkillable token now makes JWT verification no faster than a session lookup.

What flips at this scale

At this scale you keep the deny-list deliberately small and fast: only revoked-before-exp tokens live in it, pruned once their own exp passes (a revoked entry is worthless once the token would have expired anyway), and it sits in a low-latency cache in front of the durable store, never in the request's primary database.

The trade-off you'd defend

I would defend a short-lived, cache-backed deny-list plus a short token exp (minutes, not hours) over either a fully stateless long-lived JWT or a full session-per-request lookup, trading a small cache dependency for both fast verification and revocation that actually works.

Illustrative figures chosen to make the arithmetic concrete; not Okta-published numbers.

Session vs JWT

AxisSession (opaque id)JWT (signed claims)
Where state livesServer-side store; client holds only an idEncoded in the token itself
RevocationInstant: delete the store rowNeeds a deny-list or a short exp; not free
Cross-service trustNeeds the same store reachable by every serviceAny service with the verification key can trust it, no shared store
Payload visibilityNothing exposed to the clientClaims are base64, not encrypted: readable by anyone holding the token
Typical useFirst-party web app, one team's serversCross-service calls, third-party APIs, mobile clients hitting many backends

Gotchas

Checking the signature but not the claims

Symptom

A JWT signed by your own auth server for a different audience (say, a partner's API) is accepted by your service and grants access.

Cause

A valid signature only proves your key signed it; it says nothing about who the token was meant for. Skipping aud/iss checks, or the object-ownership check, admits the wrong access even though the signature is genuine.

Fix

Verify iss, aud and exp as steps separate from the signature, and check object ownership on every access, not just once at login.

Trusting the token's own alg header

Symptom

An attacker-supplied token with "alg":"HS256" verifies successfully against a service that normally issues RS256 tokens.

Cause

The library read the algorithm from the untrusted header and used the RSA public key as if it were an HMAC secret.

Fix

Pin the expected algorithm in the verifier's configuration; never branch on the token's own alg field (RFC 8725).

"Logout" that only clears the browser

Symptom

A copy of the token, pasted into curl, keeps working long after the user logged out.

Cause

Deleting client-side storage never touches the server; a JWT with no deny-list stays valid until exp regardless.

Fix

Track revocable state by jti (see Scenario A), or keep exp short enough that "log out and wait" is an acceptable answer.

Tricky questions

If a JWT is signed, is it also confidential?
Most people say

Yes, since it's cryptographically protected, nobody else can read it.

Actually

HMAC/RSA signing proves integrity and origin, not secrecy. Header and payload are only base64url-encoded, not encrypted; anyone holding the token can read every claim. Put nothing sensitive in the payload.

Does authenticating a request also authorize it?
Most people say

Yes, once you know it's user-42's valid token, you know they're allowed to act.

Actually

Authentication confirms identity; a second, explicit check must confirm user-42 owns the specific object being accessed. Skipping it is IDOR (Application threat boundaries: SQLi, SSRF and IDOR).

Scenario question

You're handed a service that authenticates with JWTs and has no logout endpoint at all — "the token just expires." Product now wants an instant "log out of all devices" button. What do you build, and what do you tell them about tokens already issued with a 24-hour exp?

Model answer

I would add a jti to every newly issued token and a token_version (or logged_out_at) claim per user, checked against a small per-user value stored server-side; bumping that value invalidates every token issued before it in one write, without a deny-list entry per token. For tokens already out there with a 24-hour exp and no such claim, I would say plainly that those specific tokens cannot be revoked early — the fix only protects tokens issued after I ship it — and I would separately propose shortening exp to 15-30 minutes with a refresh token (Rotate refresh tokens and retire sessions) so the exposure window for the next incident is minutes, not a day.

Interview corner

CommonWhat's the difference between authentication and authorization?
“I'd say authentication is proving who you are, and authorization is checking what that identity is allowed to do to a specific thing. A valid login token is not proof you own the row you're asking for.”
TrickYou revoke a user's session, but they can still make authenticated calls. Why?
“I'd check whether they're on a JWT rather than a session. A session revoke deletes server-side state and is instant; a JWT keeps validating on its own signature until it expires, unless there's a deny-list checked on every request.”
CommonWhat goes in a JWT payload, and what shouldn't?
“I'd put identity and authorization-relevant claims: sub, iss, aud, exp, maybe roles. I'd never put a password, a full PII record, or anything secret, because the payload is only base64, not encrypted.”
Experience checkWhere has session-versus-JWT confusion bitten a team you've seen?
“I'd point to treating JWT expiry as the whole security story and shipping with no way to kill a specific token early — I've seen that discovered during an incident instead of before one.”
DesignWould you use sessions or JWTs for a new internal API?
“For a first-party API where my own servers issue and check the token, I'd lean sessions for the easy instant revocation, unless the API is called by many independent services, where a signed JWT avoids a shared session store becoming a single dependency for everyone.”

Memory hook

A session is a coat-check ticket the cloakroom can void; a JWT is a signed letter nobody can un-write, only outlive.

If you remember only one thing:

Authenticating proves identity; it never proves the right to touch a specific object — check that separately, every time.

Self-check

  1. What does it mean that a JWT's claims are "signed, not encrypted"?

    Anyone holding the token can read the header and payload; the signature only proves who issued it and that it wasn't altered.

  2. Why can't you truly revoke a JWT without extra server state?

    Its own validity check is just signature plus time claims; killing one early needs a deny-list or version claim checked server-side, which is the "server state" a session already had.

  3. Name the two claims RFC 8725 says you must never skip, beyond the signature.

    iss (issuer) and aud (audience), plus checking exp.

Prove it

Take the issue_jwt/verify_jwt pair from this card, add a token_version claim and a per-user version counter in a dict, and implement logout_all_devices(user) that bumps the counter. Show that a token issued before the bump fails verification after it, and a freshly issued token after the bump succeeds. Paste both outputs.

ce-04-02Card 2 of 6

Rotate refresh tokens and retire sessions

HardP3 · Role-dependentTalk about it13 min
refresh-tokensrotationreplay-detectionmfastep-up-auth

Why you care

Access tokens are short-lived on purpose, but making users re-type a password every ten minutes is unacceptable, so almost every real system pairs a short access token with a long-lived refresh token exchanged for a new pair. The mechanic that separates a junior implementation from a production one is rotation: every refresh token is single-use, and using an already-used one is treated as a stolen-token signal, not a bug to shrug off. Interviewers who ask "how do you handle refresh tokens" are checking whether you know a refresh token needs the same theft-response plan as a password reset — because unlike a password, nobody typed it, so nobody notices it's gone until it's used twice.

Explain like I'm 5

A refresh token is a single-ride shuttle ticket that hands you a new ticket for the next ride as you board. You're never meant to hold two valid tickets, and you never reuse one you've already boarded with. If the driver ever sees the same old ticket handed in twice, that's not a jammed turnstile — someone photocopied it, so the driver cancels every ticket in that whole booklet, yours included, and sends you back to the counter to buy a new one (log in again).

Core concept

  • Access token: short-lived (minutes), sent on every API call, cheap to verify.
  • Refresh token: long-lived (days/weeks), sent only to the token endpoint, exchanged for a new access-plus-refresh pair. Never sent to ordinary API endpoints.
  • Rotation: every refresh exchange invalidates the refresh token used and issues a brand-new one. A refresh token is single-use.
  • Reuse (replay) detection: because rotation makes each token single-use, seeing the same refresh token presented a second time is a strong theft signal. The standard response is to revoke the whole token family (every token descended from one login), not just the reused token, because you can't tell which of the two holders is the attacker.
  • Concurrent refresh races: a legitimate client (two tabs, or a mobile app retrying a slow network call) can present the same refresh token twice within milliseconds, for entirely innocent reasons. Naive reuse detection revokes the legitimate user's whole session for this. A short grace window that returns the same already-issued next token to a concurrent request, without re-rotating twice, is the standard fix.
  • Reauthentication for sensitive actions: a valid session or fresh access token proves someone is still logged in, not that the same human is at the keyboard for changing a password or approving a large payment. Step-up auth — proving a second factor again for that one action — is the answer, without forcing a full re-login.
  • Storage and compromise response: refresh tokens are bearer secrets and belong in HttpOnly, Secure cookies for web clients, never localStorage, which any script (including an XSS payload) can read. Decide upfront what "compromise" triggers: revoke the family, force re-login, notify the user.

Pick a grace window in the low single-digit seconds if your clients are known to double-fire refreshes (mobile apps on flaky networks); pick zero grace and hard-revoke on any reuse if you're behind one well-tested SPA and want the simplest, most paranoid policy.

Under the hood

Each refresh token record is, conceptually, {token_id, family_id, generation, used}. Rotation marks the presented record used = True and inserts a new record with generation + 1 in the same family; a presented token whose used flag is already True is the replay signal. The race exists because "check used" and "mark used" are two operations separated by a network-plus-database round trip: two requests can both read used = False before either writes True, so both proceed and both mint a "next" token — a fork the server can't distinguish from a legitimate retry racing the legitimate client. The two production fixes are (a) make the check-and-mark atomic, a single UPDATE ... WHERE used = false RETURNING ... in Postgres, which simply fails for the loser of the race, and (b) treat that loser's failure as "return the already-rotated next token" for a few seconds instead of an intrusion. Atomic check-and-mark rotation is the same compare-and-swap idea as an optimistic-lock version column.

Minimal example TOTP against RFC 6238's own test vectors

PythonHMAC-SHA1 truncated into a time-based one-time coderuns
import hashlib, hmac, struct

def hotp(key: bytes, counter: int, digits: int = 8) -> str:
    msg = struct.pack(">Q", counter)
    h = hmac.new(key, msg, hashlib.sha1).digest()
    offset = h[-1] & 0x0F
    part = h[offset:offset + 4]
    code = (int.from_bytes(part, "big") & 0x7FFFFFFF) % (10 ** digits)
    return str(code).zfill(digits)

def totp(key: bytes, unix_time: int, step: int = 30, digits: int = 8) -> str:
    return hotp(key, unix_time // step, digits)

seed = b"12345678901234567890"  # RFC 6238 Appendix B test seed
vectors = {59: "94287082", 1111111109: "07081804", 1111111111: "14050471",
           1234567890: "89005924", 2000000000: "69279037", 20000000000: "65353130"}

for t, expected in vectors.items():
    print(t, totp(seed, t) == expected)
Output
59 True
1111111109 True
1111111111 True
1234567890 True
2000000000 True
20000000000 True

In production Rotation with reuse detection and family revocation

PythonA single-use token chain: reuse of any link kills the whole familyruns
import secrets

TOKENS = {}
FAMILIES_REVOKED = set()

def issue_initial(user: str):
    family = secrets.token_hex(8)
    tid = secrets.token_hex(16)
    TOKENS[tid] = {"user": user, "family": family, "gen": 0, "used": False}
    return tid, family

def rotate(token_id: str) -> str:
    rec = TOKENS.get(token_id)
    if rec is None:
        raise ValueError("unknown refresh token")
    if rec["family"] in FAMILIES_REVOKED:
        raise ValueError("token family revoked, reauthenticate")
    if rec["used"]:
        FAMILIES_REVOKED.add(rec["family"])
        raise ValueError("refresh token reuse detected, family revoked")
    rec["used"] = True
    new_id = secrets.token_hex(16)
    TOKENS[new_id] = {"user": rec["user"], "family": rec["family"], "gen": rec["gen"] + 1, "used": False}
    return new_id

t0, family = issue_initial("user-42")
t1 = rotate(t0)
t2 = rotate(t1)
print("current generation:", TOKENS[t2]["gen"])

try:
    rotate(t1)                      # replay: t1 was already redeemed above
except ValueError as e:
    print("ValueError:", e)
print("family revoked:", family in FAMILIES_REVOKED)

try:
    rotate(t2)                      # even the otherwise-valid latest token is now dead
except ValueError as e:
    print("ValueError:", e)
Output
current generation: 2
ValueError: refresh token reuse detected, family revoked
family revoked: True
ValueError: token family revoked, reauthenticate

See it happen A replay is indistinguishable from theft, so both sides pay for it

clientattackerauth serverrefresh(t0)t1 + access tokenrefresh(t0)401 reuse detectedrevoke familyrefresh(t1)401 family revoked, reauthenticate
  1. Normal use: t0 is presented once.
  2. t0 is marked used and cannot be redeemed again.
  3. Attacker replays a stolen copy of the original token.
  4. The server sees used=True and treats this as theft, not a retry.
  5. Every token descended from this login is killed, including the client's still-valid t1.
  6. The legitimate client's next scheduled refresh.
  7. The legitimate user pays for the theft signal too.
Notice: family revocation can't tell which side was the attacker, so it logs out the real user as collateral damage — that's the price of detecting theft at all.
Scenario A

In your world

The situation

Your mobile app stores its refresh token in local storage (fine) and calls /refresh whenever the access token is within 60 seconds of expiring, but two screens each independently check that condition and both fire a refresh call within the same second.

What actually breaks

The first call rotates the token and gets a new one back; the second call — using the now-already-used token — hits your reuse check and revokes the whole family. The user is logged out mid-session for using your app normally, and support tickets call it "randomly logs me out."

What you'd do on Monday

Serialize refreshes client-side to one in-flight call, and add a short server-side grace window that returns the already-issued next token to a repeat presentation instead of treating it as theft:

PythonA grace window turns a legitimate race into a no-op, not a lockoutruns
TOKENS = {}
GRACE_SECONDS = 2

def issue(user: str) -> str:
    tid = "t0"
    TOKENS[tid] = {"user": user, "family": "fam-1", "used_at": None, "next": None}
    return tid

def rotate(token_id: str, now: float):
    rec = TOKENS[token_id]
    if rec["used_at"] is None:
        rec["used_at"] = now
        new_id = f"{token_id}-next"
        TOKENS[new_id] = {"user": rec["user"], "family": rec["family"], "used_at": None, "next": None}
        rec["next"] = new_id
        return new_id, "rotated"
    if now - rec["used_at"] <= GRACE_SECONDS:
        return rec["next"], "grace: returned same next token"
    return None, "reuse outside grace window: revoke family"

t0 = issue("user-42")
print(rotate(t0, now=100.0))   # screen A's refresh
print(rotate(t0, now=100.4))  # screen B's refresh, 0.4s later, same stale token
print(rotate(t0, now=104.0))  # a genuine replay long after: outside the grace window
Output
('t0-next', 'rotated')
('t0-next', 'grace: returned same next token')
(None, 'reuse outside grace window: revoke family')
Scenario B

Imagine you work at Duo Security

10M sessions, 11k refreshes/second

The numbers

Illustrative: 10M active mobile sessions refreshing every 15 minutes ≈ 11,111 refresh calls/second sustained, with sensitive actions triggering a step-up challenge for roughly 2% of active sessions/day ≈ 200k step-up challenges/day, averaging 2.3/second but bursting far higher at business-hours peak.

What the Scenario-A answer does here

The Scenario A fix (a grace window plus a client-side mutex) still holds, but running check-then-mark reuse logic as two separate database statements per refresh, at 11k/s, means thousands of concurrent read-then-write races per second — not the rare double-tap of one user's two screens, but a structural rate of legitimate concurrent refreshes from different devices and different users landing on the same hot rows.

What flips at this scale

At this rate, correctness moves from "add a grace window" to "make the rotation itself atomic": one conditional update resolves the race in the database, not in application code, and step-up challenges get their own short-lived, purpose-scoped assertion so a stolen access token can never itself satisfy a step-up requirement.

The trade-off you'd defend

I would defend one atomic conditional update per rotation over any read-then-write pair plus a grace window, trading a slightly less readable query for removing an entire class of race by construction, and keep the grace window only as a client-facing smoother, not the correctness mechanism.

Illustrative figures chosen to make the arithmetic concrete; not Duo-published numbers.

Gotchas

A legitimate double-refresh looks identical to theft

Symptom

Users get logged out with no error on their end, right after normal use — two tabs, or a flaky retry.

Cause

Naive reuse detection treats any second presentation of a used token as theft, with no window for network retries or near-simultaneous refreshes from multiple tabs.

Fix

Add a short grace window that returns the same next token to a repeat presentation within a few seconds, and serialize refreshes on the client.

Read-then-write reuse checks race under load

Symptom

Occasionally two requests both succeed in rotating what should be a single-use token, each minting a "next" token.

Cause

Checking used == False and setting used = True as two separate operations leaves a window where two concurrent requests both read False first.

Fix

Make the check-and-mark a single atomic database statement (a conditional UPDATE ... RETURNING), not two round trips.

Step-up auth reachable with the same access token

Symptom

A stolen access token alone is enough to "confirm" a sensitive action that was supposed to require a fresh factor.

Cause

The sensitive-action endpoint checked only "is this access token valid," not "was a step-up factor verified for this specific action, recently."

Fix

Issue a separate, short-lived, purpose-scoped assertion only after the step-up factor succeeds, and require it specifically on the sensitive endpoint.

Tricky questions

Is revoking just the reused token enough?
Most people say

Yes, kill that one token and let the rest of the family keep working.

Actually

Once a token has been used twice, you cannot tell which of the two holders is legitimate and which is the attacker. Standard practice revokes the whole family, accepting that the legitimate user is logged out too, because that's safer than guessing wrong.

Does a long-lived refresh token need looser checks than an access token, since it's used less often?
Most people say

No, it's rarely used, so it's lower risk.

Actually

The opposite: a refresh token is exchanged for full access and lives far longer, so it needs single-use rotation, replay detection, and HttpOnly/Secure storage — access tokens are the lower-value target precisely because they expire fast.

Scenario question

You're handed a bug report: "users on the mobile app get logged out at random, support says it's every few hundred sessions." Refresh tokens rotate on every use, no grace window, and reuse is checked with a SELECT followed by an UPDATE. What's your hypothesis and fix, in order?

Model answer

I would first suspect the read-then-write race: two near-simultaneous refresh calls, two tabs or a retried request after a slow response, both read used = False before either writes True, so both proceed and one of the resulting tokens is later treated as reused. The cheapest fix is to make the check atomic with a single conditional UPDATE ... WHERE used = false RETURNING ..., which lets only one of the two racing requests win. I would also add a short grace window so the loser of that race gets the already-issued next token back instead of an error, since from the client's point of view it made the same logical request twice. The trade-off is that a grace window very slightly widens the time a stolen token could be replayed without detection — a few seconds I'm willing to accept for far fewer false lockouts.

Interview corner

CommonWhy rotate refresh tokens instead of reusing one until it expires?
“I'd say rotation makes each refresh token single-use, so a copy an attacker stole and hasn't used yet gets invalidated the moment the legitimate client uses its own copy, and reuse of an already-rotated token becomes a theft signal instead of silent, indefinite access.”
TrickTwo requests refresh with the same token and both succeed. What does that tell you?
“I'd say the check-and-mark wasn't atomic, so both requests read the token as unused before either marked it used. I'd fix it with a single conditional update, not a SELECT followed by an UPDATE.”
DesignHow do you decide when to require fresh reauthentication versus just checking the existing session?
“I'd reserve step-up reauthentication for actions with real blast radius, like changing a password or authorizing a payment above some limit, and issue a short-lived, action-scoped token only after that fresh check, so a stolen access token alone can't trigger it.”
Experience checkHave you dealt with a token-rotation race in practice?
“Not in production yet, but I've reasoned through exactly this bug: users getting logged out from normal multi-tab or retry behavior is a textbook symptom of reuse detection with no grace window and a non-atomic check.”

Memory hook

A refresh token is a single ride ticket that hands you the next one as you board; hand in a used ticket twice and the driver cancels the whole booklet.

If you remember only one thing:

Reuse of a rotated refresh token is a theft signal, not a bug — but make sure your own client can't accidentally trigger it.

Self-check

  1. Why does replaying an already-rotated refresh token revoke the whole family, not just that token?

    Because once a token has been used twice, the server can't tell which of the two holders is legitimate and which is the attacker, so it treats both as compromised.

  2. What makes a check-then-mark reuse check race under concurrent load?

    Reading used == False and writing used = True as two separate operations leaves a window where two concurrent requests can both read False first.

  3. Why shouldn't a stolen access token be able to satisfy a step-up authentication requirement?

    Step-up is meant to prove a fresh factor for one sensitive action; if a plain access token were enough, step-up would add no protection beyond what was already stolen.

Prove it

Extend this card's family-revocation code with a compare-and-swap style check using dict.setdefault that fails if used is already True (simulating UPDATE ... WHERE used = false), fire 100 "concurrent" rotate calls against the same starting token in a plain loop, and print how many succeeded (should be exactly 1) versus how many were rejected as reuse.

ce-04-03Card 3 of 6

Explain OAuth2 and OIDC flows end to end

HardP2 · Very likelyTalk about it13 min
oauth2oidcpkceauthorization-codeclient-credentials

Why you care

"Explain OAuth2" is close to a guaranteed interview question for any backend role touching third-party login or API access, and it's asked precisely because most candidates can say "redirect, then a token" without being able to say what a redirect URI mismatch protects against, or why an ID token and an access token aren't the same thing. On the job this shows up as "why does Google login break in staging but not prod" (a state/nonce or redirect mismatch), and as services quietly using an OAuth access token to answer "who is this user" — exactly what it can't safely tell you.

Explain like I'm 5

The authorization code flow is getting a locker key through a hotel concierge, not directly from the locker company. You ask the concierge (authorization server) for access; the concierge checks your ID with the guest (you, logging in) and hands your app a one-time claim ticket (the code); your app then goes privately, not through your browser, back to the concierge desk to swap that claim ticket for the actual locker key (the access token). OIDC adds a second item to that exchange: a signed note from the concierge saying who you are (the ID token) — the locker key itself never claims to say who you are, only what you can open.

Core concept

  • Roles (RFC 6749): resource owner (the user), client (your app), authorization server (issues tokens), resource server (the API the token is used against).
  • Authorization code grant, the default for anything with a user and a browser: (1) the client redirects the browser to the authorization server with client_id, redirect_uri, scope, state, and for public clients a PKCE code_challenge; (2) the user authenticates and approves; (3) the authorization server redirects back with a short-lived, single-use authorization code; (4) the client exchanges that code, server-to-server, at the token endpoint, sending the PKCE code_verifier; (5) it gets back an access token, optionally a refresh token, and, for OIDC, an ID token.
  • PKCE (RFC 7636) closes the gap where an authorization code sent through a browser redirect could be intercepted: the client generates a random code_verifier and sends its SHA-256 hash as code_challenge up front; it must produce the original code_verifier at the token exchange. Only the party that started the flow has the verifier, so an intercepted code alone is useless. The S256 method is mandatory to implement on the server and should be used by every public client (SPAs, mobile apps) — it's recommended now even for confidential clients with a secret.
  • state is your app's own CSRF token for the redirect: generate it, store it tied to the browser session, check it on the way back, or an attacker can trick a victim into completing the attacker's login flow.
  • nonce (OIDC-specific) binds the ID token to this one authentication request, checked inside the signed token itself, defending against ID token replay across sessions. state and nonce solve different problems and you need both.
  • Client credentials grant: no user at all — a service authenticates as itself directly to the token endpoint and gets an access token for its own service-to-service calls.
  • Access token vs ID token: the access token is a credential for the resource server, proving "this bearer may call this API with this scope," and isn't guaranteed to even be a JWT. The ID token is always a JWT, meant for the client, proving "this user authenticated, here is who they are." Never use an access token to answer "who is the user" — use the ID token or the OIDC /userinfo endpoint, and never send an ID token to a resource server as if it were an access token.
  • Validate every token the same way regardless of which flow produced it: signature, iss, aud, exp, and for ID tokens, nonce. Use a maintained OIDC/OAuth client library for this; hand-rolling validation in production is how algorithm-confusion bugs (Authentication and authorization: sessions and JWT) get shipped.

Under the hood

The PKCE code_verifier is a high-entropy random string, 43-128 characters from an unreserved character set per RFC 7636; the code_challenge sent in the authorization request is BASE64URL(SHA256(code_verifier)) under the mandatory S256 method. Because SHA-256 is one-way, anyone observing the authorization request — browser history, a referrer leak, another app on the same device intercepting the redirect — sees only the challenge, never the verifier, and can't reconstruct it. At the token endpoint the server recomputes the hash of the presented verifier and compares it to the stored challenge; a match proves the token request came from whoever made the original authorization request, not just whoever intercepted the redirect. The deprecated plain method, where challenge equals verifier, protects nothing against an observer who already saw the authorization request, which is why S256 is the one every client must support and every server should require.

Minimal example PKCE proves you started the flow, not just that you saw the code

PythonA verifier only the original requester ever heldruns
import base64, hashlib, secrets

def new_verifier() -> str:
    return secrets.token_urlsafe(64)[:96]   # within RFC 7636's 43-128 char range

def challenge_for(verifier: str) -> str:
    digest = hashlib.sha256(verifier.encode("ascii")).digest()
    return base64.urlsafe_b64encode(digest).rstrip(b"=").decode()

verifier = new_verifier()
challenge = challenge_for(verifier)          # sent up front, in the authorization request

presented_verifier = verifier
print(challenge_for(presented_verifier) == challenge)

stolen_code_only = challenge_for("attacker-guessed-or-blank-verifier")
print(stolen_code_only == challenge)
Output
True
False

In production A local stand-in for the authorization-code + PKCE + OIDC exchange

PythonSingle-use code, PKCE match, and a signed ID tokenruns
import base64, hashlib, hmac, json, secrets, time

SIGNING_KEY = b"authz-server-signing-key"
PENDING_CODES = {}   # code -> {challenge, client_id, redirect_uri, user}

def b64url(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()

def sign_id_token(user: str, client_id: str, nonce: str) -> str:
    header = {"alg": "HS256", "typ": "JWT"}
    payload = {"iss": "https://auth.example", "sub": user, "aud": client_id,
               "nonce": nonce, "iat": int(time.time()), "exp": int(time.time()) + 300}
    signing_input = b64url(json.dumps(header, separators=(",", ":")).encode()) + "." + \
                    b64url(json.dumps(payload, separators=(",", ":")).encode())
    sig = hmac.new(SIGNING_KEY, signing_input.encode(), hashlib.sha256).digest()
    return signing_input + "." + b64url(sig)

def authorize(client_id: str, redirect_uri: str, code_challenge: str, user: str) -> str:
    code = secrets.token_urlsafe(24)
    PENDING_CODES[code] = {"challenge": code_challenge, "client_id": client_id,
                            "redirect_uri": redirect_uri, "user": user}
    return code   # in reality this rides a 302 redirect back to redirect_uri

def token_exchange(code: str, code_verifier: str, client_id: str, redirect_uri: str, nonce: str):
    entry = PENDING_CODES.pop(code, None)   # codes are single-use: pop, don't peek
    if entry is None:
        raise ValueError("unknown or already-redeemed authorization code")
    if entry["client_id"] != client_id or entry["redirect_uri"] != redirect_uri:
        raise ValueError("client_id/redirect_uri mismatch: possible code injection")
    challenge = hashlib.sha256(code_verifier.encode()).digest()
    if not hmac.compare_digest(b64url(challenge), entry["challenge"]):
        raise ValueError("PKCE verifier does not match challenge")
    access_token = secrets.token_urlsafe(32)      # opaque, for the resource server
    id_token = sign_id_token(entry["user"], client_id, nonce)  # JWT, for the client
    return access_token, id_token

verifier = secrets.token_urlsafe(48)
challenge = b64url(hashlib.sha256(verifier.encode()).digest())
code = authorize("orders-web", "https://app.example/callback", challenge, user="user-42")

access, id_tok = token_exchange(code, verifier, "orders-web", "https://app.example/callback", "n0nce-1")
print("access token is opaque:", access.startswith("eyJ") is False)
print("id token is a JWT:", id_tok.count(".") == 2)

try:
    token_exchange(code, verifier, "orders-web", "https://app.example/callback", "n0nce-1")
except ValueError as e:
    print("ValueError:", e)
Output
access token is opaque: True
id token is a JWT: True
ValueError: unknown or already-redeemed authorization code

See it happen state, PKCE and nonce guard three different steps

browserappauth serverresource serverclick 'Login with provider'redirect: /authorize?state&code_challengeGET /authorize302 redirect: code + stateGET /callback?code&statePOST /token: code + code_verifieraccess_token + id_token(nonce)GET /orders (Bearer access_token)
  1. The user starts the flow from your app.
  2. state (CSRF) and the PKCE challenge travel in the URL; the verifier stays only with the app.
  3. The user authenticates directly with the provider; your app never sees the password.
  4. The code is short-lived and single-use; the app will check state matches.
  5. The app verifies the returned state before doing anything else.
  6. Server-to-server, over TLS, never through the browser.
  7. The ID token's nonce is checked against the value the app generated in step 2.
  8. The access token goes to the resource server; identity was already settled by the ID token.
Notice: state protects the redirect from CSRF, nonce protects the ID token from replay, and PKCE protects the code exchange from interception — three different attacks, three different fields, and skipping any one reopens exactly one of them.
Scenario A

In your world

The situation

Your team bolts on "Login with Google" using a three-year-old code sample: it builds the /authorize URL by hand, skips state entirely ("we don't have a CSRF problem, it's just login"), and reads the user's email straight off the access token by decoding it as if it were a JWT.

What actually breaks

In staging, login works. In prod, two things fail: some users' access tokens are provider-opaque strings, not JWTs, so decoding them crashes; and a security review flags that a crafted link can trick a logged-out victim into completing the attacker's OAuth flow in the victim's own browser, silently linking the victim's session to the attacker's account, because there's no state to check.

What you'd do on Monday

Generate and check state per attempt, and stop reading identity off the access token:

PythonNever decode an access token to answer "who is this user"runs
import secrets

PENDING_STATE = {}

def start_login(session_id: str) -> str:
    state = secrets.token_urlsafe(16)
    PENDING_STATE[session_id] = state
    return state   # goes into the /authorize URL, and nowhere else

def handle_callback(session_id: str, returned_state: str) -> bool:
    expected = PENDING_STATE.pop(session_id, None)
    return expected is not None and expected == returned_state

sid = "sess-1"
state = start_login(sid)
print("legit callback accepted:", handle_callback(sid, state))

sid2 = "sess-2"
start_login(sid2)
print("forged callback (wrong state) accepted:", handle_callback(sid2, "attacker-guessed-value"))
Output
legit callback accepted: True
forged callback (wrong state) accepted: False
Scenario B

Imagine you work at Auth0

3M logins/day, 10x sign-up spike

The numbers

Illustrative: 3M logins/day across web and mobile ≈ 35 authorization-code exchanges/second average, each needing a signature check, an issuer/audience check and, for OIDC, a nonce check against a per-attempt store; a 10x sign-up campaign spike pushes that to roughly 350/s.

What the Scenario-A answer does here

The Scenario A fix (real state and real ID-token identity) still works, but keeping pending codes, state and code_verifier in an in-process dict, as this card's demos do for clarity, doesn't survive more than one server: a user starting login on one instance and completing it on another, common behind a load balancer with no sticky sessions, finds their in-flight state on a different box entirely, and login fails.

What flips at this scale

At real scale everything this card kept in a local dict — pending codes, state, code_verifier, nonce — moves into a shared, short-TTL store keyed by a value that survives the redirect, and login load balancing must be sticky-session-free by design, not by accident.

The trade-off you'd defend

I would defend a shared short-TTL store for in-flight OAuth state over sticky sessions, trading one more infrastructure dependency for login working correctly regardless of which server handles which half of the redirect.

Illustrative figures chosen to make the arithmetic concrete; not Auth0-published numbers.

Gotchas

Reading identity off the access token

Symptom

Code that decodes the access token to get the user's email works for one provider and crashes for another.

Cause

Access tokens are meant for the resource server and aren't guaranteed to be JWTs or decodable at all; some are opaque, provider-internal strings.

Fix

Use the ID token (OIDC) or the /userinfo endpoint for identity; never assume the access token's shape.

Skipping state "because it's just login"

Symptom

A crafted link makes a victim's browser complete an OAuth flow the victim never intended, silently linking accounts.

Cause

With no state to verify, the callback can't tell "my own login attempt" from "an attacker's login attempt playing out in my victim's browser."

Fix

Generate a random state per attempt, store it server-side or in a signed cookie, and reject any callback whose state doesn't match.

Treating nonce and state as the same thing

Symptom

A team implements state and assumes OIDC replay protection is covered.

Cause

state defends the redirect against CSRF; nonce is checked inside the signed ID token to stop that specific token being replayed across a different authentication attempt.

Fix

Implement both; a maintained OIDC library does this for you if you don't hand-roll the flow.

Tricky questions

Is an OAuth2 access token proof of identity?
Most people say

Yes, if it validates, you know who the user is.

Actually

An access token proves the bearer may call an API with some scope; it says nothing guaranteed about identity. Identity is OIDC's ID token, a separate, always-JWT artifact designed for exactly that.

Does PKCE replace the need for state?
Most people say

Yes, PKCE secures the exchange so state is redundant.

Actually

PKCE protects the code-for-token exchange from interception; state protects the redirect from CSRF. They defend different steps, and skipping either reopens that step's attack.

Scenario question

You're handed a mobile app that stores a client secret in the compiled binary and uses it in the authorization code flow "for extra security." A pentest report flags this. What's wrong, and what do you change?

Model answer

A secret embedded in a distributed binary isn't secret — anyone can extract it, so it provides no real client authentication and gives a false sense of security. I would treat the mobile app as a public client: drop the client secret entirely and rely on PKCE, which was designed exactly for clients that can't hold a secret. The redirect URI should also be a custom scheme or app link registered with the authorization server, so a code can only be redeemed by the real app. The trade-off is losing client authentication as a factor, but PKCE compensates by binding the token exchange to whoever started the flow, which is the property I actually need here, not a secret the app could never protect.

Interview corner

CommonWalk me through the OAuth2 authorization code flow.
“I'd describe it as: the app redirects the browser to the authorization server with client_id, redirect_uri, state, and a PKCE code_challenge; the user authenticates there directly; the browser comes back with a one-time code and the same state; the app exchanges that code plus its code_verifier for tokens over a direct server-to-server call, never through the browser.”
TrickWhat's the difference between an access token and an OIDC ID token?
“The access token is for the resource server and proves scope, and it might not even be a JWT. The ID token is always a JWT, meant for the client, and proves who authenticated — I use the ID token or userinfo for identity, never the access token.”
TrickWhy do we need both state and PKCE?
“State stops CSRF on the redirect itself; PKCE stops a stolen authorization code being redeemed by whoever intercepted it. They protect two different points in the flow, so I implement both, not one instead of the other.”
DesignWould you hand-roll OAuth2/OIDC or use a library?
“I'd always use a maintained client library for token validation and flow handling. Hand-rolling signature and claim checks is exactly how algorithm-confusion and missing-audience bugs get shipped; I'd only write the parts specific to my app, like creating a session after a valid ID token.”

Memory hook

The authorization code is a claim ticket handed through the browser; the token exchange that redeems it happens privately, server to server, and PKCE proves you're the one holding the receipt.

If you remember only one thing:

state stops CSRF on the redirect, nonce stops ID-token replay, PKCE stops code interception — three fields, three different attacks.

Self-check

  1. What does the PKCE code_verifier prove at the token endpoint?

    That the party redeeming the authorization code is the same party that started the authorization request, since only they ever held the verifier.

  2. Which token should you use to answer "who is this user," and why?

    The OIDC ID token, or the /userinfo endpoint, because it's the artifact designed for identity; the access token is scoped for the resource server and isn't guaranteed to even be readable.

  3. What's the difference between what state and nonce each protect against?

    state protects the redirect step against CSRF; nonce is checked inside the signed ID token to prevent that specific token being replayed across a different authentication attempt.

Prove it

Extend this card's local authorization-code simulation to add a state check end to end (generate it at authorize(), require it at token_exchange()), and show three outputs: a successful flow, a rejected flow with a mismatched state, and a rejected flow reusing an already-redeemed code.

ce-04-04Card 4 of 6

Application threat boundaries: SQLi, SSRF and IDOR

MediumP1 · Must knowKnow cold13 min
sqlissrfidorparameterized-queriesleast-privilege

Why you care

Three different-looking bugs — a raw SQL string, an outbound HTTP call built from user input, and a database id taken straight from a URL — are all the same root failure: trusting a boundary that looks like data but is actually able to redirect control. SQL injection lets user input become code the database executes; SSRF lets user input become a destination your own server visits on your network's behalf; IDOR lets user input become the object an otherwise-correct, otherwise-authenticated request operates on. Interviewers ask about all three because together they cover most of a backend's actual attack surface, and because "we use an ORM" or "we validate input" are the two most common wrong answers that don't actually close any of them.

Explain like I'm 5

Imagine handing a courier a sealed envelope of instructions — "deliver this parcel to warehouse 42" — and the courier reads whatever's on the label without question. SQL injection is writing a fake instruction inside the "parcel description" field that says "...actually, open the vault first." SSRF is writing "warehouse 42" as "the guard's own house," and the courier, following instructions literally, walks right up to a door it should never approach. IDOR is asking for "package 42" and the courier handing it over without ever checking that you're the person who ordered package 42 — only that you asked politely and had a valid courier badge.

Core concept

  • SQL injection (SQLi) happens when user input is concatenated into a query string, so the database can't tell "data" from "instructions." Parameterized queries — placeholders bound separately from the SQL text — close this completely for that query, because the driver sends the value as data over the wire protocol, never as text the SQL parser reads. String formatting into SQL is the bug, regardless of how the value was "validated" beforehand; validation is not a substitute for parameterization.
  • Server-side request forgery (SSRF) happens when your server makes an outbound request — a webhook fetch, an image proxy, "import from URL" — to a destination partly or fully controlled by the user. Because the request originates inside your network, it can reach things the internet can't: internal admin panels, unauthenticated internal databases, and cloud metadata endpoints (169.254.169.254), which is how SSRF chains into credential theft.
  • Insecure direct object reference (IDOR) happens when an endpoint fetches or modifies an object by an id taken from the request, checks that the caller is authenticated, but never that the caller is authorized for that specific object. This is object-level authorization, a separate check from anything about tokens being merely valid (Authentication and authorization: sessions and JWT).
  • The unifying control is least privilege plus deny-by-default: a query should only ever run parameterized, an outbound fetch should only ever reach an allowlisted set of destinations, and an object lookup should only ever be scoped to the caller's own tenant or user by default.
  • SSRF defenses, per OWASP's SSRF Prevention Cheat Sheet, in order of strength: prefer an allowlist of exact destinations your server may call; if that's not possible, deny private/loopback/link-local ranges (127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16) and disable automatic redirect-following, re-validating the destination if you must follow one, since a validated URL can redirect to an internal one after the check passed.

Treat every user-influenced string that becomes part of a query, a URL, or an id lookup as hostile until it has passed through the mechanism that neutralizes it — parameter binding, a destination allowlist, an ownership-scoped query — not until it has merely been "checked" by a regex or a type hint.

Minimal example The same input, string-built vs parameterized

PythonData becomes code the moment you build the query with an f-stringruns
import sqlite3

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (id INTEGER, name TEXT, is_admin INTEGER)")
conn.executemany("INSERT INTO users VALUES (?, ?, ?)",
                  [(1, "asha", 0), (2, "root", 1)])

user_input = "1 OR 1=1"   # what someone typed into a "user id" field

def unsafe_lookup(uid):
    query = f"SELECT name FROM users WHERE id = {uid}"   # string-built: data becomes code
    return conn.execute(query).fetchall()

def safe_lookup(uid):
    return conn.execute("SELECT name FROM users WHERE id = ?", (uid,)).fetchall()

print("string-built query returns:", unsafe_lookup(user_input))
print("parameterized query returns:", safe_lookup(user_input))
Output
string-built query returns: [('asha',), ('root',)]
parameterized query returns: []

In production Object-scoped lookups and a destination allowlist

Python"Looks like a URL" is not the same as "safe to fetch"runs
import ipaddress
from urllib.parse import urlparse

ORDERS = {101: {"owner": "user-42", "amount": 500}, 102: {"owner": "user-77", "amount": 900}}

def get_order(caller: str, order_id: int):
    order = ORDERS.get(order_id)
    if order is None or order["owner"] != caller:   # object-level check, every time
        raise PermissionError(f"user {caller} may not access order {order_id}")
    return order

print(get_order("user-42", 101))
try:
    get_order("user-42", 102)          # authenticated, but not the owner
except PermissionError as e:
    print("PermissionError:", e)

ALLOWED_HOSTS = {"partner-webhooks.example.com"}
BLOCKED_NETWORKS = [ipaddress.ip_network(n) for n in
                     ("127.0.0.0/8", "10.0.0.0/8", "172.16.0.0/12",
                      "192.168.0.0/16", "169.254.0.0/16")]

def is_safe_fetch_target(url: str) -> bool:
    parsed = urlparse(url)
    if parsed.scheme not in ("http", "https") or not parsed.hostname:
        return False
    if parsed.hostname in ALLOWED_HOSTS:
        return True
    try:
        ip = ipaddress.ip_address(parsed.hostname)
    except ValueError:
        return False   # not on the allowlist and not a literal IP we can vet: default deny
    return not any(ip in net for net in BLOCKED_NETWORKS)

for candidate in (
    "https://partner-webhooks.example.com/notify",
    "http://169.254.169.254/latest/meta-data/",
    "http://93.184.216.34/",
    "http://internal-admin.local/",
):
    print(candidate, "->", is_safe_fetch_target(candidate))
Output
{'owner': 'user-42', 'amount': 500}
PermissionError: user user-42 may not access order 102
https://partner-webhooks.example.com/notify -> True
http://169.254.169.254/latest/meta-data/ -> False
http://93.184.216.34/ -> True
http://internal-admin.local/ -> False

See it happen A destination check that ran once is a check a redirect can outrun

host on allowlistfollow redirectURL from requestdestination check(allowlist + range deny)partner-webhooks.example.comserver fetch()302 -> 169.254.169.254
  1. A URL arrives from the request body. Nothing has been checked yet.
  2. The destination check runs once, before any network call, and the host passes because it's on the allowlist.
  3. The now-approved URL is fetched.
  4. The response is a 302 redirect to the cloud metadata address, a destination the same check would have rejected outright.
  5. A client that follows redirects automatically reaches the blocked address anyway, after the one check that would have stopped it already ran.
Notice: the destination check ran once, before the fetch; the redirect happened after. Disabling automatic redirects, or re-validating the destination on every hop, is what keeps the check honest.
Scenario A

In your world

The situation

Your Flask endpoint /api/orders/<order_id> requires a valid session, then runs SELECT * FROM orders WHERE id = %s with the order_id from the URL, and returns whatever comes back to whoever asked.

What actually breaks

The query is already parameterized, so nobody flags it in review — but nothing in the query or the handler checks that the order belongs to the logged-in user. A customer changes 42 to 43 in the URL out of curiosity and gets a stranger's order, full name and delivery address. No error, no log line, 200 OK.

What you'd do on Monday

Scope the query to the caller, not just the id, and treat "not found" and "not yours" the same way to the client:

PythonOwnership becomes part of the query, not an afterthoughtruns
import sqlite3

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE orders (id INTEGER, user_id TEXT, address TEXT)")
conn.executemany("INSERT INTO orders VALUES (?, ?, ?)",
                  [(42, "user-42", "12 MG Road"), (43, "user-77", "5 Park Street")])

def get_order_for(caller: str, order_id: int):
    row = conn.execute(
        "SELECT id, address FROM orders WHERE id = ? AND user_id = ?",
        (order_id, caller),
    ).fetchone()
    if row is None:
        raise LookupError("order not found")   # same message either way
    return row

print(get_order_for("user-42", 42))
try:
    get_order_for("user-42", 43)
except LookupError as e:
    print("LookupError:", e)
Output
(42, '12 MG Road')
LookupError: order not found
Scenario B

Imagine you work at Cloudflare

2B requests/day at the edge

The numbers

Illustrative: a WAF in front of 2B requests/day ≈ 23,000 requests/second, with roughly 0.1% carrying an injection-shaped or SSRF-shaped payload — a quoted string with SQL keywords, or a URL parameter pointing at a private IP — ≈ 23 suspicious requests/second, just under 2M/day.

What the Scenario-A answer does here

The Scenario A fixes (parameterized queries, an allowlist, ownership-scoped lookups) are still exactly correct at the application layer, but running the destination-range check as a plain per-request loop against a hand-maintained list doesn't hold across many services: one service updates its blocked-ranges list after an incident, nine others don't, and the SSRF hole reopens wherever the list went stale.

What flips at this scale

At this scale the check moves up a layer: a shared edge rule, or a shared internal library everyone imports rather than copy-pastes, enforces the destination allowlist and injection-pattern checks once, in front of every service — while application code still does its own parameterized queries and ownership checks regardless, because the edge layer is a second net, not a replacement for the first.

The trade-off you'd defend

I would defend "the app is correct on its own, and the edge is a second, centrally-updated net" over relying on the edge alone, trading one more layer to maintain for not having a single service's forgotten patch reopen the hole for everyone else.

Illustrative figures chosen to make the arithmetic concrete; not Cloudflare-published numbers.

Gotchas

A URL that "looks valid" still reaches internal services

Symptom

A webhook or image-import feature occasionally returns cloud credentials or internal admin HTML instead of the expected content type.

Cause

A URL can pass every format check — valid scheme, valid syntax — and still point at 169.254.169.254 or an internal hostname; validity of shape says nothing about the safety of the destination.

Fix

Check the resolved destination against an allowlist or a denied-ranges list (this card's is_safe_fetch_target), not just that the string parses as a URL.

Parameterized this query, forgot that one

Symptom

One endpoint is safe from SQLi; a "quick admin report" script three files over still builds SQL with an f-string.

Cause

Parameterization is a per-query discipline, not a project-wide property; one string-built query anywhere is enough.

Fix

Grep for string interpolation feeding raw SQL execution as a review checklist item, and prefer a query builder that makes parameter binding the default, not an opt-in.

A redirect after the destination check

Symptom

A destination that passed the allowlist check still ends up fetching an internal address.

Cause

The check ran once, on the original URL; the response then issued a redirect that was followed automatically without re-checking.

Fix

Disable automatic redirect-following in the HTTP client, or re-run the destination check on every redirect target before following it.

Tricky questions

Does using an ORM eliminate SQL injection risk?
Most people say

Yes, ORMs generate the SQL, so it's automatically safe.

Actually

An ORM's default query-builder methods parameterize values, but any raw-SQL escape hatch reopens the exact same risk. The ORM removes the temptation, not the possibility.

Is checking that a URL "starts with https://" enough SSRF protection?
Most people say

Yes, that rules out non-HTTP schemes, which is the main risk.

Actually

Scheme is one of several checks. https://169.254.169.254/ is perfectly valid HTTPS syntax and still reaches the cloud metadata endpoint; you also need to check the resolved host or IP against an allowlist or denied ranges.

Scenario question

You're handed an endpoint POST /reports/generate-from-url that fetches a user-supplied URL, parses it as a report template, and emails the result. Product wants it kept, but security wants SSRF closed without breaking the legitimate use case of partners hosting their own templates. What do you build?

Model answer

I would ask product for the actual set of legitimate template hosts and put those on an explicit allowlist checked against the resolved IP, not just the hostname string, since that closes the common case cleanly. For any host not on the list I would refuse rather than fall back to a denylist, because a denylist only blocks known-bad ranges and I'd rather under-serve an edge case than leave the door open. I would also disable automatic redirect-following and re-check the destination on any redirect, since the gap in this card's visual is exactly where an allowlisted host could still hand back a redirect to something internal. The trade-off is an extra step for partners, getting added to the allowlist, in exchange for the fetch never reaching anywhere I haven't explicitly approved.

Interview corner

CommonHow does a parameterized query prevent SQL injection?
“I'd say the value is sent to the database separately from the SQL text, over the driver's wire protocol, so the database never parses the value as part of the query — it's data no matter what characters it contains. String-building the query is what turns data into code.”
TrickYour app validates that a URL field is well-formed before fetching it. Is that enough to stop SSRF?
“No — a well-formed URL can still point at an internal address or the cloud metadata endpoint. I'd check the resolved destination against an allowlist or a denied-ranges list, and disable automatic redirects so a check can't be bypassed after the fact.”
CommonWhat makes IDOR different from an authentication bug?
“Authentication was fine — the user really is logged in. The bug is that the endpoint never checked whether that specific user owns the specific object they asked for. I always scope the lookup query itself to the caller, not just to a valid id.”
DesignHow would you prevent an SSRF regression across ten microservices?
“I wouldn't rely on each service copying its own denylist. I'd centralize the destination check in a shared library or an edge rule that every service goes through, so one incident's fix updates the list once, everywhere, instead of nine times.”

Memory hook

A courier who reads the label literally will deliver to the guard's own house if that's what the label says — check the destination, not just that it looks like an address.

If you remember only one thing:

Data becomes dangerous exactly where it stops being checked as data — bind it, allowlist it, or scope it to the caller, on every single access.

Self-check

  1. Why doesn't validating a URL's format protect against SSRF?

    Format validity says nothing about the destination; a syntactically valid URL can still point at an internal address or a cloud metadata endpoint.

  2. What's the one-line difference between an authentication bug and IDOR?

    Authentication confirms the caller is logged in; IDOR is missing the separate check that the caller owns the specific object requested.

  3. Why can a redirect defeat a destination allowlist check that passed?

    If the client follows redirects automatically, the response's new destination is never re-checked against the allowlist, so the original approval covers a hop it never saw.

Prove it

Take the is_safe_fetch_target function from this card, add a case where an "allowed" host's IP is looked up via a fixed local mapping (simulating DNS) and turns out to be 169.254.169.254, and show that checking the resolved IP, not just the hostname string, is what catches it. Print both the naive (hostname-only) and corrected (resolved-IP) results for the same input.

ce-04-05Card 5 of 6

Protect passwords and manage secret exposure

MediumP2 · Very likelyKnow cold14 min
password-hashingargon2secrets-managementconstant-time-compare

Why you care

A "successful" login always looks the same from the outside, whether the password check took 3ms with plain SHA-256 or 300ms with a memory-hard function you can't brute-force on a GPU farm — which is exactly why interviewers push past "we hash passwords" into "with what, and what parameters," because the wrong algorithm or a lazy work factor is invisible until a breach, and by then the damage is a cracked password list, not a bug report. The same carelessness that hashes passwords too cheaply usually also logs them, or a token, or an API key, in plaintext somewhere a hashing decision was never even asked about — secret exposure and weak hashing are the same failure of treating a credential like ordinary data.

Explain like I'm 5

Hashing a password properly is feeding it through a machine that's deliberately slow and expensive to run, one password at a time, so that trying every password in a dictionary against it takes a warehouse of machines a very long time. A "salt" means every password goes through the machine with its own unique extra ingredient mixed in, so nobody can precompute one giant table of answers and reuse it against everyone at once. Encryption is a different machine entirely: it's meant to be reversible with a key, which is exactly what you never want for a password, since nobody, not even you, should ever be able to get the plaintext back.

Core concept

  • Hashing, not encryption, for passwords: hashing is one-way by design; you never need the plaintext back, only to check a match. Encryption is reversible and is the wrong tool here, because a stolen encryption key un-does every password at once.
  • Salt every hash uniquely; modern algorithms and libraries do this automatically. It defeats precomputed rainbow tables and stops one password reused across services from producing identical hashes.
  • Use an adaptive, memory-hard algorithm with real work-factor parameters, never a fast general-purpose hash like plain SHA-256 or MD5. Per OWASP's Password Storage Cheat Sheet, current minimums are: Argon2id at 19 MiB memory, 2 iterations, 1 degree of parallelism (or an equivalent stronger setting); scrypt at N=2^17, r=8, p=1; bcrypt at a work factor of 10 or more, with a 72-byte password input limit; PBKDF2-HMAC-SHA256 at 600,000 or more iterations (220,000 for HMAC-SHA512), mainly for FIPS-140 compliance, since it's the weakest of the four against GPU/ASIC cracking because it isn't memory-hard. hashlib.scrypt has shipped in the standard library since Python 3.6.
  • Compare hashes in constant time: hmac.compare_digest, never ==, so the comparison doesn't leak how many leading bytes matched through timing.
  • Secrets are not passwords, and both need a lifecycle: API keys, DB credentials and signing keys need generation from a real source of randomness (secrets, never random), storage outside source control and logs, scheduled rotation and rotation on suspected exposure, and TLS in transit. A credential-free log is a policy, not an accident: redact secret-shaped fields before anything is written, because "we'll clean it up later" means it's already in a log aggregator, a ticket, and someone's terminal scrollback.
  • Password recovery never emails the password back (you don't have it — it's hashed) or a predictable token; it issues a single-use, short-lived, high-entropy reset token, invalidated the moment it's used or a new one is requested.

For a new password store, default to Argon2id at OWASP's minimum settings or stronger; use PBKDF2 only if a compliance requirement forces it, and bcrypt only if you're stuck on infrastructure that can't add an Argon2 library — never write your own hashing loop.

Under the hood

A fast hash like SHA-256 processes each guess in nanoseconds and needs almost no memory, which is exactly what makes it parallelize beautifully across thousands of GPU cores or a purpose-built ASIC: an attacker's cost per guess barely rises even at massive scale. Argon2id and scrypt are deliberately memory-hard — each guess must allocate and touch a real block of RAM (Argon2id's minimum 19 MiB, scrypt's 128 MiB at N=2^17) — and GPUs have far less memory per core than a CPU, so parallelizing guesses is bounded by memory bandwidth, not just compute; the same total attack now costs dramatically more in silicon, not just time. hmac.compare_digest matters for a smaller but sharper reason: a plain == on strings or bytes short-circuits at the first mismatched byte, so comparing a guess against a stored value byte-by-byte leaks, through response timing, how many leading bytes were correct — an attacker with enough samples can walk the value forward one byte at a time. compare_digest always takes the same time regardless of where the mismatch is.

Minimal example PBKDF2 with a unique salt and constant-time verification

PythonSame password twice, two different salts, two different digestsruns
import hashlib, hmac, secrets

def hash_password(password: str, iterations: int = 600_000):
    salt = secrets.token_bytes(16)
    digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, iterations)
    return salt, digest

def verify_password(password: str, salt: bytes, digest: bytes, iterations: int = 600_000) -> bool:
    candidate = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, iterations)
    return hmac.compare_digest(candidate, digest)

salt_a, digest_a = hash_password("correct horse battery staple")
salt_b, digest_b = hash_password("correct horse battery staple")
print("same password, different salt bytes:", salt_a != salt_b)
print("same password, different digest bytes:", digest_a != digest_b)
print(verify_password("correct horse battery staple", salt_a, digest_a))
print(verify_password("wrong password", salt_a, digest_a))
Output
same password, different salt bytes: True
same password, different digest bytes: True
True
False

In production Redact secrets before they're logged; make reset tokens single-use

PythonA config dict that's dangerous to log, and a token that can't be replayedruns
import secrets, time

CONFIG = {"service_name": "orders-api", "db_password": "s3cr3t!",
          "api_key": "sk_live_abc123", "region": "ap-south-1"}
SECRET_MARKERS = ("password", "secret", "key", "token")

def redact(config: dict) -> dict:
    return {k: ("***REDACTED***" if any(m in k.lower() for m in SECRET_MARKERS) else v)
            for k, v in config.items()}

print("naive log line:", CONFIG)
print("redacted log line:", redact(CONFIG))

RESET_TOKENS = {}

def issue_reset_token(user: str, ttl: int = 900) -> str:
    token = secrets.token_urlsafe(32)
    RESET_TOKENS[token] = {"user": user, "exp": time.time() + ttl}
    return token

def redeem_reset_token(token: str) -> str:
    entry = RESET_TOKENS.pop(token, None)   # single-use: pop, don't peek
    if entry is None:
        raise ValueError("reset token invalid or already used")
    if entry["exp"] < time.time():
        raise ValueError("reset token expired")
    return entry["user"]

token = issue_reset_token("user-42")
print("reset for:", redeem_reset_token(token))
try:
    redeem_reset_token(token)
except ValueError as e:
    print("ValueError:", e)
Output
naive log line: {'service_name': 'orders-api', 'db_password': 's3cr3t!', 'api_key': 'sk_live_abc123', 'region': 'ap-south-1'}
redacted log line: {'service_name': 'orders-api', 'db_password': '***REDACTED***', 'api_key': '***REDACTED***', 'region': 'ap-south-1'}
reset for: user-42
ValueError: reset token invalid or already used
Scenario A

In your world

The situation

Your Flask app stores passwords with hashlib.md5(password.encode()).hexdigest() because "it's a one-way hash, right?" and a debug log statement prints the full request body, including the password field, whenever a login fails "to help debug."

What actually breaks

MD5 has no work factor and, as used here, no application-level salt, so a leaked user table is crackable with an off-the-shelf rainbow table in minutes. Meanwhile the debug log has quietly written every failed login's plaintext password to a log aggregator retained for 90 days, for months, before anyone reviewed it.

What you'd do on Monday

Replace the hash with a proper adaptive one (this card's hash_password) and add redaction to the logging config before the next deploy, not after the next incident:

PythonRedact known-secret fields before anything is loggedruns
import logging
import sys

class RedactSecretsFilter(logging.Filter):
    MARKERS = ("password", "secret", "token", "api_key")

    def filter(self, record: logging.LogRecord) -> bool:
        if isinstance(record.args, dict):
            record.args = {k: ("***" if any(m in k.lower() for m in self.MARKERS) else v)
                            for k, v in record.args.items()}
        return True

logger = logging.getLogger("auth")
logger.propagate = False
logger.addFilter(RedactSecretsFilter())
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("%(message)s"))
logger.handlers = [handler]
logger.setLevel(logging.INFO)

logger.info("login attempt failed for %(username)s, password=%(password)s",
            {"username": "asha", "password": "hunter2"})
Output
login attempt failed for asha, password=***
Scenario B

Imagine you work at Razorpay

50M verifications/month, 4,000 rotated credentials

The numbers

Illustrative: a payments platform handling 50M password/PIN verification attempts a month ≈ 19/second average, and rotating roughly 4,000 service-level API keys and DB credentials across environments. At 300ms per PBKDF2 verification, that's well under 6 seconds of total CPU per second even at peak, but a single shared secrets store holding all 4,000 credentials becomes the one thing that, if leaked, re-exposes everything at once.

What the Scenario-A answer does here

The Scenario A fix (redact logs, use a real hash) still holds, but "each service keeps its own .env file with its DB password and API keys" — fine at one service — means 4,000 credentials live in 4,000 places, with no single point to rotate from and no way to know which services actually use which secret when one needs to be revoked after an incident.

What flips at this scale

At this scale, secrets stop being files developers manage and become records in a secrets manager with per-secret access policies, audit logs of every read, and scheduled rotation; the application asks for a secret at startup, not compile time, and rotation becomes "update one record" instead of "coordinate a deploy across every service that had it hardcoded."

The trade-off you'd defend

I would defend a centralized secrets manager with short-lived, scoped access over per-service credential files, trading a hard startup dependency, the app can't boot if the secrets service is down, for revocation and rotation that actually work under incident pressure (Configuration and secrets: precedence and feature flags).

Illustrative figures chosen to make the arithmetic concrete; not Razorpay-published numbers.

Password hashing algorithms

AlgorithmMinimum recommended parameters (OWASP)Memory-hard?Best use case
Argon2idm=19 MiB, t=2, p=1 (or equivalent)YesDefault choice for new systems
scryptN=2^17, r=8, p=1YesGood alternative; hashlib.scrypt is stdlib
bcryptwork factor >= 10PartiallyLegacy systems already using it; truncates input at 72 bytes
PBKDF2-HMAC-SHA256>= 600,000 iterationsNoFIPS-140 compliance; weakest of the four against GPU cracking

Gotchas

A fast hash "because it seemed fine in testing"

Symptom

A leaked user table gets fully cracked with commodity hardware within hours of a breach, when the hash was MD5/SHA-1/SHA-256 with no work factor.

Cause

General-purpose hashes are built to be fast; that speed is exactly what lets an attacker try billions of guesses per second per GPU.

Fix

Use Argon2id, or scrypt/bcrypt/PBKDF2 at OWASP's stated minimum parameters, never a bare cryptographic hash, for password storage.

Debug logging that "just this once" prints the request body

Symptom

A log aggregator, retained for months, contains plaintext passwords, tokens or API keys from failed-login or error logs.

Cause

A logging statement captured the whole payload for convenience, without a redaction step, and nobody revisited it once it shipped.

Fix

Add a redaction filter or formatter at the logging-config level (this card's RedactSecretsFilter), so every log line is safe by default, not by developer memory.

Comparing hashes with ==

Symptom

Nothing visibly wrong in normal testing; a timing-based credential-guessing attack works far better than it should.

Cause

== on bytes/strings short-circuits at the first differing byte, leaking timing information about how much of the guess matched.

Fix

hmac.compare_digest(a, b) for any secret comparison — hash verification, token verification, HMAC signatures.

Tricky questions

Is bcrypt still a fine choice for a brand-new system?
Most people say

Yes, it's the industry-standard password hash.

Actually

OWASP recommends bcrypt only for legacy systems that already use it; new systems should default to Argon2id. bcrypt also silently truncates passwords longer than 72 bytes, worth knowing if you don't cap input length yourself.

If passwords are hashed, does it matter if API keys are logged in plaintext?
Most people say

No, API keys aren't passwords, so the same rules don't apply.

Actually

An API key is a bearer secret just like a password; anyone who reads it can use it exactly as the legitimate holder would. It needs the same never-logged, never-in-source-control, rotated-on-exposure treatment, just not password-style hashing, since the system must present it, not just verify a match.

Scenario question

You're handed a breach report: an attacker read a database backup containing your users table, hashed with bcrypt at work factor 12. Product wants to know if they need to force a password reset for everyone. What do you tell them, and what would change your answer?

Model answer

I'd say bcrypt at work factor 12 is a reasonable, current setting, so this isn't a "your hashing was broken" incident, but stolen hashes are still stolen hashes — a sufficiently resourced attacker, or one targeting weak, common passwords specifically, will crack a meaningful fraction offline, with no way for you to detect or rate-limit that. I would recommend a forced reset for accounts with any weak-password signal, and at minimum force a reset for admin and high-privilege accounts immediately regardless of hash strength, since those are the highest-value targets. What would change my answer entirely is if the hash turned out to be MD5 or unsalted SHA-256 — then I'd recommend a mandatory reset for every account, no exceptions, because those are crackable at scale within the news cycle of the breach becoming public.

Interview corner

CommonWhy hash passwords instead of encrypting them?
“I'd say hashing is one-way by design, so I never need or want the plaintext back — I only need to check a match. Encryption is reversible, which means a single leaked key undoes every password at once; that's the wrong property for something I only ever need to verify.”
TrickYour password hashes use SHA-256 with a per-user salt. Is that good enough?
“The salt is good, but SHA-256 is a fast, general-purpose hash, built for speed, which is exactly what makes offline guessing fast too. I'd move to Argon2id, or at minimum PBKDF2 at OWASP's iteration count, because the algorithm's cost matters as much as the salt.”
CommonWhat's the difference between a secret and a password, in how you handle them?
“Both need to never be logged or committed, but a password only ever needs to be verified, so I hash it. A secret like an API key needs to be presented back to a service, so I store it encrypted at rest in a secrets manager, not hashed, and rotate it on a schedule.”
Experience checkHave you seen secrets leak through logs or a similar shortcut?
“I've seen debug logging capture full request bodies during an incident investigation, which is exactly the shortcut that leaks credentials into long-retained log storage. Since then I default to a redaction filter at the logging-config level, not a per-call discipline.”

Memory hook

Hashing a password is feeding it through a machine that's deliberately slow to run and never runs backwards; encryption is the wrong machine, because it's built to be undone.

If you remember only one thing:

The algorithm's cost is the whole point — a fast hash makes an attacker's guess cheap; a slow, memory-hard one makes every single guess expensive.

Self-check

  1. Why is encryption the wrong tool for storing passwords?

    Encryption is reversible with a key; a password store should never be able to produce the plaintext back, even for its own operators, and a leaked encryption key would undo every stored password at once.

  2. Name the four algorithms this card lists and which one OWASP recommends by default.

    Argon2id, scrypt, bcrypt, PBKDF2-HMAC-SHA256; Argon2id is the default recommendation for new systems.

  3. Why does hmac.compare_digest matter even though the values being compared are already hashes?

    == short-circuits at the first mismatched byte, leaking timing information about how much of a guess matched; compare_digest takes constant time regardless.

Prove it

Hash the same password with hashlib.pbkdf2_hmac at three different iteration counts (10,000, 100,000, 600,000), time each with time.perf_counter, and print the ratio of the slowest to the fastest. Then show all three still verify correctly against their own salt and digest, and that a wrong password fails against all three.

ce-04-06Card 6 of 6

Turn backend OWASP risks into negative tests

MediumP2 · Very likelyKnow cold12 min
owasp-top-10negative-testinginput-validationsecurity-testing

Why you care

"We follow OWASP" means nothing on its own — the Top 10 is a list of risk categories, not a checklist you tick, and turning it into something real means writing a test that actually sends the bad input and asserts the app rejects it, not a code review comment that says "looks fine." Interviewers who ask "how do you test for security" are checking whether you think in negative tests at all — most candidates can describe an attack in the abstract and have never written an assertion that proves their own code resists it. On the job this is the difference between "we think we're safe" and a CI job that fails the moment someone reintroduces a string-built query.

Explain like I'm 5

Testing the happy path is checking that a lock opens with the right key. A negative security test is checking that it does not open with a bent paperclip, a copy of a slightly different key, or no key at all — and that it fails the same way, locked, every single time you try, not "usually locked."

Core concept

  • OWASP Top 10 (per OWASP, the current edition is Top 10:2025) is a ranked list of common web-application risk categories, not a set of specific bugs: Broken Access Control, Security Misconfiguration, Software Supply Chain Failures, Cryptographic Failures, Injection, Insecure Design, Authentication Failures, Software or Data Integrity Failures, Security Logging and Alerting Failures, and Mishandling of Exceptional Conditions. Treat it as a list of categories to have at least one test for, not a spec to implement literally, and recheck the current edition before citing a number or rank from memory.
  • A negative test asserts that bad input, an unauthorized action, or an abused boundary is rejected, and rejected the same way every time: same status code, same generic error, no internal detail leaked. A suite with only happy-path tests can be 100% green and still ship every risk on this list.
  • Turning a risk into a test needs three things: the risk (which category), the control (the mechanism meant to stop it — parameterization, an allowlist, an ownership check, a hash, a claim check), and the test (a concrete payload or action, plus the exact expected rejection).
  • Concrete mapping, reusing this chapter's other cards: Injection — send ' OR '1'='1 or similar and assert a safe result, never a code path that "just works" (Application threat boundaries: SQLi, SSRF and IDOR). Broken Access Control — authenticate as user A, request user B's object, assert a denial, not the object (Authentication and authorization: sessions and JWT, Application threat boundaries: SQLi, SSRF and IDOR). Authentication Failures — assert weak, expired or tampered credentials are rejected (Authentication and authorization: sessions and JWT, Rotate refresh tokens and retire sessions). Cryptographic Failures — assert secrets aren't logged and password hashes use an approved algorithm (Protect passwords and manage secret exposure). Mishandling of Exceptional Conditions — assert an error response never includes a stack trace, a SQL fragment or an internal path.
  • Input validation is business-rule bounds, not just type checks: an amount field being a valid float isn't enough if -500 or an absurdly large value should never reach a database column or a payment processor. Test the boundaries deliberately — zero, negative, oversized, wrong type — one assertion per boundary, not one giant "garbage in" test that only proves something was rejected.

For every control this chapter names, write at least one test that proves the control activates on a real bad input. A control nobody has ever watched fail a test is a control nobody has verified exists.

Minimal example A negative test that proves a bound is enforced

Pythonunittest.TestCase, not a print statement, proves the boundary holdsruns
import io
import unittest

def validate_amount(amount):
    if not isinstance(amount, (int, float)) or isinstance(amount, bool):
        raise TypeError("amount must be a number")
    if amount <= 0 or amount > 1_000_000:
        raise ValueError("amount out of bounds")
    return amount

class TestAmountBounds(unittest.TestCase):
    def test_rejects_negative(self):
        with self.assertRaises(ValueError):
            validate_amount(-500)

    def test_rejects_oversized(self):
        with self.assertRaises(ValueError):
            validate_amount(2_000_000)

    def test_rejects_wrong_type(self):
        with self.assertRaises(TypeError):
            validate_amount("500")

    def test_accepts_valid_amount(self):
        self.assertEqual(validate_amount(499.5), 499.5)

suite = unittest.TestLoader().loadTestsFromTestCase(TestAmountBounds)
result = unittest.TextTestRunner(stream=io.StringIO(), verbosity=0).run(suite)
print("tests run:", result.testsRun, "failures:", len(result.failures), "errors:", len(result.errors))
Output
tests run: 4 failures: 0 errors: 0

In production One suite, four OWASP categories, four assertions

PythonEach test names its risk category in a comment, on purposeruns
import io
import sqlite3
import unittest

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (id INTEGER, name TEXT)")
conn.executemany("INSERT INTO users VALUES (?, ?)", [(1, "asha"), (2, "root")])

def find_user(raw_id):
    return conn.execute("SELECT name FROM users WHERE id = ?", (raw_id,)).fetchall()

ORDERS = {1: "user-42", 2: "user-77"}

def get_order(caller, order_id):
    if ORDERS.get(order_id) != caller:
        raise PermissionError("not found")
    return order_id

def safe_error_response(exc):
    return {"error": "request failed"}   # never str(exc) with internals

def log_line(fields):
    return {k: ("***" if "password" in k.lower() else v) for k, v in fields.items()}

class TestOwaspBoundaries(unittest.TestCase):
    def test_injection_payload_returns_no_extra_rows(self):
        # Injection
        self.assertEqual(find_user("1 OR 1=1"), [])

    def test_cross_tenant_object_denied(self):
        # Broken Access Control
        with self.assertRaises(PermissionError):
            get_order("user-42", 2)

    def test_error_response_hides_internals(self):
        # Mishandling of Exceptional Conditions
        try:
            raise ValueError("duplicate key on orders_pkey at /srv/app/db.py:88")
        except ValueError as exc:
            body = safe_error_response(exc)
        self.assertNotIn("orders_pkey", str(body))
        self.assertNotIn("/srv/app", str(body))

    def test_log_line_redacts_password(self):
        # Cryptographic Failures / credential exposure
        line = log_line({"username": "asha", "password": "hunter2"})
        self.assertEqual(line["password"], "***")

suite = unittest.TestLoader().loadTestsFromTestCase(TestOwaspBoundaries)
result = unittest.TextTestRunner(stream=io.StringIO(), verbosity=0).run(suite)
print("tests run:", result.testsRun, "failures:", len(result.failures))
Output
tests run: 4 failures: 0
Scenario A

In your world

The situation

Your team's test suite has 94% coverage and every PR must pass it before merge. All 200+ tests check that valid input produces the right output; there is not one test that sends bad input, a wrong user's id, or a malformed token.

What actually breaks

A refactor accidentally removes the WHERE user_id = ? clause from an order lookup while "simplifying" the query. Coverage stays at 94%, because every existing test still passes — they only ever asked for orders that existed and belonged to the right user. The IDOR ships to prod and is caught three weeks later by a customer, not by CI.

What you'd do on Monday

Add negative tests for each control this chapter's cards cover, sitting right next to the ones a refactor could break. One test would have caught this exact regression:

PythonOne negative test would have caught the regression before mergeruns
import io
import unittest

ORDERS = {101: "user-42"}

def get_order(caller, order_id):
    # a "simplified" refactor could accidentally reintroduce: return ORDERS.get(order_id)
    if ORDERS.get(order_id) != caller:
        raise PermissionError("not found")
    return order_id

class TestOrderOwnership(unittest.TestCase):
    def test_other_users_order_is_denied(self):
        with self.assertRaises(PermissionError):
            get_order("someone-else", 101)

result = unittest.TextTestRunner(verbosity=0, stream=io.StringIO()).run(
    unittest.TestLoader().loadTestsFromTestCase(TestOrderOwnership))
print("failures:", len(result.failures))
Output
failures: 0
Scenario B

Imagine you work at PhonePe

400M transactions/day, 150 services

The numbers

Illustrative: a payments backend processing 400M UPI transactions/day across roughly 150 services, at a peak of about 4,600 transactions/second. If each service's suite has, say, 20 negative tests covering this chapter's boundaries, that's 3,000 negative tests guarding the whole system, and a single service missing even one ownership-check test is one place where the other 149 services' correctness doesn't help.

What the Scenario-A answer does here

The Scenario A fix (write the missing negative test where the bug would have been caught) still works per-service, but writing them ad hoc, one engineer's judgment call per PR, across 150 services means coverage of "which OWASP category has a test" varies wildly service to service, and nobody can answer "are we covered" without reading 150 test files.

What flips at this scale

At this scale the checklist itself becomes a shared, versioned artifact: a small internal library of reusable negative-test fixtures — a standard injection payload set, a standard cross-tenant-access assertion helper, a standard "no stack trace in the error body" assertion — that every service imports, so "add the ownership test" is one line, not a bespoke test written from memory each time.

The trade-off you'd defend

I would defend a shared, imported negative-test toolkit over trusting each team to remember and reimplement the same checks, trading a small coordination cost, the toolkit needs an owner, for the ability to answer "are we covered" across 150 services in one query instead of 150 code reviews.

Illustrative figures chosen to make the arithmetic concrete; not PhonePe-published numbers.

Gotchas

High coverage percentage, zero negative tests

Symptom

Coverage stays green through a regression that reintroduces a known risk, like a missing ownership check or a string-built query.

Cause

Coverage percentage measures lines executed, not classes of input tried; a suite of only happy-path tests can execute every line while never trying the input that breaks it.

Fix

Track "categories with at least one negative test" as its own signal, separate from line coverage, and treat a missing one as a gap regardless of the percentage.

A negative test that asserts "something" was rejected

Symptom

A test passes even after the specific control it was meant to guard is removed, because a different, unrelated exception happens to satisfy a broad assertion.

Cause

Asserting too generically, any exception or any non-success status, instead of the specific error the control is supposed to raise.

Fix

Assert the specific exception type or status code, not just "it wasn't a success."

Treating the OWASP Top 10 as a fixed spec to implement literally

Symptom

A team debates category rank or exact wording as if it were a compliance checklist to tick off once.

Cause

The Top 10 is a periodically revised awareness document summarizing common risk categories, not a numbered legal spec.

Fix

Use it to make sure a test exists for each category relevant to your app, and recheck the current edition rather than citing an old one from memory.

Tricky questions

Does 100% line coverage mean the security-relevant paths are tested?
Most people say

Yes, 100% coverage means every line, including error handling, has been exercised.

Actually

Coverage measures which lines ran, not which inputs were tried. A line that raises PermissionError can be "covered" by a test that never actually attempts unauthorized access, if some other path happens to trigger it.

Is a WAF or scanner enough to claim "we're covered" for these categories?
Most people say

Yes, an automated scanner catches known attack signatures, so manual negative tests are redundant.

Actually

A scanner or WAF (Application threat boundaries: SQLi, SSRF and IDOR's scale card) is a second net for known patterns; it doesn't verify your specific business logic, like whether this endpoint's ownership check is present. Only a test written against your own code proves your own control exists.

Scenario question

You're handed a legacy service with 80% line coverage and no security-specific tests at all. You have one day before a release freeze. Where do you spend it?

Model answer

I would not chase a coverage number. I'd map the service's actual attack surface first — every place it takes user input into a query, every place it looks up an object by id, every place it logs or returns an error — against this chapter's categories, and write exactly one negative test per gap I find, prioritizing whichever missing control has the largest blast radius, cross-tenant data access over a cosmetic input-length check, say. I would rather ship four sharp negative tests that each prove a real control exists than spend the day chasing a percentage that says nothing about whether bad input is actually rejected. The trade-off is that I'm consciously leaving lower-risk gaps untested until next cycle, and I'd say so explicitly rather than implying the service is now "secure."

Interview corner

CommonHow do you test for security issues, concretely?
“I'd write negative tests: send the bad input, the wrong user's id, or the tampered token, and assert it's rejected the same way every time. I map each test to a specific control, like parameterization or an ownership check, not to a vague 'security testing' bucket.”
TrickYour suite has 95% coverage. Are you covered against OWASP-style risks?
“Not necessarily — coverage tells me which lines ran, not which malicious inputs were tried. I'd check separately whether there's at least one negative test per relevant risk category, since a happy-path-only suite can hit 95% and still miss every one of them.”
CommonGive me an example of turning a specific OWASP risk into a test.
“For broken access control, I'd authenticate as user A, request an object I know belongs to user B, and assert I get a denial, never the object. For injection, I'd send a payload like ' OR '1'='1 into whatever field reaches a query and assert it returns no extra rows.”
DesignHow would you keep negative-test coverage consistent across many services?
“I'd build a small shared library of reusable negative-test helpers, a standard injection payload set, a standard cross-tenant assertion, so each team imports rather than reinvents them, and I could grep across services to see who's missing which one.”

Memory hook

A negative test is checking that the lock stays locked for the wrong key, every single time, not just that it opens for the right one.

If you remember only one thing:

A green suite with zero negative tests has proven nothing about any risk on this list.

Self-check

  1. Why can a service have high line coverage and still be exposed to every risk in this chapter?

    Coverage measures which lines executed; a suite of only happy-path tests can execute every line without ever trying the malicious input a control is meant to reject.

  2. What three things does turning a risk into a test require?

    The risk (which category), the control (the mechanism meant to stop it), and the test (a concrete payload or action plus the exact expected rejection).

  3. Why assert a specific exception type instead of a bare "some exception was raised"?

    A broad assertion can pass even after the specific control is removed, if some unrelated error happens to satisfy it; asserting the specific type proves the intended control actually fired.

Prove it

Pick one endpoint or function from your own current project. Write one negative test per category this card lists that plausibly applies to it, at minimum injection, access control, and error-response leakage, run the suite, and paste the pass/fail summary. Then deliberately remove one control and show the corresponding test turns red.