A FastAPI login endpoint built on OAuth2PasswordRequestForm sends the same 401 for unknown users and wrong passwords, yet response times reveal which usernames exist; why, and what fixes it?
answer
- what the unknown-user branch skips
- a deliberately slow hash
- equal work on every branch
- one hash built at import
basics
~20 sThe unknown-user branch returns before the slow Argon2 verify, so it answers far faster than a real account. Verify the submitted password against a DUMMY_HASH on that branch, and keep the 401 detail and headers identical.
solid answer
~40 sIn the naive `authenticate_user`, a missing user returns `False` at once, while an existing one runs `password_hash.verify`, an Argon2 check that is deliberately slow. Identical messages do not help: an attacker times `POST /token` and sees which usernames are real. The FastAPI docs fix it by building `DUMMY_HASH = password_hash.hash("dummypassword")` once at import, from the same `PasswordHash.recommended()` instance, and calling `verify_password(password, DUMMY_HASH)` on the unknown branch before returning `False`. Both branches then do one Argon2 verify. The endpoint must also answer both cases with the same 401, the same `detail` and the same `WWW-Authenticate: Bearer`, and the dummy must use the same parameters as the stored hashes, or the gap returns.
code
python · 25 linesfrom pwdlib import PasswordHash
from pydantic import BaseModel
password_hash = PasswordHash.recommended() # Argon2id with pwdlib's defaults
# Built once at import, with the same hasher and parameters as real hashes.
DUMMY_HASH = password_hash.hash("dummypassword")
class UserInDB(BaseModel):
username: str
hashed_password: str
USERS = {"ana": UserInDB(username="ana", hashed_password=password_hash.hash("s3cret"))}
def authenticate_user(username: str, password: str) -> UserInDB | None:
user = USERS.get(username)
if user is None:
password_hash.verify(password, DUMMY_HASH) # same work, result ignored
return None
if not password_hash.verify(password, user.hashed_password):
return None
return usergo deeper
Recall that a login route must answer unknown usernames and wrong passwords the same way, in content and in timing.
Explain why the unknown branch is fast, what DUMMY_HASH is, where the docs build it and why it comes from the same PasswordHash instance.
Review a real login route for every way the branches can diverge: hasher and cost, early returns, distinct statuses, legacy hashes, and how a test proves they match.
Treat account enumeration as a property of the whole sign-in surface, login, registration and reset, and decide which endpoints may reveal existence at all.
## Where the leak is A login endpoint has two ways to fail: the username does not exist, or it exists and the password is wrong. The FastAPI docs answer both with the same `HTTPException`: status 401, `detail` "Incorrect username or password", `WWW-Authenticate: Bearer`. That hides the reason in the **body**, but not in the **time**. Follow the naive code path: 1. The endpoint receives `form_data` from `OAuth2PasswordRequestForm`. 2. `authenticate_user` looks the username up. 3. If there is no user, it returns `False` immediately. 4. If there is one, it calls `password_hash.verify(password, user.hashed_password)`. 5. Either way the endpoint raises the same 401. Step 4 is the expensive part on purpose. `PasswordHash.recommended()` from pwdlib uses **Argon2id** (the hashes start `$argon2id$v=19$m=65536,t=3,p=4$`), a function built to be expensive: with these parameters each check uses 64 MiB of memory and, on typical hardware, tens of milliseconds, so stolen hashes are slow to crack. Step 3 costs almost nothing. In a local run of the docs' example with the dummy verify removed, a wrong password took about 25 ms and an unknown username under 1 ms. A gap that size can survive network jitter once requests are repeated and averaged, so an attacker can sort a list of candidate usernames into real and fake without guessing any password. | Branch | Work without the fix | Work with the fix | Response | |---|---|---|---| | Unknown username | a dictionary or database miss | the same miss plus one Argon2 verify | 401, same detail | | Known user, wrong password | lookup plus one Argon2 verify | unchanged | 401, same detail | | Known user, right password | lookup, verify, token signing | unchanged | 200 with the token | ## The fix in FastAPI's docs The docs' JWT tutorial adds two lines: - At import time: `DUMMY_HASH = password_hash.hash("dummypassword")`, built from the same `password_hash` instance as every stored hash. - In `authenticate_user`, on the unknown branch: `verify_password(password, DUMMY_HASH)` before `return False`. The result is ignored; the point is the work. Now both failing branches perform one lookup and one Argon2 verification, and their timings converge. The docs state the purpose directly: the endpoint takes roughly the same time whether the username is valid or not, which prevents timing attacks used to enumerate usernames. ## Keeping the branches indistinguishable The fix holds only while the branches stay alike. When reviewing a FastAPI login route, check: - **Same hasher, same parameters.** pwdlib reads the parameters from the hash string, so a dummy built by a cheaper hasher, or with weaker settings, verifies faster than real hashes. If a team later raises the Argon2 cost, accounts still holding old hashes verify at the old speed until they are rehashed; pwdlib's `verify_and_update` returns a replacement hash on login for that purpose. - **Build it once.** Computing the dummy inside the request adds a full hash to the unknown branch and makes it slower than the known branch, a leak in the other direction. - **Same response.** One status, one `detail`, one header set. A 404 for unknown users, or a different message, undoes the fix without any timing at all. - **No shortcut before the verify.** A check such as "account disabled, return early" placed before the password verify recreates the gap for that group. The docs check `disabled` later, in `get_current_active_user`, after a token exists. ## Checking it A test can post to `/token` with `fastapi.testclient.TestClient` for a known username and an unknown one, repeat each several times, and compare medians; they should be close, not an order of magnitude apart. A cheaper unit test asserts that the verify function is called on the unknown branch. Keep any timing assertion's tolerance generous, because shared build machines are noisy; the unit test is the guard that fails reliably when someone later removes the dummy verify. ## What the fix does not cover - **Other endpoints.** Registration ("username taken") and password reset can reveal existence on their own; each needs its own answer. - **Guessing.** The dummy verify hides which usernames exist; it does not slow password guessing. Rate limits and lockout policy are separate controls. - **The event loop.** pwdlib's verify is synchronous and CPU-heavy. Called from an `async def` endpoint, as in the docs, it holds the event loop for its duration, a capacity question covered with blocking work in FastAPI.
- Why build DUMMY_HASH once at import instead of hashing a dummy password on each failed lookup?Hashing inside the request adds a full Argon2 hash to the unknown branch, on top of the verify. That branch then takes roughly twice as long as a wrong password for a real user, so the timing leak returns with the sign reversed. A hash built once costs nothing per request.
- Does the dummy verify still help if the login route checks user.disabled before verifying the password?Only partly. An early return for disabled accounts skips the verify for that group, so they answer fast and can be told apart, and a distinct message reveals them outright. Verify the password first and decide about the account afterwards; the FastAPI docs leave the disabled check to `get_current_active_user`.
- How would you test that a FastAPI login route keeps the two failure branches alike?Use `TestClient` to post repeated wrong-password logins for a known and an unknown username and compare median times, expecting them to be close. Add a unit test that the verify function runs on the unknown branch and that both responses have the same status, `detail` and headers.
A shop clerk who says 'I can't find that order' instantly for made-up numbers, but only after a slow trip to the stockroom for real ones, gives away which numbers are real. The fix is to walk to the stockroom every time.
- Identical error messages alone stop username enumeration
- Answering 404 for unknown usernames and 401 for wrong passwords
- Building the dummy hash with a cheaper hasher than stored hashes
- Timing differences this small cannot be measured over a network
- The dummy verify replaces rate limiting on the login route