suprnova::auth_flows is the lifecycle layer on top of session
authentication. Where auth::* answers "who is this
request", auth_flows::* answers everything around that question - proving
the email address is real, recovering it when the password is lost,
defending it against credential stuffing, and protecting it with a second
factor. Five flows ship under one namespace:
EmailVerification- mint, check, and consume single-use verification tokens;send_link/resenddispatch the verification mail through theMailfacade, andverifymarks the user verified through the configured user provider.PasswordReset- anti-enumerationsend_link, non-consumingcheck, andcomplete.completerotates the password through the configured user provider, revokes every session and remember-me row for the user, and sends aPasswordChangedMailsecurity notification.BruteForce+LoginThrottleMiddleware- torii-backed lockout state plus an HTTP middleware that short-circuits with429 Too Many Requestsbefore the login handler is invoked.TwoFactor- TOTP enrollment, confirmation, verification, recovery codes, secret rotation, the full challenge flow that gates a password login on the second factor, and replay protection at the 30-second timestep granularity.remember_me- re-export ofcrate::auth::remember(DB-row + bcrypt + single-use rotation persistent cookies) for namespace cohesion.
Two route-gate middleware ship in the same namespace:
EnsureEmailVerifiedMiddleware- composes afterAuthMiddlewareto gate routes onemail_verified_at.TwoFactorChallengeMiddleware- composes in front ofAuthMiddlewareto bounce a session with a pending 2FA challenge to the challenge form rather than the login page.
Every transactional message is delivered through the Mail
facade. Torii's optional mailer feature is intentionally disabled in
framework/Cargo.toml: running a second mail stack inside torii would
split telemetry, double the transport configuration surface, and force
apps to wire two "from" addresses.
Where the state lives
Email verification and password reset are provider-agnostic.
Verification and reset tokens live in the framework's own
auth_flow_tokens table (single-use, SHA-256-hashed), and the user
lookup + mutation go through whichever
UserProvider the app registered - the same
provider Auth::user resolves against. There is no global auth instance
to initialise for these two flows: a freshly-scaffolded app already has
EloquentUserProvider<User> bound, and that's all EmailVerification
and PasswordReset need.
Torii still owns the security state for the flows that genuinely depend
on it - the per-account brute-force lockout counter, OAuth / passkey /
WebAuthn ceremonies, and the session pool. Suprnova owns the
cross-cutting concerns across every flow - outbound mail, event
dispatch, the 2FA TOTP table, remember-me cookies, and the HTTP
middleware. Application code only ever touches
suprnova::auth_flows::*. Laravel folds the equivalent surface into
Fortify; Suprnova keeps the model traits (MustVerifyEmail /
CanResetPassword) and the token store in the framework so the flows
work against any user backend.
Failure semantics across flows
Every facade follows one ordering rule: the durable state change commits first, then notification side effects fire. A listener panic, a transient mail-transport failure, or a dispatcher error after the mutation cannot roll the mutation back.
EmailVerification::verifyconsumes the token and marks the user verified through the provider before firingEmailVerified.PasswordReset::completeconsumes the token and rotates the password through the provider first, then revokes every session and remember-me row for the user (logged on failure, not surfaced), then dispatchesPasswordChangedMailfire-and-forget, then firesPasswordResetCompleted.BruteForce::unlock_accountcommits the unlock before firingAccountUnlocked.TwoFactor::confirmstampsconfirmed_atbefore firingTwoFactorEnrolled;TwoFactor::disabledeletes the row before firingTwoFactorDisabled;TwoFactor::complete_challengepromotes pending → authed before dispatching the standardauth::Login+auth::Authenticatedpair followed byTwoFactorChallenged.
A listener that needs durability should buffer its work (queue a job from the listener body); the facade itself never retries.
Bootstrapping
Email verification and password reset are provider-backed and need no torii. Brute-force protection and 2FA still need torii. Wire what the flows you use require - they're independent.
Email verification + password reset
Three things, all of which a scaffolded app already has:
-
A user provider that implements the auth-flow surface. Register
EloquentUserProvider<User>(the same providerAuth::userresolves against) as thedyn UserProviderbinding inbootstrap.rs::register(). Both facades resolve the active provider internally; no instance is passed at the call site.use ; use UserProvider; use crateUser; bind!; -
The two model traits on your
User.EloquentUserProvider<User>only implements the auth-flow methods (retrieve_by_email/mark_email_verified/set_password/is_email_verified) whenUserimplements bothMustVerifyEmailandCanResetPassword- Suprnova's analogues of Laravel'sMustVerifyEmail/CanResetPasswordcontracts:use ; use ;is_email_verified()has a default that tracks the timestamp (email_verified_at().is_some()), andname()defaults toNone- override it to greet users by name in the mail. -
Two columns / tables in your migrator. The
userstable needs a nullableemail_verified_attimestamp (the provider reads it inis_email_verifiedand stamps it inmark_email_verified), and the framework's single-useauth_flow_tokenstable holds the verification / reset tokens. The framework ships the token table'sCREATE; list it in your migrator:use *;Add
email_verified_attousersin your own column migration (a nullabletimestamp_with_time_zone);NULLmeans unverified, so existing rows backfill correctly.
Tokens are single-use and SHA-256-hashed at rest - a database dump never yields a usable plaintext token. The default TTLs are 24 hours for email verification and 15 minutes for password reset.
Brute-force + 2FA: wiring torii
BruteForce / LoginThrottleMiddleware and TwoFactor are torii-backed -
they need the global torii instance initialised in
bootstrap.rs::register(), after DB::init. (OAuth, passkeys, and
WebAuthn ceremonies go through the same instance - see
Authentication.)
use ;
use DB;
pub async
init_torii is idempotent. The OnceLock guard means the second call
is a no-op, so test harnesses that re-enter register() per fixture
do not double-migrate. For tests, swap in
ToriiConfig::sqlite_in_memory() - it spins up a shared-cache
in-memory database that survives across runtimes:
let config = sqlite_in_memory
.await?
.apply_migrations;
init_torii.await?;
Registering the 2FA migrations
The framework ships the schema; your app opts in by listing both migrations in its own migrator:
use *;
;
Both are idempotent against an already-applied database (the v1 uses
CREATE TABLE IF NOT EXISTS; the v2 is a column add). Re-running
suprnova migrate against a production database that already has the
schema is a no-op.
Environment
The transactional mailables read two environment variables at send time:
| Var | Default | Used for |
|---|---|---|
APP_NAME |
"Suprnova" |
Subject branding and the otpauth:// issuer label that authenticator apps display. |
MAIL_FROM |
none - errors when unset | Envelope From on every outgoing message. Set to a verified sender domain. |
MAIL_FROM deliberately has no default. Defaulting to a placeholder
like noreply@example.com would silently break DMARC / SPF in
production and ship from a domain the operator doesn't control, so the
facade fails closed instead. EmailVerification::send_link and
PasswordReset::send_link surface the error as Err;
PasswordReset::complete logs via tracing::warn! and continues
(the password change has already committed, so the notification path
cannot roll it back).
Apps additionally set APP_URL so controllers can derive the base URL
used in send_link calls; the framework facade itself takes the base
URL as a parameter.
The mail driver is configured separately via MAIL_DRIVER - see the
Mail docs.
Email Verification
EmailVerification mints, checks, and consumes verification tokens
against the auth_flow_tokens table and marks the user verified through
the configured provider. Four operations cover the lifecycle:
| Method | Signature | Notes |
|---|---|---|
send_link |
send_link<U: MustVerifyEmail>(user: &U, base_url: &str) -> Result<()> |
Mint + mail, given a user already in hand. |
resend |
resend(email: &str, base_url: &str) -> Result<()> |
Anti-enumeration: looks the user up by email; an unknown address is a silent Ok(()). |
check |
check(token: &str) -> Result<bool> |
Non-consuming - safe to call on a landing page. |
verify |
verify(token: &str) -> Result<String> |
Single-use: consumes the token, marks the user verified, returns the user id. |
use EmailVerification;
// After a fresh signup, with the freshly-created user in hand:
send_link.await?;
// Optional landing-page check - non-consuming, so a page refresh
// does not burn the token.
let valid: bool = check.await?;
// The click-through handler consumes the token and stamps the user,
// returning the verified user's id.
let user_id: String = verify.await?;
verify fires EmailVerified on success - listeners are the right
place to unlock additional functionality (welcome email, default
follows, "complete your profile" CTA) without coupling them to the
verification handler. The event carries the provider's user id.
The resend endpoint (anti-enumeration)
resend takes only the email - the facade looks the user up through the
active provider and, when an account is on file, mints a token and sends
the mail; an unknown email is a silent no-op that still returns
Ok(()). The handler never branches on existence itself, so a probing
caller cannot distinguish "sent" from "no such account":
use HashMap;
use EmailVerification;
use ;
pub async
async
send_link and resend both build the URL as
{base_url}?token={plaintext_token}. A trailing slash on base_url is
trimmed before the query string is appended, so
https://app.example.com/verify/ and https://app.example.com/verify
both produce a clean URL.
The click-through handler pulls the token from the query string and
calls verify:
async
The handler does not need to look up the user - verify consumes the
token, marks the user verified through the provider, returns the user
id, and fires EmailVerified. Single-use: a second verify on the same
token returns an error.
Verified-only routes: EnsureEmailVerifiedMiddleware
EnsureEmailVerifiedMiddleware gates routes on the authenticated
user's email_verified_at. Compose it after AuthMiddleware and the
chain blocks any request whose user has not yet completed the verify
step.
The choice between 403 JSON and 302 HTML redirect is made at
route-registration time via the constructor - there is no
request-content sniffing, matching the pattern set by
AuthMiddleware::new / AuthMiddleware::redirect_to:
use ;
// API surface - 403 with a JSON body.
group!
.middleware
.middleware
.routes;
// Web surface - 302 (or 409 + X-Inertia-Location for Inertia visits).
group!
.middleware
.middleware
.routes;
If no user is authenticated, the middleware falls into the same response
branch as "authed but not verified" - matching Laravel's
! $request->user() || ! hasVerifiedEmail() shape. Compose
AuthMiddleware first when you want a separate 401 for unauthed
requests.
For in-handler branching (e.g. conditionally rendering a "please verify" CTA without redirecting), load the typed user through the session guard and read the trait method:
use ;
use crateUser;
if let Some = .await?
Password Reset
PasswordReset has three operations:
| Method | Signature | Notes |
|---|---|---|
send_link |
send_link(email: &str, base_url: &str) -> Result<()> |
Anti-enumeration: looks the user up by email; an unknown address is a silent Ok(()). |
check |
check(token: &str) -> Result<bool> |
Non-consuming - confirm the token before rendering the new-password form. |
complete |
complete(token: &str, new_password: &str) -> Result<String> |
Single-use: consumes the token, rotates the password, revokes sessions + remember-me, sends the change notification, returns the user id. |
use PasswordReset;
// From the "forgot password" form. Always Ok(()) - the facade looks
// the user up and only sends when an account is on file.
send_link.await?;
// Optional landing-page check before rendering the new-password form.
let valid: bool = check.await?;
// The click-through handler, after the user submits a new password:
// consume the token + rotate the password, returning the user id.
let user_id: String = complete.await?;
complete hashes new_password before handing it to the provider -
pass the plaintext, not a pre-hashed value. An empty / whitespace
password is rejected up front with a 400.
Anti-enumeration
send_link is structured so the response shape never leaks whether an
email address has an account:
- It always returns
Ok(()). When the email is absent no token is minted, no mail is dispatched, and noPasswordResetLinkSentevent fires - but the absence is not surfaced through the return type either, so a caller (and a network observer) cannot distinguish "no such account" from "link sent." - The dogfood controller pairs
send_linkwith a fixed 200 response body, so a probing caller cannot distinguish through status code, response body, or response timing.
complete side effects
complete runs four steps in order:
- Consume the token (single-use) and rotate the password hash through the configured provider (the only step that can fail the call).
- Revoke every session row for the user via
crate::session::destroy_all_for_user(best-effort: failurestracing::warn!). - Revoke every remember-me row via
crate::auth::remember::revoke_all_for_user(best-effort). - Dispatch
PasswordChangedMailfire-and-forget, then firePasswordResetCompleted.
A stolen session and a captured remember-me cookie must not outlive the credential they depended on. The revocations happen on every successful reset, not just on user-initiated ones, so a security-team forced reset also kicks out an active attacker.
Brute-Force Protection
The brute-force layer has two parts: the BruteForce facade that
records and queries lockout state, and the LoginThrottleMiddleware
that short-circuits at the HTTP layer before the handler is invoked.
The BruteForce facade
Call record_failed_attempt from the failed-auth branch of your login
handler, and reset_attempts from the success branch:
use BruteForce;
// In the failed-auth path:
let status = record_failed_attempt.await?;
if status.is_locked
// In the success path:
reset_attempts.await?;
record_failed_attempt returns the updated LockoutStatus
(is_locked, failed_attempts, and locked_until when locked). Pass
the optional ip for audit logs; pass None if your transport doesn't
surface a client IP cleanly.
Two additional operations:
// Read-only - safe on emails with no history.
let status = get_lockout_status.await?;
let locked: bool = is_locked.await?;
// Admin / forced unlock. Fires `AccountUnlocked` only on a real state
// transition (no-op unlock on an already-unlocked account does not fire).
let was_locked: bool = unlock_account.await?;
unlock_account returns true when the account had been locked at the
time of the call, false otherwise. The AccountUnlocked event fires
only on true - a false return is the no-op it is, not an audit
event.
LoginThrottleMiddleware
The middleware reads the lockout state for whichever email a request is
targeting and short-circuits with 429 Too Many Requests when the
account is locked. The login handler is never invoked, so a locked
account does not even get to attempt a credentials check:
use LoginThrottleMiddleware;
use Router;
// The email extractor is a sync closure over `&Request`. Reading
// JSON/form body is async and consumes `Request`, so the closure
// cannot read the body - pull from a header, query string, or
// route param instead.
let throttle = new;
let router = new
.post
.middleware;
Practical extraction surfaces:
- A header (
X-Login-Email), set by a preceding pre-processor - the pattern used in the dogfood app. - A query string parameter (
?email=…). - A route parameter (
/login/{email}).
Returning None from the extractor is the explicit "I have nothing to
check" signal - the middleware passes the request through unchanged.
This makes the middleware safe to install on routes that occasionally
see anonymous traffic (e.g. the same POST /login endpoint that also
handles a no-email "request password reset" sub-action).
On lock the middleware returns:
- Status
429 Too Many Requests. Retry-Afterheader - seconds, computed from the lockout'slocked_untilviaLockoutStatus::retry_after_seconds. Falls back to900(15 minutes - torii's default lockout period) if the timestamp is somehow absent.- Body:
"Account locked due to too many failed login attempts. Try again later."
Fail-open on backend errors
If get_lockout_status returns an Err (transient database hiccup),
the middleware passes the request through. The downstream login
handler will then make the call itself and can decide whether to fail
closed or open. The middleware errs on the side of availability:
taking down the login endpoint whenever the auth database has a blip
is worse than letting the handler make the call directly.
Layering with RateLimitMiddleware
LoginThrottleMiddleware is per-account - it gates a single email
when the threshold is crossed. For per-IP quotas, layer it with
RateLimitMiddleware. The two compose naturally:
let router = new
.post
.middleware
.middleware;
Together they cover the realistic shapes of credential stuffing: distributed (one email × many IPs) is the rate limit's job; focused (many attempts × one email) is the throttle middleware's job.
Configuration
Torii's BruteForceProtectionConfig defaults to 5 failed attempts
before lockout and a 15-minute lockout period. These are what
init_torii wires up today; configuring per-app values requires
reaching into torii's own configuration surface and is not exposed
through Suprnova's ToriiConfig builder. The defaults are deliberately
conservative - pick "five mistypes locks me out for 15 minutes" before
deciding to relax them.
Two-Factor (TOTP)
TwoFactor covers TOTP-based 2FA - the kind that pairs with any
standards-compliant authenticator app (Google Authenticator, 1Password,
Bitwarden, Authy). The flow is enrollment → confirmation → ongoing
verification, plus single-use recovery codes for when the user loses
their device, plus the challenge flow that stitches everything into the
login lifecycle.
The TwoFactorUser trait
The framework cannot reach into your application's user storage, so callers implement a small trait to bridge from their user model to the 2FA facade:
use TwoFactorUser;
user_id is the opaque storage key - typically
torii::UserId.as_str(), but any stable per-user identifier works.
The 2FA table indexes on it; there is no FK to your user table.
email is folded into the otpauth:// URL's account_name segment so
the authenticator app renders the row with a human-readable label
(e.g. "MyCorp (alice@example.com)").
A common pattern is a small newtype that wraps your user model:
use TwoFactorUser;
use User as ToriiUser;
Storage
2FA state lives in the framework-owned two_factor_credentials table.
Secrets and recovery codes are encrypted at rest with
crate::crypto::Crypt::encrypt_string, which requires a process-global
EncryptionKey. Apps opt into the schema by listing both migrations
in their Migrator::migrations() - see Bootstrapping.
Enroll, confirm, verify
use ;
// 1. Enrollment: generate a fresh secret + 10 recovery codes, persist
// them encrypted, return everything needed to render the QR code.
let response: EnrollmentResponse = enroll.await?;
// response.otpauth_url - `otpauth://totp/...` deep link
// response.qr_code_svg - <svg> wrapping a base64 PNG, embed inline
// response.recovery_codes - Vec<String>, 10 plaintext codes - show ONCE
// 2. Confirm: the user opens the authenticator app and types in the
// 6-digit code. `confirm` validates it and stamps `confirmed_at`.
confirm.await?;
// fires `TwoFactorEnrolled`
// 3. On subsequent logins, gate the session on `verify`:
let ok: bool = verify.await?;
if !ok
enroll returns plaintext recovery codes exactly once. There is
no API to retrieve them later - the encrypted column is one-way from
this point on. Show them on the enrollment success page, encourage the
user to save them, and don't store the plaintext anywhere else.
enroll refuses to overwrite a confirmed enrollment - it returns a
409 to push the caller toward re_enroll, which requires proof of
possession. Re-enrolling on an unconfirmed (pending) row is allowed:
the prior enrollment never became authoritative.
Replay protection
verify writes the current TOTP timestep to last_used_timestep on
success. Subsequent verifies where current_timestep <= last_used_timestep are rejected even when the code itself is
structurally valid, defeating a stolen-code replay inside the 30-second
window.
The timestep claim is atomic. The stamp lands via a conditional
UPDATE … WHERE last_used_timestep IS NULL OR last_used_timestep < :current, and the verify only succeeds when the statement affects
exactly one row. Two concurrent verifies in the same timestep cannot
both win: the first flips the column, the second's predicate no
longer matches, and the second is treated as a replay. A plain
read-modify-write would be a TOCTOU race - both verifies read the
pre-stamp row, both validate the same code, both stamp, both succeed.
Concurrent racers are also counted as failed attempts so the
brute-force counter records them.
Recovery codes
let consumed: bool = consume_recovery_code.await?;
Single-use: a matching code is removed from the row before the call
returns, so a second attempt against the same code returns false.
Codes are 12 decimal digits in NNNNNN-NNNNNN shape (~40 bits of
entropy each, matching Laravel Fortify's format).
consume_recovery_code only accepts codes when 2FA is fully confirmed -
it short-circuits to Ok(false) while confirmed_at is NULL.
Without this gate, an attacker who triggered enrollment on a victim
account (or any flow that creates the row without confirming) could
authenticate using only a fresh recovery code, bypassing TOTP entirely.
The contract is symmetric with verify's "confirmed enrollment only"
guard.
Rotating recovery codes and secrets
When a user exhausts their recovery codes, or wants to rotate them after a suspected compromise:
let fresh: = regenerate_recovery_codes.await?;
proof must validate as either a current TOTP code or an unused
recovery code. Without the proof check, a session-hijacked attacker
could silently blow away the legitimate user's recovery codes
(denial-of-service against account recovery). The fresh codes replace
the persisted set; the existing secret and confirmed_at are
preserved, so the user's authenticator app keeps working without
re-pairing. Errors:
400- no confirmed enrollment exists; callenroll/confirmfirst.401-proofvalidates as neither a TOTP code nor an unused recovery code.429- the account is locked by brute-force throttling.
To rotate the secret (re-pair to a new device) without disabling 2FA first:
let response = re_enroll.await?;
Same proof model as regenerate_recovery_codes. The row is rewritten
with a fresh secret + 10 fresh recovery codes; confirmed_at resets to
NULL so the user must confirm with a code from the new authenticator
before 2FA is active again.
Disable
disable.await?;
// fires `TwoFactorDisabled` only if a row was removed
Idempotent: a disable on a user who never enrolled is not an error.
The TwoFactorDisabled event fires only on a real state transition,
so audit listeners see one entry per actual disable rather than one
per click on a no-op button.
Challenge flow (gating login on the second factor)
The enroll / confirm / verify primitives are the building blocks; the challenge flow stitches them into the login lifecycle so a user with 2FA enabled cannot reach protected pages on password alone.
The flow:
- Password login resolves a user.
- If
TwoFactor::is_enabled_by_id(&user_id)returnstrue, the login handler callsTwoFactor::start_challenge(user_id, remember)- that stashes the user-id as pending in the session, clears the fully-authenticated slot, revokes any remember-me cookie issued byAuth::attempt, and remembers whether the user opted into remember-me so the cookie can be re-issued after the challenge completes.Auth::id()returnsNonefrom this point until the challenge completes. - The handler redirects to a
/two-factor-challengeroute that shows the code form. - The challenge POST handler calls
TwoFactor::complete_challenge(code)- verifies the code (TOTP or an unused recovery code, matching Fortify's challenge controller), promotes pending → authed, rotates the session id (defeating session fixation) and the CSRF token, re-issues the remember-me cookie when the user opted in, and dispatches the standardauth::Login+auth::Authenticatedlifecycle events plus the 2FA-specificTwoFactorChallenged.
use TwoFactor;
use ;
pub async
pub async
complete_challenge rotates the session id and CSRF token as part of
the promotion to authed. That closes the classic session-fixation
attack where an attacker plants a known session id on a victim before
they log in - after the rotation, the planted id is dead and only the
freshly-generated id carries the authenticated state. The contract
matches Auth::login_id / Auth::login_using_id, so 2FA logins are
indistinguishable from no-2FA logins in terms of session state and
listener observability.
Gate every protected route group with TwoFactorChallengeMiddleware
before AuthMiddleware so a pending session is bounced to the
challenge page rather than the login page:
use ;
group!
.middleware
.middleware
.routes;
The challenge page itself (the GET that renders the form, the POST
that calls complete_challenge) must NOT install
TwoFactorChallengeMiddleware - it is the destination. The POST
handler typically also checks TwoFactor::pending_user_id().is_some()
up front so a stale link does not reach the verify logic with an
empty session.
TwoFactor::cancel_challenge() clears both pending slots without
authenticating anyone - wire it to a "back to login" link on the
challenge page.
Recovery code fallback. complete_challenge(code) tries the TOTP
path first and falls back to consuming a recovery code, so a user who
lost their authenticator can still get in. Each recovery code is
single-use.
Brute-force linkage. Failed challenge codes feed the per-account
brute-force counter through BruteForce::record_failed_attempt, the
same way bare TwoFactor::verify does. An attacker grinding the
challenge form will trip AccountLocked after the configured
threshold. A single bad submission counts as one failed attempt
even though complete_challenge tries both the TOTP and recovery-code
paths internally - the silent-validation cores skip the brute-force
counter so the outer layer records the canonical attempt exactly once.
Lockout gate. complete_challenge checks BruteForce::is_locked
up front and returns 429 Too Many Requests if the account is
already locked - even when the submitted code is correct. Without
this in-method gate an attacker who tripped the lockout could still
get in by submitting the right code on the next request: the
brute-force counter is keyed on the user's email but verify itself
doesn't consult it. The password path's LoginThrottleMiddleware
enforces the same constraint at the route layer; composing it in
front of the challenge POST route is fine - both gates are
idempotent.
Failure event. complete_challenge dispatches
TwoFactorChallengeFailed { user_id } on a bad code (or a locked
account), distinct from the password path's auth::Failed. Listeners
watching for "user tried 2FA and failed" subscribe to the new event;
listeners watching for "password didn't authenticate" stay on
auth::Failed. The two surfaces are kept separate so a 2FA mistype
does not look like a password failure to audit pipelines.
Why Suprnova diverges
The 2FA user_id is intentionally a String. If it were typed as
i64, Uuid, or torii::UserId, the 2FA table would be permanently
tied to whatever shape the framework picked first - apps that store
users with a different shape (UUIDs vs auto-increment integers, or
apps that do not use torii at all but want the 2FA module) would be
locked out. A stringy user_id lets each app pick whatever stable
per-user identifier it likes; the trade-off is one .to_string() at
the call site. Laravel's Fortify ties the equivalent column to
Eloquent's User::id - Suprnova decouples it so TwoFactor is a
reusable lifecycle primitive, not a User-shaped accessory.
Remember-me
suprnova::auth_flows::remember_me re-exports suprnova::auth::remember -
the persistent-cookie module that already shipped alongside session
auth. The re-export is purely organisational: everything auth-flow-shaped
lives under auth_flows::*, even when the implementation predates this
namespace.
The design that ships:
- DB-row + bcrypt hash - each issued token has a row in the
remember_tokenstable storing only the bcrypt hash, never the plaintext. A database dump cannot yield re-authenticating credentials. - Single-use rotation - a successful verification DELETEs the matched row and issues a fresh one. A captured cookie cannot be re-used; if attacker and victim race to use it, the loser sees the row gone and fails to authenticate.
- Revocation -
revoke_all_for_userwipes every row for a user in one DELETE.Auth::logoutchains this so a real logout actually clears persistent state, andPasswordReset::completedoes the same so a password reset invalidates every existing persistent cookie. - Pruning -
prune_expiredcleans up expired rows on a schedule.
In practice the framework's session middleware does the heavy lifting;
the typical app does not call the remember_me module directly. The
Authentication doc covers the user-facing surface -
the remember flag on Auth::login, the cookie name, and the
lifetime knobs.
Events
Nine events fire across the flows, one per security-state transition:
| Event | Fired by | Carries |
|---|---|---|
EmailVerified |
EmailVerification::verify on success |
user_id: String |
PasswordResetLinkSent |
PasswordReset::send_link on success - anti-enumeration silent for absent emails |
user_id: String, email: String |
PasswordResetCompleted |
PasswordReset::complete on success |
user_id: String |
AccountLocked |
BruteForce::record_failed_attempt on the unlocked → locked transition |
email: String, failed_attempts: u32 |
AccountUnlocked |
BruteForce::unlock_account when an actual unlock occurred |
email: String |
TwoFactorEnrolled |
TwoFactor::confirm on success |
user_id: String |
TwoFactorChallenged |
TwoFactor::complete_challenge promoted pending → authed |
user_id: String |
TwoFactorChallengeFailed |
TwoFactor::complete_challenge rejected a bad code or refused a locked account |
user_id: String |
TwoFactorDisabled |
TwoFactor::disable when a row was actually removed |
user_id: String |
Every event is Debug + Clone + 'static, carries no sensitive data
(no plaintext tokens, no IPs), and uses stringy identifiers so
listeners can serialize them across task boundaries without leaking
type information from the user-storage backend.
Listening
Subscribe via the standard event API - same surface as every other in-process event:
use Arc;
use async_trait;
use AccountLocked;
use ;
;
// In bootstrap.rs:
.await;
Listeners run on Tokio's runtime and are dispatched in registration order. See the Events chapter for the full surface.
Testing
Three fakes cover the auth-flows surface, and they compose.
Mail::fake()
Installs a process-local capture transport. Every send during the guard's lifetime lands in an in-memory buffer instead of going out:
use Mail;
async
MailFake exposes assert_sent, assert_not_sent,
assert_sent_count, plus the raw captured() and count()
accessors. When the guard drops, the previously-bound transport is
restored - tests that interleave fakes with explicit transport
binding do not leak state.
EventFacade::fake()
The same shape, but for events:
use EmailVerified;
use assert_dispatched;
use EventFacade;
async
The fake records dispatched events without invoking listeners, so a
listener that talks to an external service will not fire during the
test. The companion assert_not_dispatched::<E>(pred) asserts the
negative; dispatched_count::<E>(pred) returns the raw count for
finer-grained assertions.
Integration tests for email verification + password reset
Verify / reset tests need no torii - provision the auth_flow_tokens
table on an in-memory database, register a provider, set MAIL_FROM,
and drive the facade under Mail::fake(). The framework's own tests
mint the table directly from create_auth_flow_tokens_table():
use ConnectionTrait;
use create_auth_flow_tokens_table;
use Mail;
use TestDatabase;
async
The provider-backed paths (resend / verify / complete) additionally
register a dyn UserProvider binding so the lookup + mutation resolve -
see framework/tests/email_verify.rs and
framework/tests/password_reset.rs.
ToriiConfig::sqlite_in_memory() for brute-force + 2FA tests
Brute-force and 2FA tests spin up a fresh torii on an in-memory SQLite
database. The example test files in framework/tests/ use a shared
runtime + once_cell::sync::Lazy<()> pattern to amortise the cost
across tests, plus #[serial] to keep the process-global mail transport
stable between tests that interleave Mail::fake():
use Lazy;
use serial;
use Runtime;
use ;
static RT: = new;
static SETUP: = new;
Canonical examples - copy from these when writing your own:
framework/tests/email_verify.rs- verify token round-trip,send_linktrailing-slash trimming,Mail::fake()assertions on subject/HTML.framework/tests/password_reset.rs- reset round-trip with new-password authentication, anti-enumeration on unknown emails,completerejects reused tokens.framework/tests/brute_force.rs- full lockout lifecycle,AccountLockedfires once per transition,unlock_accountreturnswas_locked.framework/tests/two_factor.rs- full enroll → confirm → verify with a real TOTP code computed from the otpauth URL, recovery-code single-use, re-enrollment overwrites the secret, replay rejection across two concurrent verifies.framework/tests/two_factor_challenge_flow.rs- the end-to-end challenge flow with session rotation, remember-me re-issue, and event dispatch.framework/tests/email_verified_middleware.rsandtwo_factor_challenge_middleware.rs- middleware response shapes (403 JSON vs 302 vs 409 + X-Inertia-Location).
Reference
| Symbol | Purpose |
|---|---|
suprnova::auth_flows::EmailVerification |
send_link, resend, check, verify - provider-backed; verify returns the user id. |
suprnova::auth_flows::EnsureEmailVerifiedMiddleware |
new() for 403 JSON, redirect_to(path) for 302 / 409 + X-Inertia-Location. Checks the configured provider's is_email_verified (fail-closed). |
suprnova::auth_flows::PasswordReset |
send_link, check, complete - provider-backed; complete returns the user id. |
suprnova::MustVerifyEmail / suprnova::CanResetPassword |
Model traits a user behind EloquentUserProvider implements so the verify / reset facades can read its email + write its verification timestamp / password hash. |
suprnova::auth_flows::token_store::create_auth_flow_tokens_table |
SeaORM CREATE TABLE for auth_flow_tokens - list in your migrator. |
suprnova::auth_flows::BruteForce |
record_failed_attempt, reset_attempts, get_lockout_status, is_locked, unlock_account. |
suprnova::auth_flows::LoginThrottleMiddleware |
HTTP middleware that 429s pre-handler when the targeted account is locked. |
suprnova::auth_flows::TwoFactor |
enroll, re_enroll, confirm, verify, consume_recovery_code, regenerate_recovery_codes, is_enabled, is_enabled_by_id, start_challenge, pending_user_id, cancel_challenge, complete_challenge, disable. |
suprnova::auth_flows::TwoFactorUser |
Trait bridging the app's user model to the 2FA facade. |
suprnova::auth_flows::EnrollmentResponse |
Return value of TwoFactor::enroll - otpauth_url, qr_code_svg, recovery_codes. |
suprnova::auth_flows::TwoFactorChallengeMiddleware |
new() for 403 JSON, redirect_to(path) for 302 / 409 + X-Inertia-Location. Compose in front of AuthMiddleware. |
suprnova::auth_flows::two_factor::migration::Migration |
SeaORM migration for two_factor_credentials. List in your Migrator::migrations(). |
suprnova::auth_flows::two_factor::migration_replay::Migration |
Column add for last_used_timestep (TOTP replay protection). List after the create-table migration. |
suprnova::auth_flows::remember_me |
Re-export of suprnova::auth::remember. |
suprnova::auth_flows::events::* |
Nine events - see Events. |
suprnova::auth_flows::EmailVerificationMail |
Transactional Mailable. Subject "Verify your email for {APP_NAME}". |
suprnova::auth_flows::PasswordResetMail |
Transactional Mailable. Subject "Reset your {APP_NAME} password". |
suprnova::auth_flows::PasswordChangedMail |
Security-notification Mailable. Subject "Your {APP_NAME} password was changed". |
suprnova::torii_integration::ToriiConfig |
Torii bootstrap config. from_sea_orm(conn) for production, sqlite_in_memory() for tests. |
suprnova::torii_integration::init_torii |
Idempotent global init. Call once from bootstrap.rs::register(). |
Next
- Authentication - guards, providers, the
Authfacade,AuthMiddleware. - Mail - the transport layer the
send_linkcalls dispatch through. - Events - registering listeners for the nine auth-flow events.
- Rate Limiting - pair
RateLimitMiddleware::ip_basedwithLoginThrottleMiddlewarefor layered defence. - Session - what
start_challenge/complete_challengetouch when they rotate the session id.
