//! The security page: the password, two-factor sign-in and the recovery codes of the signed-in //! person. Each change is a POST that checks the CSRF token first and then redirects (PRG), except //! where the codes are shown: those render on the POST response, once. use std::time::Instant; use base64::Engine as _; use base64::engine::general_purpose::STANDARD as BASE64; use im_core::model::AuditAction; use im_core::password::{check_policy, hash_password_async, verify_password_async}; use im_core::secret; use im_core::totp; 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::see_other; use topcoat::router::page; use topcoat::view::{View, component, view}; use crate::audit::{Actor, record}; use crate::auth::{Viewer, check_second_factor, require_csrf, require_user, unix_now}; use crate::i18n::Lang; use crate::i18n::account::{Txt, policy_problem, recovery_left, text}; use crate::live::Topic; use crate::mail::{self, Notice}; use crate::state::AppState; use crate::throttle::{LOGIN_USER_LIMIT, user_key}; use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell}; /// How many recovery codes one issue gives. const RECOVERY_CODES: usize = 10; /// The query of `GET /account/security`. #[derive(Deserialize, Default)] struct NoticeQuery { #[serde(default)] notice: String, } /// The password change form. #[derive(Deserialize, Default)] struct PasswordForm { #[serde(default)] csrf: String, #[serde(default)] current_password: String, #[serde(default)] new_password: String, #[serde(default)] new_password_again: String, } /// A form with a CSRF token and one six-digit code (or recovery code). #[derive(Deserialize, Default)] struct CodeForm { #[serde(default)] csrf: String, #[serde(default)] code: String, } /// The enrolment form: the current password when two-factor sign-in is off, a code when it is on. #[derive(Deserialize, Default)] struct StartForm { #[serde(default)] csrf: String, #[serde(default)] current_password: String, #[serde(default)] code: String, } /// The turn-off form: the password and a second factor. #[derive(Deserialize, Default)] struct DisableForm { #[serde(default)] csrf: String, #[serde(default)] current_password: String, #[serde(default)] code: String, } /// The recovery-code form: the password only. #[derive(Deserialize, Default)] struct RecoveryForm { #[serde(default)] csrf: String, #[serde(default)] current_password: String, } /// What the page shows above its sections: a notice, an error, or freshly issued codes. #[derive(Default)] struct Flash { notice: Option, alert: Option, codes: Vec, } impl Flash { fn alert(message: impl Into) -> Self { Self { alert: Some(message.into()), ..Self::default() } } } /// A pending enrolment, ready to show: the base32 secret, the otpauth link and the QR code. struct Enrolment { secret: String, link: String, qr: String, } /// `GET /account/security`. #[page("/account/security")] async fn security_page(cx: &Cx, Form(query): Form) -> Result { let viewer = require_user(cx).await?; let lang = page_lang(cx, Some(&viewer)); let flash_notice = match query.notice.as_str() { "enrol" => Some(text(lang, Txt::EnrolSecurityNotice)), "saved-password" => Some(text(lang, Txt::SavedPassword)), "saved-2fa-on" => Some(text(lang, Txt::Saved2faOn)), "saved-2fa-off" => Some(text(lang, Txt::Saved2faOff)), _ => None, }; let flash = Flash { notice: flash_notice.map(str::to_owned), ..Flash::default() }; render_security(cx, viewer.clone(), flash).await } /// `POST /account/security/password`. #[page(POST "/account/security/password")] async fn change_password(cx: &Cx, Form(form): Form) -> Result { let viewer = require_csrf(cx, &form.csrf).await?; let state = app_context::(cx); let lang = page_lang(cx, Some(&viewer)); if let Some(problem) = password_problem(state, &viewer, &form.current_password).await? { return render_security(cx, viewer.clone(), Flash::alert(text(lang, problem))).await; } if form.new_password != form.new_password_again { return render_security( cx, viewer.clone(), Flash::alert(text(lang, Txt::ErrPasswordsDiffer)), ) .await; } if let Err(violation) = check_policy(&form.new_password, &viewer.user.email, &viewer.user.name) { let message = policy_problem(lang, violation); return render_security(cx, viewer.clone(), Flash::alert(message)).await; } if verify_password_async(form.new_password.clone(), viewer.user.password_hash.clone()).await? { return render_security( cx, viewer.clone(), Flash::alert(text(lang, Txt::ErrPasswordSame)), ) .await; } let hash = hash_password_async(form.new_password.clone()).await?; // One transaction: the new hash, and the end of every other session of the person with the old // password. This session stays signed in. let ended = state .store .change_password(&viewer.user.id, &hash, &viewer.session.id) .await?; changed(state, &viewer); record( cx, Actor::User(&viewer.user.id), AuditAction::PasswordChanged, Some(("user", &viewer.user.id)), json!({ "sessions_ended": ended.len() }), ) .await; mail::notify( &state.store, &state.key, &viewer.user, lang, Notice::PasswordChanged, ) .await; Err(see_other("/account/security?notice=saved-password").into()) } /// `POST /account/security/2fa/start`: starts an enrolment. Turning on needs no code; replacing an /// authenticator of an account that already has two-factor sign-in needs its current code. #[page(POST "/account/security/2fa/start")] async fn start_enrolment(cx: &Cx, Form(form): Form) -> Result { let viewer = require_csrf(cx, &form.csrf).await?; let state = app_context::(cx); let lang = page_lang(cx, Some(&viewer)); if viewer.user.totp_enabled() { if form.code.trim().is_empty() { return render_security( cx, viewer.clone(), Flash::alert(text(lang, Txt::ErrCodeMissing)), ) .await; } if state.reserve_second_factor(&viewer.user.id).is_err() { return render_security( cx, viewer.clone(), Flash::alert(text(lang, Txt::ErrThrottled)), ) .await; } if check_second_factor(&state.store, &state.key, &viewer.user, &form.code) .await? .is_none() { return render_security( cx, viewer.clone(), Flash::alert(text(lang, Txt::ErrCodeInvalid)), ) .await; } state.refund_second_factor(&viewer.user.id); } else if let Some(problem) = password_problem(state, &viewer, &form.current_password).await? { // Turning two-factor sign-in on is a change of the account, so the password is needed too. return render_security(cx, viewer.clone(), Flash::alert(text(lang, problem))).await; } let secret = totp::new_secret(); let sealed = secret::seal(&state.key, secret::purpose::TOTP_SECRET, &secret)?; state .store .set_totp_pending(&viewer.user.id, &sealed) .await?; Err(see_other("/account/security").into()) } /// `POST /account/security/2fa/confirm`: the first code from the new authenticator turns /// two-factor sign-in on, and issues the recovery codes, shown once. #[page(POST "/account/security/2fa/confirm")] async fn confirm_enrolment(cx: &Cx, Form(form): Form) -> Result { let viewer = require_csrf(cx, &form.csrf).await?; let state = app_context::(cx); let lang = page_lang(cx, Some(&viewer)); let Some(sealed) = state.store.totp_pending(&viewer.user.id).await? else { return render_security( cx, viewer.clone(), Flash::alert(text(lang, Txt::ErrNoPending)), ) .await; }; let shared = secret::open(&state.key, secret::purpose::TOTP_SECRET, &sealed)?; let last = viewer .user .totp_last_step .and_then(|step| u64::try_from(step).ok()); let Some(step) = totp::verify(&shared, form.code.trim(), totp::step_for(unix_now()), last) else { return render_security( cx, viewer.clone(), Flash::alert(text(lang, Txt::ErrCodeInvalid)), ) .await; }; let codes = issue_codes(); let hashes: Vec = codes .iter() .map(|code| totp::recovery_code_hash(&state.key, code)) .collect(); // The other sessions end with the first factor (see `Store::enable_totp`); this one stays. let enabled = state .store .enable_totp( &viewer.user.id, &sealed, step, &hashes, Some(&viewer.session.id), ) .await?; // A parallel confirmation of the same enrolment got there first: its codes are the ones shown. if !enabled { return render_security( cx, viewer.clone(), Flash::alert(text(lang, Txt::ErrNoPending)), ) .await; } changed(state, &viewer); record( cx, Actor::User(&viewer.user.id), AuditAction::TotpEnabled, Some(("user", &viewer.user.id)), json!({ "recovery_codes": codes.len() }), ) .await; mail::notify( &state.store, &state.key, &viewer.user, lang, Notice::TwoFactorOn, ) .await; // Reload the person, so the page shows two-factor sign-in as on. let user = state .store .user_by_id(&viewer.user.id) .await? .ok_or(im_core::Error::NotFound)?; let viewer = Viewer { user, ..viewer }; let flash = Flash { notice: Some(text(lang, Txt::Saved2faOn).to_owned()), codes, ..Flash::default() }; render_security(cx, viewer.clone(), flash).await } /// `POST /account/security/2fa/disable`: needs the password and a second factor. #[page(POST "/account/security/2fa/disable")] async fn disable_two_factor(cx: &Cx, Form(form): Form) -> Result { let viewer = require_csrf(cx, &form.csrf).await?; let state = app_context::(cx); let lang = page_lang(cx, Some(&viewer)); if !viewer.user.totp_enabled() { return Err(see_other("/account/security").into()); } if let Some(problem) = password_problem(state, &viewer, &form.current_password).await? { return render_security(cx, viewer.clone(), Flash::alert(text(lang, problem))).await; } if form.code.trim().is_empty() { return render_security( cx, viewer.clone(), Flash::alert(text(lang, Txt::ErrCodeMissing)), ) .await; } if state.reserve_second_factor(&viewer.user.id).is_err() { return render_security( cx, viewer.clone(), Flash::alert(text(lang, Txt::ErrThrottled)), ) .await; } if check_second_factor(&state.store, &state.key, &viewer.user, &form.code) .await? .is_none() { return render_security( cx, viewer.clone(), Flash::alert(text(lang, Txt::ErrCodeInvalid)), ) .await; } // The other sessions end with the second factor (see `Store::disable_totp`); this one stays. state .store .disable_totp(&viewer.user.id, Some(&viewer.session.id)) .await?; state.clear_second_factor(&viewer.user.id); changed(state, &viewer); record( cx, Actor::User(&viewer.user.id), AuditAction::TotpDisabled, Some(("user", &viewer.user.id)), json!({}), ) .await; mail::notify( &state.store, &state.key, &viewer.user, lang, Notice::TwoFactorOff, ) .await; Err(see_other("/account/security?notice=saved-2fa-off").into()) } /// `POST /account/security/recovery`: replaces the recovery codes. The old codes stop working. #[page(POST "/account/security/recovery")] async fn regenerate_recovery(cx: &Cx, Form(form): Form) -> Result { let viewer = require_csrf(cx, &form.csrf).await?; let state = app_context::(cx); let lang = page_lang(cx, Some(&viewer)); if !viewer.user.totp_enabled() { return Err(see_other("/account/security").into()); } if let Some(problem) = password_problem(state, &viewer, &form.current_password).await? { return render_security(cx, viewer.clone(), Flash::alert(text(lang, problem))).await; } let codes = issue_codes(); let hashes: Vec = codes .iter() .map(|code| totp::recovery_code_hash(&state.key, code)) .collect(); state .store .replace_recovery_codes(&viewer.user.id, &hashes) .await?; record( cx, Actor::User(&viewer.user.id), AuditAction::RecoveryCodesIssued, Some(("user", &viewer.user.id)), json!({ "count": codes.len() }), ) .await; mail::notify( &state.store, &state.key, &viewer.user, lang, Notice::RecoveryCodes, ) .await; let flash = Flash { codes, ..Flash::default() }; render_security(cx, viewer.clone(), flash).await } /// Fresh recovery codes, in the form people type them (`xxxx-xxxx`). fn issue_codes() -> Vec { (0..RECOVERY_CODES) .map(|_| totp::new_recovery_code()) .collect() } /// Checks the password of the signed-in person, counted against the same limit as sign-in. The attempt is /// counted before the check, so parallel guesses cannot all pass. `None` when the password is right; /// otherwise the message to show: the throttle's, or the wrong-password one. Wrong passwords on this page /// count toward the sign-in limit, so guessing here locks sign-in too. pub async fn password_problem( state: &AppState, viewer: &Viewer, given: &str, ) -> Result> { let limit = user_key(&viewer.user.email); if state .throttle .reserve(&limit, LOGIN_USER_LIMIT, Instant::now()) .is_err() { return Ok(Some(Txt::ErrThrottled)); } if verify_password_async(given.to_owned(), viewer.user.password_hash.clone()).await? { state.throttle.clear(&limit); return Ok(None); } Ok(Some(Txt::ErrWrongPassword)) } /// Tells the open account pages that the person's security changed. fn changed(state: &AppState, viewer: &Viewer) { state.live.bump(&Topic::Account(viewer.user.id.clone())); } /// Builds the QR code of a secret as a `data:` image, so no request leaves the page for it. fn enrolment_of(state: &AppState, viewer: &Viewer, sealed: &str) -> Result { let shared = secret::open(&state.key, secret::purpose::TOTP_SECRET, sealed)?; let link = totp::otpauth_uri(&viewer.user.email, &shared); let code = qrcode::QrCode::new(link.as_bytes()) .map_err(|error| topcoat::Error::msg(error.to_string()))?; let svg = code .render::() .min_dimensions(240, 240) .build(); Ok(Enrolment { secret: totp::base32_encode(&shared), link, qr: format!("data:image/svg+xml;base64,{}", BASE64.encode(svg)), }) } /// The security page: reads what the sections show, then renders them. async fn render_security(cx: &Cx, viewer: Viewer, flash: Flash) -> Result { let state = app_context::(cx); let lang = page_lang(cx, Some(&viewer)); let pending = match state.store.totp_pending(&viewer.user.id).await? { Some(sealed) => Some(enrolment_of(state, &viewer, &sealed)?), None => None, }; let enabled = viewer.user.totp_enabled(); let unused = if enabled { state.store.unused_recovery_codes(&viewer.user.id).await? } else { 0 }; let info = ViewerInfo::of(&viewer); let csrf = viewer.session.csrf_token.clone(); Ok(security_view( cx, lang, info, csrf, enabled, unused, pending, flash, )) } /// The markup of the security page. It owns everything it shows, so it can outlive the handler. #[allow(clippy::too_many_arguments)] fn security_view( cx: &Cx, lang: Lang, info: ViewerInfo, csrf: String, enabled: bool, unused: u64, pending: Option, flash: Flash, ) -> impl View { let has_pending = pending.is_some(); let Flash { notice: flash_notice, alert: flash_alert, codes, } = flash; view! { cx => shell(title: text(lang, Txt::SecurityTitle), lang: lang, viewer: Some(info),

