Security
Authentication
The user model implements smeltery::auth::Authenticatable, and bootstrap/app.rs registers it with
.auth::<User>():
impl smeltery::auth::Authenticatable for Model {
fn auth_id(&self) -> i64 { self.id }
fn password_hash(&self) -> &str { &self.password }
fn remember_token(&self) -> Option<&str> { self.remember_token.as_deref() }
// Optional: a nullable `credentials_epoch` column lets `auth::end_credentials` end open sessions.
fn credentials_epoch(&self) -> Option<i64> { self.credentials_epoch }
}
Users are found by id and by their email column; remember-me tokens are stored in remember_token. An address is
compared trimmed and with its ASCII letters in lowercase (smeltery::auth::normalize_email), and a row counts only
when its stored address equals the typed one apart from ASCII letter case, so a database collation that also folds
accents (MySQL's and MariaDB's defaults) never matches a look-alike address. Handlers on web routes take Auth:
| Call | Does |
|---|---|
auth.check(), auth.id() |
whether someone is signed in, and who |
auth.user::<User>().await? |
the signed-in user (loaded once per request) |
auth.attempt(email, password, remember).await? |
true and signed in when the password matches and the login policies allow it (validate + app.check_login + login); it never asks a second factor, so with a login completion registered (below) it refuses with an error, like login |
auth.validate(email, password).await? |
the user (AuthUser) when the password matches, without signing in; the same budgets as attempt |
auth.login(&user, remember).await? |
sign in a user (a new session id and CSRF token); an error while a login completion is registered (sign in through app.login_completion(), whose code uses auth.login_user(&user, remember); AuthUser::of(&user) wraps a model) |
auth.logout().await? |
sign out this session: it is invalidated (the database and file drivers delete it), the remember-me cookie removed and the user's remember token replaced with a new random one, so no remember-me cookie of the user signs in any more; other devices stay signed in |
auth::cycle_remember_token(&app, user_id).await? |
replace the user's remember token with a random one (only its SHA-256 stored): no remember-me cookie of the user signs in any more; sessions stay |
auth.logout_other_devices(password).await? |
sign out every other session of the user: password (the current one) is hashed again with a fresh salt, and the remember token is replaced, so no remember-me cookie signs a device in again; false and nothing changes when it is wrong. It counts against confirm_password's five tries a minute |
auth.set_password(new).await? |
store a new password for the signed-in user and keep this session signed in: every other session ends, the remember token is replaced; false for a guest. Check the current password first |
auth.confirm_password(password).await? |
true when the signed-in user's password matches, and the session remembers the time; five tries a minute per user, then 429 / a redirect back with the message on password |
auth.password_confirmed_within(duration) |
whether this session confirmed the password within duration |
auth.intended(default) |
a 303 to the page the auth middleware turned the visitor away from, else to default; the remembered page is forgotten |
auth.set_intended(path) |
remember a page for intended: false (nothing remembered) unless path is a path on this site of at most 2048 bytes |
With remember, a remember-me cookie (remember_<session cookie>, encrypted, five years) holds the user id and a
random 60-character token whose SHA-256 is stored in users.remember_token; a request without a signed-in session
but with a valid cookie is signed in from it.
A signed-in session is bound to the user's password hash. When it changes (a
password change or reset, logout_other_devices), every session made before is signed out on its next request, a
copied session cookie included. The check reads the user's row on each request of a signed-in user. With
SESSION_DRIVER=cookie nothing is stored on the server, so a copy of a session cookie made before logout stays
valid until the session expires (SESSION_LIFETIME idle, SESSION_ABSOLUTE_LIFETIME at most); with database or
file the logout deletes the session, which is why new apps use the database driver.
Every attempt counts before the account is looked up and the password checked, so parallel requests get no extra
tries: thirty a minute from one client whatever the address (auth.ip(), the client address after
TRUSTED_PROXIES; an IPv6 client by its /64), five a minute for one address from one client, and twenty per five
minutes for one address from one network (an IPv4 /24, an IPv6 /48). Addresses with and without an account count
alike, so the limit tells nothing about which addresses are registered, and guesses from other networks never lock
the account's owner out. A successful sign-in resets the address's counts and gives its attempt back to the client's.
Past a limit attempt returns an error that JSON clients get as 429 and web forms as a redirect back with "Too many
login attempts. Please try again in N seconds." on email. The counts live in the process's memory, in fixed
windows that start with the first attempt.
The auth middleware sends guests to the route named login (or /login) with a 303, and answers 401 to JSON
clients. The guest middleware sends signed-in users to AUTH_HOME.
Before that redirect, the auth middleware remembers the page in the session when the request is a GET page visit:
not from a JSON client, not a background fetch / XHR, not a subresource (an image, script, stylesheet or frame,
told apart by the browser's Sec-Fetch-Mode and Sec-Fetch-Dest headers), not a prefetch and not an event stream;
Inertia visits count. It stores the path and query, never the host, at most 2048 bytes. Signing in keeps it,
signing out drops it. A login handler answers with auth.intended(…) after a successful attempt, so the user
lands on the page they asked for:
use serde::Deserialize;
use smeltery::prelude::*;
#[derive(Deserialize)]
struct LoginForm {
email: String,
password: String,
}
async fn login(app: App, auth: Auth, Form(form): Form<LoginForm>) -> Result<Redirect> {
if auth.attempt(&form.email, &form.password, false).await? {
return Ok(auth.intended(&app.settings().auth_home));
}
Ok(Redirect::to("/login"))
}
intended only redirects to a path on this site: one that starts with a single / and holds only visible ASCII
characters other than \ (browsers read //host, /\host and /<tab>/host as another host). Anything else in the
session gives default.
smeltery::auth::hash_password(password) hashes with argon2id (default parameters) and verify_password(password,
hash) checks one, both on a blocking thread. At most HASH_CONCURRENCY (default: the number of CPUs) hashes and
checks run at once in the process and up to HASH_QUEUE (64) more wait; further ones fail at once with 503, so a
flood of sign-ins, registrations or resets cannot exhaust the memory.
auth::verify_credentials(&app, client_ip, email, password).await? is the check behind validate and attempt for
code without a session (issuing an API token): the same three budgets (shared with attempt), the same dummy-hash
timing for unknown addresses, Some(AuthUser) on a match. auth::find_by_email::<User>(&app, email).await? finds a
user the way they do. #[serde(deserialize_with = "smeltery::auth::deserialize_email")] on a form's email field
reads it trimmed and in lower case. auth::model_column::<User>("email") is a column of the model by name, and
app.auth_model() the TypeId of the model registered with .auth::<User>().
Password changes: sessions, remember-me cookies and other credentials bound to the password hash end when it
changes. auth.set_password(new) keeps the current session; app code that writes password itself calls
auth::password_changed(&app, user_id, except).await? afterwards (except: the principal of the request, whose
credential stays), which replaces the remember token. A password reset, logout_other_devices, set_password and
password_changed then run the app's credential listeners (AppBuilder::credential_listener, a
smeltery::auth::CredentialListener told the user id, why (CredentialChange::{Reset, Changed,
OtherDevicesLoggedOut, Ended}), the credential that stays, and for a reset whether it verified a previously unverified
address (was_unverified)), before the request answers. Every listener runs and the event below is published even
when one fails; then the first error fails the request, the password stays changed. password_changed refuses an
except principal of another user. Keep a credential only after checking the current password. Each also
publishes one smeltery::auth::AuthEvent on the
PubSub topic auth (auth::EVENTS_TOPIC): RevokedAll { user_id, kind,
except } (as JSON {"type":"revoked_all",…}), and a logout publishes Revoked { user_id, key } for the session
it ended (key as principal.key() names it). auth::publish_event(&app, &event) publishes one. Delivery is at
most once, as every PubSub message.
Password confirmation: the password.confirm middleware (registered by .auth::<User>(), put it after auth)
lets a session through that confirmed its password with auth.confirm_password(password) within
AUTH_PASSWORD_TIMEOUT seconds (default 10800). Otherwise JSON clients and API routes get 423 {"message": "Password
confirmation required."}, and a page visit is remembered (as auth does) and sent to the route named
password.confirm (or /user/confirm-password) with a 303. Every sign-in and sign-out removes the confirmation
with the other session keys a sign-in owns (names starting with _auth. or _temper.).
Second factor: AppBuilder::second_factor(f) registers a smeltery::auth::SecondFactor (required(app, user),
verify(app, user, code)); app.second_factor() returns it. verify answers a SecondFactorVerdict: Valid,
Invalid, or TooManyAttempts { retry_after } when the account's code budget is spent (the code is then not
checked). verdict.into_result("code", message)? turns it into the endpoint's answer: Ok(()), 422 with message
on code, or 429 with Retry-After and "Too many attempts. Please try again in N seconds." on code.
Login policy: AppBuilder::login_policy(p) adds a smeltery::auth::LoginPolicy, a rule without a session that
every new sign-in meets: check(app, user) answers LoginDecision::Allow or LoginDecision::refuse(status,
message) (a suspended account, an IP rule). app.check_login(&user).await? asks every policy in the order they
were added (none: allowed); the first refusal is an error with the policy's status and its message on email (JSON
clients get the status, browsers are sent back with the message). auth.attempt, Temper's login, its two-factor
challenge and registration, and Hallmark's token endpoint ask it after the password and before the second factor.
A remember-me cookie meets it too: a refused restore stays a guest, the cookie is removed and the user's remember
token replaced. Policies gate new sign-ins, token issuance and remember-me restores only: refusing a user does not
end an open session, issued API tokens or open sockets; auth::end_credentials (below) ends them.
Ending a user's credentials: auth::end_credentials(&app, user_id).await? signs a user out everywhere without
a password change (a suspension, together with a login policy that refuses them): it adds one to the user's
credentials_epoch, so every open web session of the user is signed out on its next request; it replaces the
remember token, runs the credential listeners with CredentialChange::Ended (Hallmark deletes every token of the
user) and publishes RevokedAll { kind: Every, except: None } (Anvil closes the user's sockets). The epoch is a
nullable integer column credentials_epoch on the users table (t.big_integer("credentials_epoch").nullable())
that the model returns from Authenticatable::credentials_epoch (Option<i64>; default None). Sessions are bound
to the password hash and the epoch; sign-ins and sign-outs never change the epoch, so they never end other
sessions. A model without the column keeps working (None binds sessions as before); end_credentials then still
ends the remember token, tokens and sockets, and returns an error because open sessions stay signed in. A step
that fails never skips the others: the listeners run and the event goes out, then the first error is returned. It
does not change the password: whoever holds it (or a pending two-factor login) can sign in again unless a login
policy refuses the user.
Login completion: AppBuilder::login_completion(c) registers a smeltery::auth::LoginCompletion:
complete(app, auth, session, headers, user, remember) finishes signing in a known user (an AuthUser) and returns
the response; app.login_completion() returns it, so code that proves a user another way calls it instead of
auth.login_user(&user, remember) (Auth::login without the model type).
Password resets: auth::passwords::send_reset_link(&app, email) finds the account as attempt does, stores a
token for that account in password_reset_tokens (user_id, the token's SHA-256, created_at; one row per
account, replaced by each new link) and sends the link APP_URL + the route named password.reset (its {token}
filled in, else /reset-password/{token}) + ?email=… to the address stored on the account, never to the typed
one. It returns Some(user id) when a link was issued and None otherwise, for the caller's records (the answer
to the visitor stays the same either way). At most
one link a minute goes to one address (further requests in that minute do nothing), an address without an account
does nothing, and the mail leaves in the background (under APP_ENV=testing before the call returns), so neither the
answer nor its timing tells whether an account exists; a failed delivery is logged, not returned. The link goes out
with mail installed (.mail()) as the ResetPassword mail
(smeltery::mail::ResetPassword, its template part of the framework). Without mail, the link goes to the log at
info level in local development (APP_ENV local or testing and an APP_URL on this machine: localhost,
*.localhost or a loopback address); anywhere else only a warning that no mail is set up is logged, never the link.
auth::passwords::reset(&app, email, token,
new_password) finds the account the same way, through the user model, and, when the token matches and is less than
60 minutes old, uses the token up (one conditional delete: of two requests with one token one wins), sets the new
password on that row by its id and clears its remember token; the new password hash signs out every session of the
user. With .verify_email::<User>() the address is marked verified when the link was mailed to the address the
account has now (a link proves control of the address it reached; the last 16 characters of a mailed token name
that address). A token from passwords::create_token verifies nothing. It returns the user's id
(Ok(Some(id))), Ok(None) for an unknown address or a wrong, used or expired token, then runs the credential
listeners and publishes RevokedAll (above). On MySQL and MariaDB a users.email column with a binary collation
(utf8mb4_bin) also makes the database itself compare addresses byte for byte.
Email verification: a user model whose email must be verified implements smeltery::auth::MustVerifyEmail
and has a nullable email_verified_at column; bootstrap/app.rs adds .verify_email::<User>() after
.auth::<User>():
impl smeltery::auth::MustVerifyEmail for User {
fn email(&self) -> &str { &self.email }
fn email_verified_at(&self) -> Option<DateTimeUtc> { self.email_verified_at }
}
fn build(app: smeltery::AppBuilder) -> smeltery::AppBuilder {
app.auth::<User>().verify_email::<User>()
}
An existing users table gets the column with smeltery make:migration add_email_verified_at_to_users_table, its
column line changed to t.datetime("email_verified_at").nullable();.
The verified middleware (put it after auth) sends guests, and users whose email_verified_at is empty, to the
route named verification.notice (or /email/verify) with a 303 and answers 403 {"error": "Your email address is
not verified."} to JSON clients. Without .verify_email::<User>() it lets every signed-in user through; guests
never pass.
| Call | Does |
|---|---|
auth.send_verification_email().await? |
reads the signed-in user's row again and issues their link to the mailer: true when a link was issued; false (nothing issued) for a guest, a verified user, or without .verify_email |
auth.resend_verification_email().await? |
the same, six calls a minute per user (counted atomically); then 429 for JSON clients, a redirect back with "Too many verification emails. Please try again in N seconds." on email for forms |
auth.has_verified_email().await? |
for a signed-in user: true when their email is verified, or without .verify_email; false for a guest |
EmailVerificationRequest (handler argument) |
the checked link; request.fulfill().await? sets email_verified_at (and updated_at when the model has it) to now: true the first time, false when it was set already |
auth::verification::verification_url(&app, &user), send_verification_link(&app, &user).await? |
the link of any user, and sending it |
app.verifies_email() |
whether the app requires verified addresses (.verify_email::<User>()) |
auth::mark_verified(&app, user_id).await?, auth::mark_unverified(&app, user_id).await? |
set email_verified_at to now (unless set) or empty it (after the address changed), through the user model: true when it changed; an error without .verify_email |
A link is APP_URL followed by the route named verification.verify (/email/verify/{id}/{hash}) and
?expires=…&signature=…. hash is the SHA-256 of the user's email and signature an HMAC-SHA256 of the id, the
hash and the expiry time under a key derived from APP_KEY; the expiry time is fixed in the link when it is made,
AUTH_VERIFICATION_EXPIRE minutes later (default 60, at least 1). EmailVerificationRequest needs a signed-in user
(put the route behind auth: a link opened while signed out leads to the login, and a login handler that answers
with auth.intended(…) brings the user back to the link) and answers 403 "This verification link is invalid or
has expired." unless the signature is valid, the expiry time has not passed, the id is the signed-in user's and the
hash matches their current email: a link stops working when the email changes. With .verify_email, a route named verification.verify
without both {id} and {hash} stops the build with an error. A handler that changes a user's email sets
email_verified_at to None in the same update and then calls auth.send_verification_email(), which sends the
link to the new address. The link is sent like a reset link: with mail installed as the VerifyEmail mail
(smeltery::mail::VerifyEmail, its template part of the framework); without mail it goes to the log in local
development only (as above).
A web app declares the three routes:
use smeltery::auth::EmailVerificationRequest;
use smeltery::prelude::*;
async fn notice(app: App, auth: Auth) -> Result<Response> {
if auth.has_verified_email().await? {
return Ok(Redirect::to(&app.settings().auth_home).into_response());
}
Ok("Check your inbox for the verification link.".into_response())
}
async fn verify(app: App, session: Session, request: EmailVerificationRequest) -> Result<Redirect> {
request.fulfill().await?;
session.flash("status", "Your email address is verified.");
Ok(Redirect::to(&app.settings().auth_home))
}
async fn send(auth: Auth, session: Session, back: Back) -> Result<Redirect> {
auth.resend_verification_email().await?;
session.flash("status", "verification-link-sent");
Ok(back.redirect())
}
fn routes(r: &mut Router) {
r.get("/email/verify", notice).name("verification.notice").middleware("auth");
r.get("/email/verify/{id}/{hash}", verify)
.name("verification.verify")
.middleware("auth");
r.post("/email/verification-notification", send)
.name("verification.send")
.middleware("auth");
}
The register handler calls auth.send_verification_email().await? after auth.login(&user, false).await?.