//! Password reset by mail: `GET/POST /forgot` asks for a link, `GET/POST /reset/{token}` spends it. //! //! The forgot answer is the same for every address. It is a redirect to the same place, and the work //! behind it is the same lookup either way. For a known, enabled address the link is created and mailed //! in a background task, so the response does not wait for the mail queue. Requests are counted per //! address and per client, and a counted-out request gets the same redirect with no work at all. //! //! The reset link is single use and lasts `policy.reset_minutes`. Spending it sets the password, ends //! every session of the person with its back-channel logouts, and signs the browser in again. An account //! with two-factor sign-in is sent to the sign-in page instead, so the second factor is still asked. use std::sync::Arc; use std::time::{Duration, Instant}; use im_core::model::{AuditAction, User, amr}; use im_core::names::{normalize_email, parse_email}; use im_core::password::{check_policy, hash_password_async, verify_password_async}; use im_core::store::Store; use im_core::store::audit::NewAudit; use im_core::store::sessions::SignInState; use im_core::time::stamp_after; use im_core::token::{generate_token, hash_token}; use serde::Deserialize; use serde_json::json; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; use topcoat::router::error::{forbidden, not_found, see_other}; use topcoat::router::page; use topcoat::view::{View, view}; use crate::audit::{Actor, record}; use crate::auth::{after_sign_in, check_pre_csrf, clear_pre_csrf, pre_csrf_token, start_session}; use crate::client_ip::client_ip; use crate::i18n::Lang; use crate::i18n::account::{Txt, policy_problem, text}; use crate::i18n::flows::{Flow, text as flow_text}; use crate::live::Topic; use crate::mail::{self, Mail, Notice, Recipient}; use crate::pages::path_param; use crate::state::AppState; use crate::throttle::{FORGOT_EMAIL_LIMIT, FORGOT_IP_LIMIT, forgot_email_key, ip_key}; use crate::views::{alert, field, notice, page_lang, shell}; /// The forgot-password form. #[derive(Deserialize, Default)] struct ForgotForm { #[serde(default)] precsrf: String, #[serde(default)] email: String, } /// The query of `GET /forgot`: `sent=1` after a request. #[derive(Deserialize, Default)] struct ForgotQuery { #[serde(default)] sent: String, } /// The new-password form. #[derive(Deserialize, Default)] struct ResetForm { #[serde(default)] precsrf: String, #[serde(default)] password: String, #[serde(default)] password_again: String, } /// `GET /forgot`. #[page("/forgot")] async fn forgot_form(cx: &Cx, Form(query): Form) -> Result { let csrf = pre_csrf_token(cx); let lang = page_lang(cx, None); Ok(forgot_view(cx, lang, csrf, query.sent == "1")) } /// `POST /forgot`. The same redirect whatever the address is. #[page(POST "/forgot")] async fn forgot_submit(cx: &Cx, Form(form): Form) -> Result { if !check_pre_csrf(cx, &form.precsrf) { return Err(forbidden().into()); } let state = app_context::(cx); let lang = page_lang(cx, None); let email = normalize_email(&form.email); let client = client_ip(cx); let email_limit = forgot_email_key(&email); let client_limit = ip_key("forgot-ip", client); // Counted only while neither key is limited: a request refused by the limit is not counted again, so // the mail of a flood is capped at the limit's worth per window. let limited = state .throttle .reserve_all( &[ (&email_limit, FORGOT_EMAIL_LIMIT), (&client_limit, FORGOT_IP_LIMIT), ], Instant::now(), ) .is_err(); // The same lookup for a known and an unknown address; only a known, enabled one gets a link. if !limited && let Ok(address) = parse_email(&email) && let Some(user) = state.store.user_by_email_folded(&address).await? && !user.is_disabled() { spawn_reset( state.store.clone(), state.key.clone(), state.config.base_url.clone(), state.policy().reset_minutes, user, lang, client.to_string(), ); } Ok(forgot_view(cx, lang, pre_csrf_token(cx), true)) } /// Creates a reset link for `user` and queues its mail, in the background. The mail is sealed first and the /// store checks its cooldown in the same transaction that creates the link, so a request inside the cooldown /// creates no link and leaves the older one working. Failures are logged; the person who asked sees the same /// answer either way. fn spawn_reset( store: Store, key: Arc<[u8; 32]>, base_url: String, minutes: u32, user: User, lang: Lang, ip: String, ) { tokio::spawn(async move { let token = generate_token(); let expires = stamp_after(Duration::from_secs(u64::from(minutes) * 60)); let link = format!("{base_url}/reset/{token}"); let lang = mail::lang_for(&user, lang); let to = match Recipient::new(Some(&user.name), &user.email) { Ok(to) => to, Err(error) => { tracing::error!(error, "reset mail not queued"); return; } }; let mail = Mail::Reset { link: &link, minutes, }; let sealed = match mail::seal(&key, &to, lang, &mail) { Ok(sealed) => sealed, Err(error) => { tracing::error!(error = %error, "reset mail not queued"); return; } }; match store .create_reset_link(&user.id, &hash_token(&token), &expires, &sealed.as_new()) .await { Ok(Some(_)) => {} Ok(None) => { tracing::info!("reset mail dropped by the cooldown; no link created"); return; } Err(error) => { tracing::error!(error = %error, "reset link not created"); return; } } let entry = NewAudit { actor_id: None, actor_kind: "anonymous", action: AuditAction::ResetRequested.as_str(), target_kind: Some("user"), target_id: Some(&user.id), ip: Some(ip.as_str()), data: None, }; if let Err(error) = store.record_audit(&entry).await { tracing::error!(error = %error, "audit entry was not written"); } }); } /// `GET /reset/{token}`. Only a live reset link opens the form; anything else is not found. #[page("/reset/{token}")] async fn reset_form(cx: &Cx) -> Result { let state = app_context::(cx); let Some(token) = path_param(cx, "token") else { return Err(not_found().into()); }; if state .store .live_reset_link(&hash_token(&token)) .await? .is_none() { return Err(not_found().into()); } let csrf = pre_csrf_token(cx); let lang = page_lang(cx, None); Ok(reset_view(cx, lang, csrf, token, None)) } /// `POST /reset/{token}`: sets the password and ends every session of the person. #[page(POST "/reset/{token}")] async fn reset_submit(cx: &Cx, Form(form): Form) -> Result { if !check_pre_csrf(cx, &form.precsrf) { return Err(forbidden().into()); } let state = app_context::(cx); let Some(token) = path_param(cx, "token") else { return Err(not_found().into()); }; let token_hash = hash_token(&token); let Some(link) = state.store.live_reset_link(&token_hash).await? else { return Err(not_found().into()); }; let Some(user) = state .store .user_by_id(&link.user_id) .await? .filter(|user| !user.is_disabled()) else { return Err(not_found().into()); }; let lang = mail::lang_for(&user, page_lang(cx, None)); let csrf = pre_csrf_token(cx); if form.password != form.password_again { let problem = text(lang, Txt::ErrPasswordsDiffer).to_owned(); return Ok(reset_view(cx, lang, csrf, token, Some(problem))); } if let Err(violation) = check_policy(&form.password, &user.email, &user.name) { let problem = policy_problem(lang, violation); return Ok(reset_view(cx, lang, csrf, token, Some(problem))); } if verify_password_async(form.password.clone(), user.password_hash.clone()).await? { let problem = text(lang, Txt::ErrPasswordSame).to_owned(); return Ok(reset_view(cx, lang, csrf, token, Some(problem))); } let hash = hash_password_async(form.password.clone()).await?; // The conditional spend and the password change are one transaction: a second request with the same // link gets None here, even if both passed the checks above. let Some(user_id) = state.store.redeem_reset_link(&token_hash, &hash).await? else { return Err(not_found().into()); }; state.live.bump(&Topic::Account(user_id.clone())); record( cx, Actor::Anonymous, AuditAction::PasswordReset, Some(("user", &user_id)), json!({}), ) .await; mail::notify(&state.store, &state.key, &user, lang, Notice::PasswordReset).await; if user.totp_enabled() { clear_pre_csrf(cx); return Err(see_other("/login").into()); } // The state the reset just set, with no second factor (checked above): a disable that committed // since then refuses the session. let decided_on = SignInState { password_hash: &hash, totp_enabled: false, }; if !start_session(cx, &user, amr::PASSWORD, decided_on).await? { clear_pre_csrf(cx); return Err(see_other("/login").into()); } clear_pre_csrf(cx); Err(see_other(after_sign_in(state, &user, "/")).into()) } /// The forgot-password page. fn forgot_view(cx: &Cx, lang: Lang, csrf: String, sent: bool) -> impl View { view! { cx => shell(title: flow_text(lang, Flow::ForgotTitle), lang: lang, viewer: None,

(flow_text(lang, Flow::ForgotTitle))

if sent { notice(message: flow_text(lang, Flow::ForgotSent).to_owned()) }

(flow_text(lang, Flow::ForgotIntro))

field(label: text(lang, Txt::Email), name: "email", kind: "email", autocomplete: "username", value: String::new())

(flow_text(lang, Flow::BackToSignIn))

) } } /// The new-password page for `token`. The form posts back to the same path. fn reset_view( cx: &Cx, lang: Lang, csrf: String, token: String, problem: Option, ) -> impl View { let action = format!("/reset/{token}"); view! { cx => shell(title: flow_text(lang, Flow::ResetTitle), lang: lang, viewer: None,

(flow_text(lang, Flow::ResetTitle))

(flow_text(lang, Flow::ResetIntro))

if let Some(problem) = problem { alert(message: problem) }
field(label: text(lang, Txt::NewPassword), name: "password", kind: "password", autocomplete: "new-password", value: String::new()) field(label: text(lang, Txt::NewPasswordAgain), name: "password_again", kind: "password", autocomplete: "new-password", value: String::new())

(text(lang, Txt::PasswordHint))

) } }