Avoid user enumeration in auth errors
Learn why a login must answer the same generic 401 whether the email is unknown or the password is wrong, and how different messages let an attacker list real accounts
A login form asks for two things, an email and a password, and there are two ways it can fail: the email belongs to nobody, or the password is wrong. A helpful-sounding server tells the user which one it was. That helpfulness is a leak. An attacker who can tell the two failures apart can feed the form a list of email addresses and sort them into real accounts and invented ones, without ever knowing a password. That sorted list is called user enumeration, and this page is about closing it: every failed login answers the same generic 401, no matter which half of the pair was wrong.
Where This Fits
The login handler built earlier checks the password and returns Unauthorized when the check fails. This page is the reason that single variant covers both failures. The handler already has the shape right, one error for the whole login, and this page explains the attack that shape stops, the subtler leaks that survive a generic message, and the timing fix that closes the last of them.
Think of a reception desk that answers the phone. A caller asks for a person by name. If the desk says "there is nobody here by that name" for strangers and "that person is out" for staff, the caller can read the whole staff list out of the desk one name at a time. A desk that always says "we cannot connect you" gives nothing away. The login handler is that desk.
The Smallest Working Version
The wrong version first, because the mistake is the lesson. A login that names the failure hands an attacker a sorting machine:
// Wrong - each message names which half of the login failed
pub async fn login(
State(state): State<AppState>,
Json(input): Json<LoginInput>,
) -> HandlerResult<Json<TokenPair>> {
let row = sqlx::query_as::<_, (i32, Option<String>, String)>(
"SELECT id, password_hash, role FROM users WHERE email = $1",
)
.bind(&input.email)
.fetch_optional(&state.pool)
.await?;
let Some((user_id, Some(password_hash), role)) = row else {
return Err(AppError::ValidationError("no account with that email".to_string()));
};
if !verify_password(&input.password, &password_hash) {
return Err(AppError::ValidationError("wrong password".to_string()));
}
// ... issue tokens
}
Two different messages, and worse, two different statuses: 422 for the unknown email and 422 for the wrong password, but with different text, so a script can sort them either way. The fix is one variant for both failures, with one status and one body:
pub async fn login(
State(state): State<AppState>,
Json(input): Json<LoginInput>,
) -> HandlerResult<Json<TokenPair>> {
let row = sqlx::query_as::<_, (i32, Option<String>, String)>(
"SELECT id, password_hash, role FROM users WHERE email = $1",
)
.bind(&input.email)
.fetch_optional(&state.pool)
.await?;
let (user_id, password_hash, role) = match row {
Some((id, Some(hash), role)) => (id, hash, role),
Some((_, None, _)) => return Err(AppError::Unauthorized),
None => {
// Run a full dummy hash so an unknown email costs about the
// same time as a wrong password, instead of answering instantly.
let _ = hash_password_argon2("dummy-password-for-timing");
return Err(AppError::Unauthorized);
}
};
if !verify_password(&input.password, &password_hash) {
return Err(AppError::Unauthorized);
}
let secret = jwt_secret();
let access_token = issue_access_token(user_id, &role, &secret)?;
let (plain, hash) = new_refresh_token();
store_refresh_token(&state.pool, user_id, &hash).await?;
Ok(Json(TokenPair {
access_token,
refresh_token: plain,
}))
}
Every failure path returns AppError::Unauthorized, which the shared error conversion turns into status 401 and the body {"error": "unauthorized"}. The client sees one answer for every kind of failure, and the server log keeps the detail, because the distinction is useful for debugging and useless to the person at the keyboard.
Working Setup:
If an unknown email and a wrong password produce the same status code and the same response body, byte for byte, the login no longer leaks account existence through its answers. The test near the end of this page checks exactly that equality.
How the Attack Works
Enumeration needs no password, no special tool, and no access to the server. The attacker takes a list of email addresses, from a breach, a company directory, or a guess at a common pattern, and sends one login attempt per address with any password. Each response is one bit of information: this address exists, or it does not. A thousand attempts cost minutes, and the result is a list of real accounts.
That list is valuable on its own. It feeds phishing emails that name a real service the victim actually uses. It feeds credential stuffing, where passwords leaked from one site are tried against the same email on this one. And it feeds targeted password guessing against the accounts that matter, instead of wasting attempts on addresses that were never registered. The login form is the cheapest source of that list, because it is public by design and answers every question put to it.
The attack works on any difference, not only on different words. A different status code leaks the same bit. A different response time leaks it. A different response length leaks it. Even a redirect to a different page leaks it. The rule is not "use the same words", it is "make the two failures indistinguishable in every way the caller can observe".
Attacker tries asha@example.com with a wrong password
|
v
Server answers 401 {"error": "unauthorized"}
|
v
Attacker tries nobody@example.com with a wrong password
|
v
Server answers 401 {"error": "unauthorized"}
|
v
Attacker learns nothing - both answers are identical
Why the Generic Answer Costs So Little
The usual objection is that a real user who mistypes their email gets no help. That is true, and it is a small cost. A real user knows their own email address, and a mistyped one is fixed by reading the form again. The user who benefits from "no account with that email" is the one who forgot which address they registered with, and that person is helped just as well by a password reset flow that sends a message to the address if it exists. The attacker, meanwhile, loses the cheapest way to harvest the user list. A small inconvenience for a forgetful user buys a real defence for every account.
The same reasoning applies to the message text. "unauthorized" says nothing about which half failed, and that is the whole point. It is the same word the error variant already uses for a missing or bad token, so the login failure and the token failure are indistinguishable too, which is a second leak closed for free.
The Server Log May Know More:
The generic answer is for the client, not for the operator. The server log can record that the email was unknown or that the password did not match, because the log is not visible to the attacker. Keep the detail in the log and the sameness in the response. A handler that logs nothing is harder to debug, and a handler that tells the client everything is easier to attack.
The Timing Leak
A generic message closes the visible leak, and a timing difference reopens it invisibly. Consider the two paths through the handler. For a known email with a wrong password, the handler runs a password check, which takes a noticeable amount of time, because password hashing is deliberately slow. For an unknown email, the handler finds no row and returns at once. An attacker who measures response times can sort the addresses by speed: slow means the account exists, fast means it does not.
The fix is to spend the same time on both paths. When the email is unknown, the handler runs a full dummy hash of a fixed string before returning, so the unknown-email path costs about the same as a real password check:
None => {
let _ = hash_password_argon2("dummy-password-for-timing");
return Err(AppError::Unauthorized);
}
The dummy password is a constant string that no real user has, and its hash is thrown away. What matters is the work, not the result. A sleep would not do as well, because the real check's duration varies with the machine load, while a hash on the same machine varies the same way. The dummy hash tracks the real cost automatically.
This is a mitigation, not a proof. Timing measurements over a network are noisy, and a single request tells an attacker almost nothing. But a patient attacker who averages thousands of measurements can still separate two paths whose average times differ, so the dummy hash is worth doing, and it costs one line. The same idea applies to any handler with a fast failure path and a slow success path: make the failure do the same work.
The Same Rule in Signup and Password Reset
Login is not the only form that can leak existence. A signup form that answers "this email is already registered" tells an attacker the same thing the login form would. The safe signup answers every attempt the same way, and sends a message to the address only if an account already exists, saying the account exists and offering a password reset. The person who actually owns the address learns what happened from their inbox, and the attacker learns nothing from the response.
A password reset form follows the same rule. It always answers with the same message, something like "if an account exists for this email, a reset link has been sent", and it sends the link only when the account is real. A form that says "no account with that email" is the enumeration leak wearing a different label.
These two forms belong to other pages in the chapter, and they are mentioned here only because the rule is one rule, not three: any response that differs by whether an account exists is a leak, whatever the form is called.
Validation Errors Are Not Existence Leaks:
A signup form may still reject a malformed email, like one with no @ sign, or a password shorter than the minimum. Those errors describe the shape of the input, not whether an account exists, and they are safe. The line is between "this input is badly formed" and "this account exists". Keep the first, remove the second.
Testing That the Two Failures Are Identical
The test below ran against live Postgres and passed. It sends the two failing logins and compares the full answers, not just the status. The call helper builds a request against the router in memory and returns the status code and the parsed JSON body:
let (status_unknown, body_unknown) = call(
app.clone(), "POST", "/login", None,
json!({"email": "nobody@example.com", "password": "whatever"}),
).await;
let (status_wrong, body_wrong) = call(
app.clone(), "POST", "/login", None,
json!({"email": "asha@example.com", "password": "wrong-pass"}),
).await;
assert_eq!(status_unknown, StatusCode::UNAUTHORIZED);
assert_eq!(status_unknown, status_wrong);
assert_eq!(body_unknown, body_wrong);
assert_eq!(body_unknown, json!({"error": "unauthorized"}));
Comparing the bodies for equality is the important assertion. Comparing only the status would miss a leak through different message text, and comparing only the text would miss a leak through different statuses. The test also confirms the correct login still succeeds with the same handler, so the generic error did not break the happy path.
Rate limiting is a separate defence that pairs well with this one. Limiting login attempts per address and per IP slows an attacker who tries thousands of addresses, while the generic error makes each attempt uninformative. Either defence alone is weaker: a rate limit without a generic error still leaks one bit per allowed attempt, and a generic error without a rate limit still lets an attacker average timing measurements over unlimited attempts. Together they make enumeration slow and unrewarding.
Common Beginner Mistakes
Different messages for the two failures
// Wrong - the attacker sorts addresses by the message text
return Err(AppError::ValidationError("no account with that email".to_string()));
return Err(AppError::ValidationError("wrong password".to_string()));
This is the original mistake, and it is the one this page exists to remove. One variant, one message, for both failures.
Different statuses for the two failures
// Wrong - the status alone is enough to sort the addresses
// unknown email -> 404, wrong password -> 401
A 404 for an unknown email and a 401 for a wrong password leaks the same bit as the messages did. Both failures are 401, because both mean the server does not know who is asking. A missing account is not a missing resource in the sense the 404 variant means.
Returning instantly for an unknown email
// Wrong - fast means unknown, slow means known
None => return Err(AppError::Unauthorized),
The message is generic, but the timing is not. The dummy hash in the correct version exists for exactly this case. Any handler that skips the slow step on one path and runs it on the other has this leak.
Leaking existence through the signup form
// Wrong - the same leak, one page over
if email_exists(&input.email) {
return Err(AppError::ValidationError("email already registered".to_string()));
}
The rule does not stop at the login route. Every public form that takes an email must answer the same way whether the address exists or not.
Telling the user too much in a "helpful" error
// Wrong - detail that helps the attacker more than the user
return Err(AppError::ValidationError(
"wrong password for asha@example.com, 3 attempts left".to_string(),
));
An error that names the account, counts the attempts, or hints at the password policy gives an attacker facts to work with. The client gets the generic 401. The log gets the detail.
Final Complete Example
The finished login handler, with the generic error, the dummy hash, and the token issue in one place:
pub async fn login(
State(state): State<AppState>,
Json(input): Json<LoginInput>,
) -> HandlerResult<Json<TokenPair>> {
let row = sqlx::query_as::<_, (i32, Option<String>, String)>(
"SELECT id, password_hash, role FROM users WHERE email = $1",
)
.bind(&input.email)
.fetch_optional(&state.pool)
.await?;
let (user_id, password_hash, role) = match row {
Some((id, Some(hash), role)) => (id, hash, role),
Some((_, None, _)) => return Err(AppError::Unauthorized),
None => {
let _ = hash_password_argon2("dummy-password-for-timing");
return Err(AppError::Unauthorized);
}
};
if !verify_password(&input.password, &password_hash) {
return Err(AppError::Unauthorized);
}
let secret = jwt_secret();
let access_token = issue_access_token(user_id, &role, &secret)?;
let (plain, hash) = new_refresh_token();
store_refresh_token(&state.pool, user_id, &hash).await?;
Ok(Json(TokenPair {
access_token,
refresh_token: plain,
}))
}
The handler needs one helper from the password pages, a function that hashes a password with argon2 and returns the encoded hash string:
fn hash_password_argon2(password: &str) -> Result<String, AppError> {
let hash = Argon2::default()
.hash_password(password.as_bytes())
.map_err(|_| AppError::InternalError)?;
Ok(hash.to_string())
}
Summary
The rule on this page is a single sentence that generalises further than login: a public response must never vary with a fact the caller is not allowed to know. The login form applies it to account existence, and the same sentence covers signup, password reset, and any future form that takes an identifier. The check for a reader's own code is mechanical: send the two failing requests, compare the status, the body, and the rough timing, and fix whatever differs. A login that passes that check has not made the app unbreakable, but it has taken away the cheapest source of its user list, and that is a defence worth more than the helpful message it replaces.