| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | use std::sync::Arc; |
| 13 | use std::time::{Duration, Instant}; |
| 14 | |
| 15 | use im_core::model::{AuditAction, User, amr}; |
| 16 | use im_core::names::{normalize_email, parse_email}; |
| 17 | use im_core::password::{check_policy, hash_password_async, verify_password_async}; |
| 18 | use im_core::store::Store; |
| 19 | use im_core::store::audit::NewAudit; |
| 20 | use im_core::store::sessions::SignInState; |
| 21 | use im_core::time::stamp_after; |
| 22 | use im_core::token::{generate_token, hash_token}; |
| 23 | use serde::Deserialize; |
| 24 | use serde_json::json; |
| 25 | use topcoat::Result; |
| 26 | use topcoat::context::{Cx, app_context}; |
| 27 | use topcoat::router::content::Form; |
| 28 | use topcoat::router::error::{forbidden, not_found, see_other}; |
| 29 | use topcoat::router::page; |
| 30 | use topcoat::view::{View, view}; |
| 31 | |
| 32 | use crate::audit::{Actor, record}; |
| 33 | use crate::auth::{after_sign_in, check_pre_csrf, clear_pre_csrf, pre_csrf_token, start_session}; |
| 34 | use crate::client_ip::client_ip; |
| 35 | use crate::i18n::Lang; |
| 36 | use crate::i18n::account::{Txt, policy_problem, text}; |
| 37 | use crate::i18n::flows::{Flow, text as flow_text}; |
| 38 | use crate::live::Topic; |
| 39 | use crate::mail::{self, Mail, Notice, Recipient}; |
| 40 | use crate::pages::path_param; |
| 41 | use crate::state::AppState; |
| 42 | use crate::throttle::{FORGOT_EMAIL_LIMIT, FORGOT_IP_LIMIT, forgot_email_key, ip_key}; |
| 43 | use crate::views::{alert, field, notice, page_lang, shell}; |
| 44 | |
| 45 | |
| 46 | #[derive(Deserialize, Default)] |
| 47 | struct ForgotForm { |
| 48 | #[serde(default)] |
| 49 | precsrf: String, |
| 50 | #[serde(default)] |
| 51 | email: String, |
| 52 | } |
| 53 | |
| 54 | |
| 55 | #[derive(Deserialize, Default)] |
| 56 | struct ForgotQuery { |
| 57 | #[serde(default)] |
| 58 | sent: String, |
| 59 | } |
| 60 | |
| 61 | |
| 62 | #[derive(Deserialize, Default)] |
| 63 | struct ResetForm { |
| 64 | #[serde(default)] |
| 65 | precsrf: String, |
| 66 | #[serde(default)] |
| 67 | password: String, |
| 68 | #[serde(default)] |
| 69 | password_again: String, |
| 70 | } |
| 71 | |
| 72 | |
| 73 | #[page("/forgot")] |
| 74 | async fn forgot_form(cx: &Cx, Form(query): Form<ForgotQuery>) -> Result<impl View> { |
| 75 | let csrf = pre_csrf_token(cx); |
| 76 | let lang = page_lang(cx, None); |
| 77 | Ok(forgot_view(cx, lang, csrf, query.sent == "1")) |
| 78 | } |
| 79 | |
| 80 | |
| 81 | #[page(POST "/forgot")] |
| 82 | async fn forgot_submit(cx: &Cx, Form(form): Form<ForgotForm>) -> Result<impl View> { |
| 83 | if !check_pre_csrf(cx, &form.precsrf) { |
| 84 | return Err(forbidden().into()); |
| 85 | } |
| 86 | let state = app_context::<AppState>(cx); |
| 87 | let lang = page_lang(cx, None); |
| 88 | let email = normalize_email(&form.email); |
| 89 | let client = client_ip(cx); |
| 90 | let email_limit = forgot_email_key(&email); |
| 91 | let client_limit = ip_key("forgot-ip", client); |
| 92 | |
| 93 | |
| 94 | let limited = state |
| 95 | .throttle |
| 96 | .reserve_all( |
| 97 | &[ |
| 98 | (&email_limit, FORGOT_EMAIL_LIMIT), |
| 99 | (&client_limit, FORGOT_IP_LIMIT), |
| 100 | ], |
| 101 | Instant::now(), |
| 102 | ) |
| 103 | .is_err(); |
| 104 | |
| 105 | |
| 106 | if !limited |
| 107 | && let Ok(address) = parse_email(&email) |
| 108 | && let Some(user) = state.store.user_by_email_folded(&address).await? |
| 109 | && !user.is_disabled() |
| 110 | { |
| 111 | spawn_reset( |
| 112 | state.store.clone(), |
| 113 | state.key.clone(), |
| 114 | state.config.base_url.clone(), |
| 115 | state.policy().reset_minutes, |
| 116 | user, |
| 117 | lang, |
| 118 | client.to_string(), |
| 119 | ); |
| 120 | } |
| 121 | Ok(forgot_view(cx, lang, pre_csrf_token(cx), true)) |
| 122 | } |
| 123 | |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | fn spawn_reset( |
| 129 | store: Store, |
| 130 | key: Arc<[u8; 32]>, |
| 131 | base_url: String, |
| 132 | minutes: u32, |
| 133 | user: User, |
| 134 | lang: Lang, |
| 135 | ip: String, |
| 136 | ) { |
| 137 | tokio::spawn(async move { |
| 138 | let token = generate_token(); |
| 139 | let expires = stamp_after(Duration::from_secs(u64::from(minutes) * 60)); |
| 140 | let link = format!("{base_url}/reset/{token}"); |
| 141 | let lang = mail::lang_for(&user, lang); |
| 142 | let to = match Recipient::new(Some(&user.name), &user.email) { |
| 143 | Ok(to) => to, |
| 144 | Err(error) => { |
| 145 | tracing::error!(error, "reset mail not queued"); |
| 146 | return; |
| 147 | } |
| 148 | }; |
| 149 | let mail = Mail::Reset { |
| 150 | link: &link, |
| 151 | minutes, |
| 152 | }; |
| 153 | let sealed = match mail::seal(&key, &to, lang, &mail) { |
| 154 | Ok(sealed) => sealed, |
| 155 | Err(error) => { |
| 156 | tracing::error!(error = %error, "reset mail not queued"); |
| 157 | return; |
| 158 | } |
| 159 | }; |
| 160 | match store |
| 161 | .create_reset_link(&user.id, &hash_token(&token), &expires, &sealed.as_new()) |
| 162 | .await |
| 163 | { |
| 164 | Ok(Some(_)) => {} |
| 165 | Ok(None) => { |
| 166 | tracing::info!("reset mail dropped by the cooldown; no link created"); |
| 167 | return; |
| 168 | } |
| 169 | Err(error) => { |
| 170 | tracing::error!(error = %error, "reset link not created"); |
| 171 | return; |
| 172 | } |
| 173 | } |
| 174 | let entry = NewAudit { |
| 175 | actor_id: None, |
| 176 | actor_kind: "anonymous", |
| 177 | action: AuditAction::ResetRequested.as_str(), |
| 178 | target_kind: Some("user"), |
| 179 | target_id: Some(&user.id), |
| 180 | ip: Some(ip.as_str()), |
| 181 | data: None, |
| 182 | }; |
| 183 | if let Err(error) = store.record_audit(&entry).await { |
| 184 | tracing::error!(error = %error, "audit entry was not written"); |
| 185 | } |
| 186 | }); |
| 187 | } |
| 188 | |
| 189 | |
| 190 | #[page("/reset/{token}")] |
| 191 | async fn reset_form(cx: &Cx) -> Result<impl View> { |
| 192 | let state = app_context::<AppState>(cx); |
| 193 | let Some(token) = path_param(cx, "token") else { |
| 194 | return Err(not_found().into()); |
| 195 | }; |
| 196 | if state |
| 197 | .store |
| 198 | .live_reset_link(&hash_token(&token)) |
| 199 | .await? |
| 200 | .is_none() |
| 201 | { |
| 202 | return Err(not_found().into()); |
| 203 | } |
| 204 | let csrf = pre_csrf_token(cx); |
| 205 | let lang = page_lang(cx, None); |
| 206 | Ok(reset_view(cx, lang, csrf, token, None)) |
| 207 | } |
| 208 | |
| 209 | |
| 210 | #[page(POST "/reset/{token}")] |
| 211 | async fn reset_submit(cx: &Cx, Form(form): Form<ResetForm>) -> Result<impl View> { |
| 212 | if !check_pre_csrf(cx, &form.precsrf) { |
| 213 | return Err(forbidden().into()); |
| 214 | } |
| 215 | let state = app_context::<AppState>(cx); |
| 216 | let Some(token) = path_param(cx, "token") else { |
| 217 | return Err(not_found().into()); |
| 218 | }; |
| 219 | let token_hash = hash_token(&token); |
| 220 | let Some(link) = state.store.live_reset_link(&token_hash).await? else { |
| 221 | return Err(not_found().into()); |
| 222 | }; |
| 223 | let Some(user) = state |
| 224 | .store |
| 225 | .user_by_id(&link.user_id) |
| 226 | .await? |
| 227 | .filter(|user| !user.is_disabled()) |
| 228 | else { |
| 229 | return Err(not_found().into()); |
| 230 | }; |
| 231 | let lang = mail::lang_for(&user, page_lang(cx, None)); |
| 232 | let csrf = pre_csrf_token(cx); |
| 233 | |
| 234 | if form.password != form.password_again { |
| 235 | let problem = text(lang, Txt::ErrPasswordsDiffer).to_owned(); |
| 236 | return Ok(reset_view(cx, lang, csrf, token, Some(problem))); |
| 237 | } |
| 238 | if let Err(violation) = check_policy(&form.password, &user.email, &user.name) { |
| 239 | let problem = policy_problem(lang, violation); |
| 240 | return Ok(reset_view(cx, lang, csrf, token, Some(problem))); |
| 241 | } |
| 242 | if verify_password_async(form.password.clone(), user.password_hash.clone()).await? { |
| 243 | let problem = text(lang, Txt::ErrPasswordSame).to_owned(); |
| 244 | return Ok(reset_view(cx, lang, csrf, token, Some(problem))); |
| 245 | } |
| 246 | |
| 247 | let hash = hash_password_async(form.password.clone()).await?; |
| 248 | |
| 249 | |
| 250 | let Some(user_id) = state.store.redeem_reset_link(&token_hash, &hash).await? else { |
| 251 | return Err(not_found().into()); |
| 252 | }; |
| 253 | state.live.bump(&Topic::Account(user_id.clone())); |
| 254 | record( |
| 255 | cx, |
| 256 | Actor::Anonymous, |
| 257 | AuditAction::PasswordReset, |
| 258 | Some(("user", &user_id)), |
| 259 | json!({}), |
| 260 | ) |
| 261 | .await; |
| 262 | mail::notify(&state.store, &state.key, &user, lang, Notice::PasswordReset).await; |
| 263 | |
| 264 | if user.totp_enabled() { |
| 265 | clear_pre_csrf(cx); |
| 266 | return Err(see_other("/login").into()); |
| 267 | } |
| 268 | |
| 269 | |
| 270 | let decided_on = SignInState { |
| 271 | password_hash: &hash, |
| 272 | totp_enabled: false, |
| 273 | }; |
| 274 | if !start_session(cx, &user, amr::PASSWORD, decided_on).await? { |
| 275 | clear_pre_csrf(cx); |
| 276 | return Err(see_other("/login").into()); |
| 277 | } |
| 278 | clear_pre_csrf(cx); |
| 279 | Err(see_other(after_sign_in(state, &user, "/")).into()) |
| 280 | } |
| 281 | |
| 282 | |
| 283 | fn forgot_view(cx: &Cx, lang: Lang, csrf: String, sent: bool) -> impl View { |
| 284 | view! { cx => |
| 285 | shell(title: flow_text(lang, Flow::ForgotTitle), lang: lang, viewer: None, |
| 286 | <section class="card narrow stack"> |
| 287 | <h1>(flow_text(lang, Flow::ForgotTitle))</h1> |
| 288 | if sent { |
| 289 | notice(message: flow_text(lang, Flow::ForgotSent).to_owned()) |
| 290 | } |
| 291 | <p class="muted">(flow_text(lang, Flow::ForgotIntro))</p> |
| 292 | <form method="post" action="/forgot" class="stack"> |
| 293 | <input type="hidden" name="precsrf" value=(csrf)> |
| 294 | field(label: text(lang, Txt::Email), name: "email", kind: "email", autocomplete: "username", value: String::new()) |
| 295 | <button type="submit" class="button primary">(flow_text(lang, Flow::ForgotSubmit))</button> |
| 296 | </form> |
| 297 | <p><a href="/login">(flow_text(lang, Flow::BackToSignIn))</a></p> |
| 298 | </section> |
| 299 | ) |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | /// The new-password page for `token`. The form posts back to the same path. |
| 304 | fn reset_view( |
| 305 | cx: &Cx, |
| 306 | lang: Lang, |
| 307 | csrf: String, |
| 308 | token: String, |
| 309 | problem: Option<String>, |
| 310 | ) -> impl View { |
| 311 | let action = format!("/reset/{token}"); |
| 312 | view! { cx => |
| 313 | shell(title: flow_text(lang, Flow::ResetTitle), lang: lang, viewer: None, |
| 314 | <section class="card narrow stack"> |
| 315 | <h1>(flow_text(lang, Flow::ResetTitle))</h1> |
| 316 | <p class="muted">(flow_text(lang, Flow::ResetIntro))</p> |
| 317 | if let Some(problem) = problem { |
| 318 | alert(message: problem) |
| 319 | } |
| 320 | <form method="post" action=(action) class="stack"> |
| 321 | <input type="hidden" name="precsrf" value=(csrf)> |
| 322 | field(label: text(lang, Txt::NewPassword), name: "password", kind: "password", autocomplete: "new-password", value: String::new()) |
| 323 | field(label: text(lang, Txt::NewPasswordAgain), name: "password_again", kind: "password", autocomplete: "new-password", value: String::new()) |
| 324 | <p class="hint">(text(lang, Txt::PasswordHint))</p> |
| 325 | <button type="submit" class="button primary">(flow_text(lang, Flow::ResetSubmit))</button> |
| 326 | </form> |
| 327 | </section> |
| 328 | ) |
| 329 | } |
| 330 | } |