forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

reset.rs330 lines, 12.1 KiBHistoryRawDownload
1//! Password reset by mail: `GET/POST /forgot` asks for a link, `GET/POST /reset/{token}` spends it.
2//!
3//! The forgot answer is the same for every address. It is a redirect to the same place, and the work
4//! behind it is the same lookup either way. For a known, enabled address the link is created and mailed
5//! in a background task, so the response does not wait for the mail queue. Requests are counted per
6//! address and per client, and a counted-out request gets the same redirect with no work at all.
7//!
8//! The reset link is single use and lasts `policy.reset_minutes`. Spending it sets the password, ends
9//! every session of the person with its back-channel logouts, and signs the browser in again. An account
10//! with two-factor sign-in is sent to the sign-in page instead, so the second factor is still asked.
11
12use std::sync::Arc;
13use std::time::{Duration, Instant};
14
15use im_core::model::{AuditAction, User, amr};
16use im_core::names::{normalize_email, parse_email};
17use im_core::password::{check_policy, hash_password_async, verify_password_async};
18use im_core::store::Store;
19use im_core::store::audit::NewAudit;
20use im_core::store::sessions::SignInState;
21use im_core::time::stamp_after;
22use im_core::token::{generate_token, hash_token};
23use serde::Deserialize;
24use serde_json::json;
25use topcoat::Result;
26use topcoat::context::{Cx, app_context};
27use topcoat::router::content::Form;
28use topcoat::router::error::{forbidden, not_found, see_other};
29use topcoat::router::page;
30use topcoat::view::{View, view};
31
32use crate::audit::{Actor, record};
33use crate::auth::{after_sign_in, check_pre_csrf, clear_pre_csrf, pre_csrf_token, start_session};
34use crate::client_ip::client_ip;
35use crate::i18n::Lang;
36use crate::i18n::account::{Txt, policy_problem, text};
37use crate::i18n::flows::{Flow, text as flow_text};
38use crate::live::Topic;
39use crate::mail::{self, Mail, Notice, Recipient};
40use crate::pages::path_param;
41use crate::state::AppState;
42use crate::throttle::{FORGOT_EMAIL_LIMIT, FORGOT_IP_LIMIT, forgot_email_key, ip_key};
43use crate::views::{alert, field, notice, page_lang, shell};
44
45/// The forgot-password form.
46#[derive(Deserialize, Default)]
47struct ForgotForm {
48 #[serde(default)]
49 precsrf: String,
50 #[serde(default)]
51 email: String,
52}
53
54/// The query of `GET /forgot`: `sent=1` after a request.
55#[derive(Deserialize, Default)]
56struct ForgotQuery {
57 #[serde(default)]
58 sent: String,
59}
60
61/// The new-password form.
62#[derive(Deserialize, Default)]
63struct ResetForm {
64 #[serde(default)]
65 precsrf: String,
66 #[serde(default)]
67 password: String,
68 #[serde(default)]
69 password_again: String,
70}
71
72/// `GET /forgot`.
73#[page("/forgot")]
74async 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/// `POST /forgot`. The same redirect whatever the address is.
81#[page(POST "/forgot")]
82async 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 // Counted only while neither key is limited: a request refused by the limit is not counted again, so
93 // the mail of a flood is capped at the limit's worth per window.
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 // The same lookup for a known and an unknown address; only a known, enabled one gets a link.
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/// Creates a reset link for `user` and queues its mail, in the background. The mail is sealed first and the
125/// store checks its cooldown in the same transaction that creates the link, so a request inside the cooldown
126/// creates no link and leaves the older one working. Failures are logged; the person who asked sees the same
127/// answer either way.
128fn 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/// `GET /reset/{token}`. Only a live reset link opens the form; anything else is not found.
190#[page("/reset/{token}")]
191async 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/// `POST /reset/{token}`: sets the password and ends every session of the person.
210#[page(POST "/reset/{token}")]
211async 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 // The conditional spend and the password change are one transaction: a second request with the same
249 // link gets None here, even if both passed the checks above.
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 // The state the reset just set, with no second factor (checked above): a disable that committed
269 // since then refuses the session.
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/// The forgot-password page.
283fn 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.
304fn 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}