Password
Argon2id hashing with a random salt and burn_verify on the miss path — timing never distinguishes a wrong password from an absent account.
A password-login service does three things: store a hash on signup, compare it on signin, and refuse a login without telling the attacker whether the email exists. The framework ships three small helpers that cover the cryptography and the timing-attack mitigation — everything else (lockouts, registration policy, mailers) belongs to your service.
The helpers wrap the argon2 crate at a
pinned work factor — Argon2id, m = 19 MiB, t = 2, p = 1, the OWASP
Password Storage Cheat Sheet’s recommendation — rather than riding the
crate’s defaults, which an upstream release could lower without a line
changing here.
Three functions
Section titled “Three functions”use nest_rs::authn::{hash_password, verify_password, burn_verify};use nest_rs::core::Secret;
let hash: Secret<String> = hash_password("hunter2")?;let ok: bool = verify_password(hash.expose_secret(), "hunter2")?;burn_verify("anything"); // runs a verify against a dummy hash| Function | Returns | Use |
|---|---|---|
hash_password(&str) | Result<Secret<String>, PasswordError> | Store it as is on signup, in a Secret<String> column |
verify_password(&hash, &str) | Result<bool, PasswordError> | Compare on signin |
burn_verify(&str) | () | Run on the miss path so timing matches |
hash_password draws a fresh 16-byte salt from the system CSPRNG on every
call — the PHC specification’s recommended length — so you never reuse a
salt and never store one separately. The returned string encodes the
PHC-format hash, salt, and parameters in one self-describing column, and
verify_password reads the parameters back out of it: moving the pinned
work factor never invalidates a credential already stored. It comes back a
Secret, so a Debug or a log line that reaches it prints <redacted>, never
the hash an offline attack starts from; expose_secret() reads it where a
&str is due.
Signup — hash then store
Section titled “Signup — hash then store”use nest_rs::authn::{AuthError, CredentialError, burn_verify, hash_password, verify_password};// …
pub(crate) fn prepare_new_user( input: CreateUser, org_id: Uuid, password: Option<&str>,) -> Result<entity::ActiveModel, ServiceError> { input.validate()?; let password_hash = match password { Some(plain) => Some( hash_password(plain) .map_err(|e| ServiceError::internal_because("password hashing failed", e))?, ), None => None, }; Ok(active_for_new_user(input, org_id, password_hash))}Validation runs first, so a malformed signup never pays for a hash. A failed
hash is ServiceError::internal_because — a 500 whose detail and the
hasher’s own error reach the operator’s log line as one chain, while the wire
carries a constant message.
Signin — burn on every miss path
Section titled “Signin — burn on every miss path”The naïve signin path leaks existence: an absent email returns in microseconds, a present one takes ~50ms to hash and compare. An attacker probes the timing and enumerates the user base.
burn_verify runs a real Argon2 verify against a static dummy hash so
every miss path takes the same wall-clock time as a real verify:
pub(crate) fn verify_credentials( user: Option<entity::Model>, password: &str,) -> Result<entity::Model, CredentialError> { let Some(user) = user else { burn_verify(password); tracing::warn!(target: crate::users::TARGET, reason = "unknown_email", "login failed"); return Err(CredentialError); };
let Some(ref hash) = user.password_hash else { burn_verify(password); tracing::warn!(target: crate::users::TARGET, user_id = %user.id, reason = "no_password_set", "login failed"); return Err(CredentialError); };
match verify_password(hash.expose_secret(), password) { Ok(true) => Ok(user), Ok(false) => { tracing::warn!(target: crate::users::TARGET, user_id = %user.id, reason = "bad_password", "login failed"); Err(CredentialError) } Err(e) => { tracing::error!(target: crate::users::TARGET, user_id = %user.id, error = %error_message(&e), reason = "unverifiable_hash", "login failed"); Err(CredentialError) } }}Four things in that snippet are the rule rather than the style, and each was a defect before it was a habit:
verify_passwordis matched, neverunwrap_or(false). A stored hash that cannot be parsed is not a wrong password — folding the two loses theerrorevent and reports a broken record as an ordinary miss.- The target is
features::users, notnest_rs::authn. A span target names the crate that emitted the event; app code writing a framework target makes the event unattributable. - The address typed never reaches the line. A known account is named
by its
user_id, which the app minted; an unknown one by itsreasonalone. What the client typed is a payload value — even its domain would land in exactly the log an incident query reads. - Every line carries a
reason. Three identical"login failed"warns tell an operator nothing about which path fired.
Three miss paths, three calls — none distinguishable from the wire:
- No user with that email →
burn_verify, returnCredentialError. - User found but no
password_hash(OAuth-only account) →burn_verify, returnCredentialError. - Hash exists, password wrong →
verify_passwordalready ran (real Argon2 work), returnCredentialError.
The dummy hash is computed once and cached in a OnceLock so the
first burn pays the hash cost and every subsequent burn reuses it.
CredentialError — opaque by design
Section titled “CredentialError — opaque by design”Every failure a credential causes returns the same CredentialError, whose
Display is the fixed string "invalid credentials": wrong email, wrong password,
no password set, a stored hash that will not parse. A store that does not answer
decided nothing about the credential, so it stays AuthError::Unavailable, a 503:
#[derive(Debug, Clone, thiserror::Error)]#[error("invalid credentials")]pub struct CredentialError;A login endpoint turns it into 401, with the bare WWW-Authenticate: Bearer RFC 9110 asks of every 401 and nothing more: a wrong password is
no call to discover an authorization server, so a protected resource
server adds no pointer to
it. A token endpoint serving the
password grant wraps it in TokenError::InvalidGrant instead — RFC 6749
§5.2 assigns rejected resource-owner credentials to invalid_grant (400)
and reserves invalid_client for a failure of the client’s own
authentication: a 401 with a Basic challenge when the client
authenticated over HTTP Basic, a 400 otherwise. The two are not
interchangeable, and the status differs, so pick by which endpoint you are
serving. The tracing::warn! calls in
verify_credentials capture the actual reason for operators — they
never reach the client.
PasswordError — hashing-level failures
Section titled “PasswordError — hashing-level failures”hash_password and verify_password return PasswordError:
| Variant | Meaning |
|---|---|
HashFailed(cause) | Argon2 refused to hash (rare — usually an OOM or RNG failure); cause says which |
InvalidHash(cause) | The stored string is not a hash Argon2id can run — it did not parse as PHC, or names an algorithm, version or parameters the hasher refuses (schema drift or corruption); cause says which. Only a mismatch is Ok(false) |
cause is the hasher’s error behind an Arc<dyn Error + Send + Sync>: log
the chain with nest_rs::core::error_message, or downcast source() if you
need the hasher’s own type. Match a variant with a pattern, never ==.
A login service collapses both into CredentialError so the wire
stays uniform; only the stored-hash-corrupt case logs distinctly.
What the helpers do not cover
Section titled “What the helpers do not cover”- Lockouts and rate-limiting. Pair signin with
ThrottlerGuardat the controller level. - Password policy. Validate the input with
validatorbefore callinghash_password. - Account-lookup queries. The service decides what to load, the helpers only hash.
- Refresh tokens, session rotation. Live in your token-issuer’s domain — the auth crate stays storage-agnostic.
Going further
Section titled “Going further”- JWT — the access token a successful login issues.
- Authentication —
Strategy,AuthnGuard<S>, the guard that runs them. - Throttler — slowing brute-force attempts at the controller edge.