(text(lang, Txt::SecurityTitle))

if let Some(message) = flash_notice { notice(message: message) } if let Some(message) = flash_alert { alert(message: message) }

(text(lang, Txt::PasswordSection))

(text(lang, Txt::PasswordHelp))

field(label: text(lang, Txt::CurrentPassword), name: "current_password", kind: "password", autocomplete: "current-password", value: String::new()) field(label: text(lang, Txt::NewPassword), name: "new_password", kind: "password", autocomplete: "new-password", value: String::new()) field(label: text(lang, Txt::NewPasswordAgain), name: "new_password_again", kind: "password", autocomplete: "new-password", value: String::new())

(text(lang, Txt::PasswordHint))

(text(lang, Txt::TwoFactorSection))

if enabled {

(text(lang, Txt::TwoFactorOnText))

} else {

(text(lang, Txt::TwoFactorOffText))

} if let Some(pending) = pending { enrolment_block(lang: lang, csrf: csrf.clone(), secret: pending.secret, link: pending.link, qr: pending.qr) } if enabled {

(text(lang, Txt::ReplaceTitle))

(text(lang, Txt::ReplaceHelp))

field(label: text(lang, Txt::CodeFromApp), name: "code", kind: "text", autocomplete: "one-time-code", value: String::new())

(text(lang, Txt::RecoveryTitle))

(text(lang, Txt::RecoveryHelp))

(recovery_left(lang, unused))

(text(lang, Txt::RegenerateHelp))

field(label: text(lang, Txt::CurrentPassword), name: "current_password", kind: "password", autocomplete: "current-password", value: String::new())

(text(lang, Txt::DisableTitle))

(text(lang, Txt::DisableHelp))

field(label: text(lang, Txt::CurrentPassword), name: "current_password", kind: "password", autocomplete: "current-password", value: String::new()) field(label: text(lang, Txt::CodeFromApp), name: "code", kind: "text", autocomplete: "one-time-code", value: String::new())
} else if !has_pending {
field(label: text(lang, Txt::CurrentPassword), name: "current_password", kind: "password", autocomplete: "current-password", value: String::new())
} if !codes.is_empty() {

(text(lang, Txt::NewCodesTitle))

(text(lang, Txt::CodesShownOnce))

    for code in codes {
  • (code)
  • }
}
) } } /// A pending enrolment: the QR code, the secret to type, and the form that confirms the first code. #[component] async fn enrolment_block( lang: Lang, csrf: String, secret: String, link: String, qr: String, ) -> Result { Ok(view! {

(text(lang, Txt::PendingTitle))

(text(lang, Txt::PendingHelp))

(text(lang,

(text(lang, Txt::SecretKey)) (secret)

(text(lang, Txt::SetupLink))

field(label: text(lang, Txt::CodeFromApp), name: "code", kind: "text", autocomplete: "one-time-code", value: String::new())
}) }