forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.4 MiB7ef8c05Tahinli9 minutes ago334 commits

settings_security.rs1638 lines, 57.4 KiBHistoryRawDownload
1use std::time::{Duration, Instant};
2
3use forge_core::mail::MailKind;
4use forge_core::names::normalize_name;
5use forge_core::totp;
6use forge_core::{AuditAction, Session, User, secret};
7use http::header::{HeaderValue, RETRY_AFTER};
8use serde::Deserialize;
9use topcoat::Result;
10use topcoat::context::{Cx, context};
11use topcoat::router::content::Form;
12use topcoat::router::error::{SeeOther, see_other};
13use topcoat::router::{HeaderMap, StatusCode, page, query_params, route};
14use topcoat::view::{View, component, view};
15
16use crate::audit::{self, Actor, Target};
17use crate::auth::{
18 CsrfForm, hash_password_async, logout, require_csrf, require_user, two_factor_enabled,
19 verify_password_async, verify_second_factor,
20};
21use crate::i18n::packages::{self as pk, K as PK};
22use crate::i18n::releases_ci::{self as rc, K as RC};
23use crate::i18n::s;
24use crate::i18n::{self, Key, Lang, t};
25use crate::pages::passkeys::{PasskeyPanel, build_panel, passkeys_panel};
26use crate::pages::register::check_new_password;
27use crate::pages::settings_export;
28use crate::pages::settings_sessions::session_label;
29use crate::state::AppState;
30use crate::throttle::{self, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT};
31use crate::views::parts::{RailItem, SubPart, confirm_act, head, post_act, rail};
32use crate::views::{added_status, alert, rel_time, shell, user_facing_message};
33
34const RECOVERY_CODE_COUNT: usize = 10;
35const LOW_RECOVERY_CODES: u64 = 3;
36const MAX_DEVICE_NAME_CHARS: usize = 40;
37
38#[query_params(error = bad_request)]
39struct SecurityQuery {
40 saved: Option<String>,
41 part: Option<String>,
42}
43
44#[derive(Deserialize)]
45struct PasswordForm {
46 #[serde(default)]
47 csrf: String,
48 #[serde(default)]
49 current_password: String,
50 #[serde(default)]
51 new_password: String,
52 #[serde(default)]
53 confirm_password: String,
54}
55
56#[derive(Deserialize)]
57struct EmailForm {
58 #[serde(default)]
59 csrf: String,
60 #[serde(default)]
61 email: String,
62 #[serde(default)]
63 current_password: String,
64}
65
66#[derive(Deserialize)]
67struct CodeForm {
68 #[serde(default)]
69 csrf: String,
70 #[serde(default)]
71 current_password: String,
72 #[serde(default)]
73 code: String,
74}
75
76#[derive(Deserialize)]
77struct EnrollForm {
78 #[serde(default)]
79 csrf: String,
80 #[serde(default)]
81 code: String,
82 #[serde(default)]
83 name: String,
84}
85
86#[derive(Deserialize)]
87struct DisableForm {
88 #[serde(default)]
89 csrf: String,
90 #[serde(default)]
91 current_password: String,
92 #[serde(default)]
93 code: String,
94}
95
96#[derive(Deserialize)]
97struct DeleteAccountForm {
98 #[serde(default)]
99 csrf: String,
100 #[serde(default)]
101 current_password: String,
102 #[serde(default)]
103 code: String,
104 #[serde(default)]
105 confirm_username: String,
106}
107
108#[derive(Default)]
109struct Shown {
110 notice: Option<&'static str>,
111 password_error: Option<String>,
112 email_error: Option<String>,
113 email_draft: Option<String>,
114 two_factor_error: Option<String>,
115 two_factor_panel: TwoFactorPanel,
116 codes: Option<Vec<String>>,
117 throttled: Option<Duration>,
118 part: Option<String>,
119}
120
121#[derive(Clone, Copy, Default, PartialEq, Eq)]
122enum TwoFactorPanel {
123 #[default]
124 Setup,
125 Regenerate,
126 Disable,
127}
128
129struct DeviceView {
130 name: String,
131 added: Option<String>,
132 used: Option<String>,
133 codes_line: String,
134 codes_low: bool,
135}
136
137struct SecurityPage {
138 lang: Lang,
139 email: String,
140 email_verified: bool,
141 stored_email: String,
142 email_status: String,
143 email_sent: Option<String>,
144 mail_ready: bool,
145 pending: Option<(String, String)>,
146 password_changed: Option<String>,
147 two_factor: Option<DeviceView>,
148 passkeys: PasskeyPanel,
149 sessions: Vec<Session>,
150 current_session_id: String,
151 shown: Shown,
152}
153
154pub(crate) fn security_rail_items(
155 lang: Lang,
156 active: &str,
157 two_factor_on: bool,
158 passkey_count: usize,
159 session_count: usize,
160) -> Vec<RailItem> {
161 let two_factor_val = if two_factor_on {
162 t(lang, Key::PillOn)
163 } else {
164 t(lang, Key::PillOff)
165 };
166 vec![
167 RailItem {
168 name: t(lang, Key::Password).to_owned(),
169 val: String::new(),
170 href: "/settings/security?part=password".to_owned(),
171 current: active == "password",
172 },
173 RailItem {
174 name: t(lang, Key::Email).to_owned(),
175 val: String::new(),
176 href: "/settings/security?part=email".to_owned(),
177 current: active == "email",
178 },
179 RailItem {
180 name: t(lang, Key::TwoFactorAuth).to_owned(),
181 val: two_factor_val.to_owned(),
182 href: "/settings/security?part=two-factor".to_owned(),
183 current: active == "two-factor",
184 },
185 RailItem {
186 name: s(lang, "Passkeys", "Geçiş anahtarları").to_owned(),
187 val: passkey_count.to_string(),
188 href: "/settings/security?part=passkeys".to_owned(),
189 current: active == "passkeys",
190 },
191 RailItem {
192 name: t(lang, Key::Sessions).to_owned(),
193 val: session_count.to_string(),
194 href: "/settings/security?part=sessions".to_owned(),
195 current: active == "sessions",
196 },
197 RailItem {
198 name: t(lang, Key::SecurityLog).to_owned(),
199 val: String::new(),
200 href: "/settings/security/log".to_owned(),
201 current: active == "log",
202 },
203 ]
204}
205
206pub(crate) async fn security_rail_for(
207 state: &AppState,
208 lang: Lang,
209 viewer: &(User, Session),
210 active: &str,
211) -> forge_core::Result<Vec<RailItem>> {
212 let two_factor_on = two_factor_enabled(&state.store, &viewer.0.id).await?;
213 let passkey_count = state.store.list_passkeys(&viewer.0.id).await?.len();
214 let session_count = state.store.list_sessions(&viewer.0.id).await?.len();
215 Ok(security_rail_items(
216 lang,
217 active,
218 two_factor_on,
219 passkey_count,
220 session_count,
221 ))
222}
223
224#[component]
225async fn security_body(cx: &Cx, page: SecurityPage, csrf: &str) -> Result<impl View> {
226 let SecurityPage {
227 lang,
228 email,
229 email_verified,
230 stored_email,
231 email_status,
232 email_sent,
233 mail_ready,
234 pending,
235 password_changed,
236 two_factor,
237 passkeys,
238 sessions,
239 current_session_id,
240 shown,
241 } = page;
242 let Shown {
243 notice,
244 password_error,
245 email_error,
246 two_factor_error,
247 two_factor_panel,
248 codes,
249 part,
250 ..
251 } = shown;
252 let two_factor_on = two_factor.is_some();
253 let passkey_count = passkeys.items.len();
254 let session_count = sessions.len();
255 let others = sessions
256 .iter()
257 .filter(|session| session.id != current_session_id)
258 .count();
259 let pending_set = pending.is_some();
260 let password_open = password_error.is_some();
261 let email_open = email_error.is_some();
262 let email_set = !email.is_empty();
263 let show_resend = email_set && !email_verified && mail_ready;
264 let (regenerate_error, disable_error, setup_error) = match two_factor_panel {
265 TwoFactorPanel::Regenerate => (two_factor_error, None, None),
266 TwoFactorPanel::Disable => (None, two_factor_error, None),
267 TwoFactorPanel::Setup => (None, None, two_factor_error),
268 };
269 let regenerate_open = regenerate_error.is_some();
270 let disable_open = disable_error.is_some();
271 const TOPICS: [&str; 5] = ["password", "email", "two-factor", "passkeys", "sessions"];
272 let active: &'static str = if password_open {
273 "password"
274 } else if email_open {
275 "email"
276 } else if regenerate_open
277 || disable_open
278 || setup_error.is_some()
279 || codes.is_some()
280 || (pending_set && part.is_none())
281 {
282 "two-factor"
283 } else {
284 part.as_deref()
285 .and_then(|asked| TOPICS.into_iter().find(|topic| *topic == asked))
286 .unwrap_or("password")
287 };
288 let items = security_rail_items(lang, active, two_factor_on, passkey_count, session_count);
289 Ok(view! {
290 head(title: t(lang, Key::Security), sub: Vec::<SubPart>::new())
291 if let Some(message) = notice {
292 <p class="state" role="status">(message)</p>
293 }
294 <div class="work">
295 rail(label: t(lang, Key::Security), items: items)
296 <div class="sheet" data-topic=(active)>
297 <section class="sec" id="password">
298 <h2>(t(lang, Key::Password))</h2>
299 if let Some(stamp) = password_changed {
300 <p class="state">(i18n::last_changed_label(lang)) " " rel_time(lang: lang, stamp: stamp.as_str())</p>
301 }
302 if let Some(message) = password_error {
303 alert(message: message.as_str())
304 }
305 <form data-hard="true" method="post" action="/settings/security/password" class="fields">
306 <input type="hidden" name="csrf" value=(csrf)>
307 <div class="field">
308 <label for="current-password">(t(lang, Key::CurrentPassword))</label>
309 <input id="current-password" type="password" name="current_password" autocomplete="current-password" required=(true)>
310 </div>
311 <div class="field">
312 <label for="new-password">(t(lang, Key::NewPassword))</label>
313 <input id="new-password" type="password" name="new_password" autocomplete="new-password" minlength="10" maxlength="1024" required=(true)>
314 </div>
315 <div class="field">
316 <label for="confirm-password">(t(lang, Key::ConfirmNewPassword))</label>
317 <input id="confirm-password" type="password" name="confirm_password" autocomplete="new-password" required=(true)>
318 </div>
319 <button type="submit" class="primary">(t(lang, Key::ChangePassword))</button>
320 </form>
321 </section>
322 <section class="sec" id="email">
323 <h2>(t(lang, Key::Email))</h2>
324 if stored_email.is_empty() {
325 <p class="state">(t(lang, Key::EmailNoAddress))</p>
326 } else {
327 <p class="state"><span class="security-email">(stored_email.as_str())</span> (" · ")(email_status.as_str()) if let Some(stamp) = email_sent { " " rel_time(lang: lang, stamp: stamp.as_str()) }</p>
328 }
329 if let Some(message) = email_error {
330 alert(message: message.as_str())
331 }
332 <form method="post" action="/settings/security/email" class="fields">
333 <input type="hidden" name="csrf" value=(csrf)>
334 <div class="field">
335 <label for="email-address">(t(lang, Key::Email))</label>
336 <input id="email-address" type="email" name="email" autocomplete="email" maxlength="254" required=(true) value=(email.as_str())>
337 </div>
338 <div class="field">
339 <label for="email-current-password">(t(lang, Key::CurrentPassword))</label>
340 <input id="email-current-password" type="password" name="current_password" autocomplete="current-password" required=(true)>
341 </div>
342 <button type="submit" class="primary">(t(lang, Key::SaveEmail))</button>
343 </form>
344 if show_resend {
345 <div class="acts">
346 post_act(label: t(lang, Key::VerifyResend), action: "/settings/security/email/resend", csrf: csrf)
347 </div>
348 }
349 </section>
350 <section class="sec" id="two-factor">
351 <h2>(t(lang, Key::TwoFactorAuth))</h2>
352 if let Some(list) = codes {
353 <div class="opened" data-once="">
354 <p class="state">(t(lang, Key::RecoveryCodes))</p>
355 <p class="hint">(t(lang, Key::RecoveryCodesSave))</p>
356 <ul class="topic-list" id="recovery-codes">
357 for code in list.into_iter() {
358 <li><code>(code)</code></li>
359 }
360 </ul>
361 <div class="acts">
362 <button type="button" class="act" data-copy="recovery-codes" data-lines="" data-copied=(rc::t(lang, RC::CopyDone)) data-failed=(rc::t(lang, RC::CopyFailed))>(pk::t(lang, PK::CopyCommand))</button>
363 </div>
364 </div>
365 }
366 if let Some(device) = two_factor {
367 <p class="state">(t(lang, Key::PillOn)) " · " (device.name.as_str())</p>
368 <p class="state">added_status(lang: lang, added: device.added.as_deref(), used: device.used.as_deref())</p>
369 <div class="line">
370 <span class="name">(t(lang, Key::RecoveryCodes))</span>
371 <span class="val">(device.codes_line.as_str())</span>
372 </div>
373 if device.codes_low {
374 <p class="hint topic-warn">(t(lang, Key::CodesRunningLow))</p>
375 }
376 <details class="reveal" open=(regenerate_open)>
377 <summary class="act">(s(lang, "Regenerate…", "Yeniden oluştur…"))</summary>
378 <div class="opened">
379 if let Some(message) = regenerate_error {
380 alert(message: message.as_str())
381 }
382 <form data-hard="true" method="post" action="/settings/security/2fa/recovery" class="fields">
383 <input type="hidden" name="csrf" value=(csrf)>
384 <div class="field">
385 <label for="regenerate-password">(t(lang, Key::CurrentPassword))</label>
386 <input id="regenerate-password" type="password" name="current_password" autocomplete="current-password" required=(true)>
387 </div>
388 <div class="field">
389 <label for="regenerate-code">(t(lang, Key::Code))</label>
390 <input id="regenerate-code" type="text" name="code" autocomplete="one-time-code" required=(true)>
391 </div>
392 <button type="submit" class="primary">(t(lang, Key::RegenerateCodes))</button>
393 </form>
394 </div>
395 </details>
396 <details class="reveal" open=(disable_open)>
397 <summary class="act danger">(t(lang, Key::TurnOffTwoFactorButton))</summary>
398 <div class="opened">
399 if let Some(message) = disable_error {
400 alert(message: message.as_str())
401 }
402 <form data-hard="true" method="post" action="/settings/security/2fa/disable" class="fields">
403 <input type="hidden" name="csrf" value=(csrf)>
404 <div class="field">
405 <label for="disable-password">(t(lang, Key::CurrentPassword))</label>
406 <input id="disable-password" type="password" name="current_password" autocomplete="current-password" required=(true)>
407 </div>
408 <div class="field">
409 <label for="disable-code">(t(lang, Key::Code))</label>
410 <input id="disable-code" type="text" name="code" autocomplete="one-time-code" required=(true)>
411 </div>
412 <button type="submit" class="danger">(t(lang, Key::TurnOffTwoFactorButton))</button>
413 </form>
414 </div>
415 </details>
416 } else if pending_set {
417 <p class="state">(t(lang, Key::SetupInProgress))</p>
418 } else {
419 <p class="state">(t(lang, Key::PillOff))</p>
420 <div class="acts">
421 <form data-hard="true" method="post" action="/settings/security/2fa/enable" class="act-form">
422 <input type="hidden" name="csrf" value=(csrf)>
423 <button type="submit" class="act">(t(lang, Key::SetUpAction))</button>
424 </form>
425 </div>
426 }
427 if let Some((secret, uri)) = pending {
428 <p class="state">(t(lang, Key::SecretPrefix)) <code>(secret)</code></p>
429 <p class="state">(t(lang, Key::LinkPrefix)) <code>(uri)</code></p>
430 if let Some(message) = setup_error {
431 alert(message: message.as_str())
432 }
433 <form data-hard="true" method="post" action="/settings/security/2fa/confirm" class="fields">
434 <input type="hidden" name="csrf" value=(csrf)>
435 <div class="field">
436 <label for="enrol-code">(t(lang, Key::CodeFromApp))</label>
437 <input id="enrol-code" type="text" name="code" inputmode="numeric" autocomplete="one-time-code" maxlength="6" required=(true)>
438 </div>
439 <div class="field">
440 <label for="enrol-name">(t(lang, Key::DeviceName))</label>
441 <input id="enrol-name" type="text" name="name" autocomplete="off" maxlength="40" placeholder=(t(lang, Key::AuthenticatorApp))>
442 </div>
443 <button type="submit" class="primary">(t(lang, Key::ConfirmAndTurnOn))</button>
444 </form>
445 }
446 </section>
447 passkeys_panel(lang: lang, csrf: csrf, panel: passkeys)
448 <section class="sec" id="sessions">
449 <h2>(t(lang, Key::Sessions))</h2>
450 if others > 0 {
451 <div class="acts">
452 confirm_act(lang: lang, label: t(lang, Key::RevokeAllOthers), action: "/settings/sessions/revoke-others", csrf: csrf)
453 </div>
454 }
455 for session in sessions.into_iter() {
456 <div class="line">
457 <span class="name">(session_label(lang, &session))</span>
458 <span class="val">
459 if session.id == current_session_id {
460 (t(lang, Key::ThisSession)) " · "
461 }
462 if let Some(ip) = session.last_ip.as_deref() {
463 (ip) " · "
464 }
465 (i18n::dated_label(lang, Key::LastSeen)) " " rel_time(lang: lang, stamp: session.last_seen.as_str()) " · " (t(lang, Key::SignedIn)) " " rel_time(lang: lang, stamp: session.created_at.as_str())
466 </span>
467 if session.id != current_session_id {
468 confirm_act(lang: lang, label: t(lang, Key::Revoke), action: "/settings/sessions/revoke", csrf: csrf, fields: vec![("id".to_owned(), session.id.clone())])
469 }
470 </div>
471 }
472 </section>
473 </div>
474 </div>
475 })
476}
477
478fn notice_for(lang: Lang, saved: Option<&str>) -> Option<&'static str> {
479 match saved {
480 Some("password") => Some(t(lang, Key::OkPasswordChanged)),
481 Some("email") => Some(t(lang, Key::OkEmailSaved)),
482 Some("verify_sent") => Some(t(lang, Key::OkVerifySent)),
483 Some("verify_wait") => Some(s(
484 lang,
485 "Too many verification emails went to this address lately, so none was sent now. Wait a few minutes, then use Resend.",
486 "Bu adrese son zamanlarda çok fazla doğrulama e-postası gönderildi, bu yüzden şimdi gönderilmedi. Birkaç dakika bekleyip Yeniden gönder'i kullanın.",
487 )),
488 Some("2fa-off") => Some(t(lang, Key::OkTwoFactorOff)),
489 Some("passkey-added") => Some(s(lang, "Passkey added.", "Geçiş anahtarı eklendi.")),
490 Some("passkey-renamed") => Some(s(
491 lang,
492 "Passkey renamed.",
493 "Geçiş anahtarı yeniden adlandırıldı.",
494 )),
495 Some("passkey-deleted") => Some(s(lang, "Passkey deleted.", "Geçiş anahtarı silindi.")),
496 Some("passkey-bad-name") => Some(s(
497 lang,
498 "A passkey name is 1 to 40 characters on one line.",
499 "Geçiş anahtarı adı tek satırda 1 ile 40 karakter olmalı.",
500 )),
501 _ => None,
502 }
503}
504
505pub(crate) async fn mail_can_send(state: &AppState) -> bool {
506 if state.config.mail.transport == forge_core::config::MailTransport::Log {
507 return true;
508 }
509 match state.store.mail_settings().await {
510 Ok(settings) => {
511 settings.enabled
512 && !settings.host.trim().is_empty()
513 && !settings.from_addr.trim().is_empty()
514 }
515 Err(_) => false,
516 }
517}
518
519async fn build_page(
520 state: &AppState,
521 lang: Lang,
522 viewer: &(User, Session),
523 shown: Shown,
524) -> forge_core::Result<SecurityPage> {
525 let totp_state = state.store.totp_state(&viewer.0.id).await?;
526 let (pending, two_factor) = match totp_state {
527 Some(totp) if totp.enabled => {
528 let unused = state.store.unused_recovery_codes(&viewer.0.id).await?;
529 let device = DeviceView {
530 name: totp
531 .name
532 .unwrap_or_else(|| t(lang, Key::AuthenticatorApp).to_owned()),
533 added: totp.created_at.clone(),
534 used: totp.last_used_at.clone(),
535 codes_line: i18n::codes_left_line(lang, unused, RECOVERY_CODE_COUNT as u64),
536 codes_low: unused <= LOW_RECOVERY_CODES,
537 };
538 (None, Some(device))
539 }
540 Some(totp) => match totp.sealed_secret {
541 Some(sealed) => {
542 let shared = secret::open(&state.key, &sealed)?;
543 let pending = (
544 totp::base32_encode(&shared),
545 totp::otpauth_uri(&viewer.0.username, &shared),
546 );
547 (Some(pending), None)
548 }
549 None => (None, None),
550 },
551 None => (None, None),
552 };
553 let password_changed = state.store.password_changed_at(&viewer.0.id).await?;
554 let stored_email = viewer.0.email.clone().unwrap_or_default();
555 let email_verified = state.store.email_is_verified(&viewer.0.id).await?;
556 let mut email_sent = None;
557 let email_status = if stored_email.is_empty() {
558 String::new()
559 } else if email_verified {
560 t(lang, Key::PillVerified).to_owned()
561 } else {
562 let mut status = t(lang, Key::EmailNotVerified).to_owned();
563 if let Some(mail) = state
564 .store
565 .latest_mail_for(&viewer.0.id, MailKind::Verification)
566 .await?
567 {
568 let line = i18n::email_mail_line(lang, mail.state, mail.attempts);
569 status = format!("{status} · {line}");
570 if matches!(mail.state, forge_core::mail::MailState::Sent) {
571 email_sent = mail.sent_at;
572 }
573 }
574 status
575 };
576 let email = shown
577 .email_draft
578 .clone()
579 .unwrap_or_else(|| viewer.0.email.clone().unwrap_or_default());
580 Ok(SecurityPage {
581 lang,
582 passkeys: build_panel(state, &viewer.0.id).await?,
583 email_verified,
584 stored_email,
585 email_status,
586 email_sent,
587 mail_ready: mail_can_send(state).await,
588 email,
589 pending,
590 password_changed,
591 two_factor,
592 sessions: state.store.list_sessions(&viewer.0.id).await?,
593 current_session_id: viewer.1.id.clone(),
594 shown,
595 })
596}
597
598async fn respond(cx: &Cx, viewer: (User, Session), shown: Shown) -> Result<impl View> {
599 let state = context::<AppState>(cx);
600 let mut headers = HeaderMap::new();
601 let status = match shown.throttled {
602 Some(retry) => {
603 headers.insert(RETRY_AFTER, HeaderValue::from(retry.as_secs().max(1)));
604 StatusCode::TOO_MANY_REQUESTS
605 }
606 None => StatusCode::OK,
607 };
608 let lang = i18n::lang(cx, Some(&viewer.0));
609 let page = build_page(state, lang, &viewer, shown).await?;
610 let csrf = viewer.1.csrf_token.clone();
611 Ok(view! {
612 (status)
613 (headers)
614 shell(title: t(lang, Key::Security), viewer: Some(&viewer), security_body(page: page, csrf: csrf.as_str()))
615 })
616}
617
618struct Refused {
619 message: &'static str,
620 retry: Option<Duration>,
621}
622
623async fn require_password(
624 lang: Lang,
625 state: &AppState,
626 user: &User,
627 password: &str,
628) -> forge_core::Result<std::result::Result<(), Refused>> {
629 let key = throttle::user_key(&normalize_name(&user.username));
630 let now = Instant::now();
631 if let Some(retry) = state.throttle.check(&key, LOGIN_USER_LIMIT, now) {
632 return Ok(Err(Refused {
633 message: t(lang, Key::ErrThrottled),
634 retry: Some(retry),
635 }));
636 }
637 if verify_password_async(password.to_owned(), user.password_hash.clone()).await? {
638 state.throttle.clear(&key);
639 Ok(Ok(()))
640 } else {
641 state.throttle.record_failure(&key, now);
642 Ok(Err(Refused {
643 message: t(lang, Key::ErrWrongPassword),
644 retry: None,
645 }))
646 }
647}
648
649fn second_factor_blocked(state: &AppState, user_id: &str) -> Option<Duration> {
650 state.throttle.check(
651 &throttle::two_factor_key(user_id),
652 TWO_FACTOR_USER_LIMIT,
653 Instant::now(),
654 )
655}
656
657async fn check_second_factor(
658 state: &AppState,
659 lang: Lang,
660 user_id: &str,
661 code: &str,
662) -> forge_core::Result<std::result::Result<(), Refused>> {
663 if let Some(retry) = second_factor_blocked(state, user_id) {
664 return Ok(Err(Refused {
665 message: t(lang, Key::ErrThrottled),
666 retry: Some(retry),
667 }));
668 }
669 let key = throttle::two_factor_key(user_id);
670 if verify_second_factor(&state.store, &state.key, user_id, code).await? {
671 state.throttle.clear(&key);
672 Ok(Ok(()))
673 } else {
674 state.throttle.record_failure(&key, Instant::now());
675 Ok(Err(Refused {
676 message: t(lang, Key::ErrWrongCode),
677 retry: None,
678 }))
679 }
680}
681
682fn new_recovery_codes() -> (Vec<String>, Vec<String>) {
683 let codes: Vec<String> = (0..RECOVERY_CODE_COUNT)
684 .map(|_| totp::new_recovery_code())
685 .collect();
686 let hashes = codes.iter().map(|c| totp::recovery_code_hash(c)).collect();
687 (codes, hashes)
688}
689
690#[page("/settings/security")]
691async fn security_page(cx: &Cx) -> Result<impl View> {
692 let viewer = require_user(cx).await?;
693 let lang = i18n::lang(cx, Some(&viewer.0));
694 let query = query_params::<SecurityQuery>(cx)?;
695 if query.part.as_deref() == Some("danger") {
696 return Err(see_other("/settings/export?part=delete").into());
697 }
698 let saved = query.saved.clone();
699 let part = query.part.clone().or_else(|| {
700 saved.as_deref().map(|saved| {
701 match saved {
702 "password" => "password",
703 "2fa-off" => "two-factor",
704 s if s.starts_with("passkey") => "passkeys",
705 _ => "email",
706 }
707 .to_owned()
708 })
709 });
710 let shown = Shown {
711 notice: notice_for(lang, saved.as_deref()),
712 part,
713 ..Shown::default()
714 };
715 respond(cx, viewer, shown).await
716}
717
718#[page(POST "/settings/security/password")]
719async fn password_change(cx: &Cx, Form(form): Form<PasswordForm>) -> Result<impl View> {
720 let viewer = require_csrf(cx, &form.csrf).await?;
721 let lang = i18n::lang(cx, Some(&viewer.0));
722 let state = context::<AppState>(cx);
723 let mut shown = Shown::default();
724 if let Err(refused) = require_password(lang, state, &viewer.0, &form.current_password).await? {
725 shown.password_error = Some(refused.message.into());
726 shown.throttled = refused.retry;
727 return respond(cx, viewer, shown).await;
728 }
729 if let Some(message) = check_new_password(lang, &form.new_password, &form.confirm_password) {
730 shown.password_error = Some(message);
731 return respond(cx, viewer, shown).await;
732 }
733 let hash = hash_password_async(form.new_password).await?;
734 state.store.set_password_hash(&viewer.0.id, &hash).await?;
735 state
736 .store
737 .delete_sessions_except(&viewer.0.id, &viewer.1.id)
738 .await?;
739 audit::record(
740 &state.store,
741 Some(cx),
742 Actor::User(&viewer.0),
743 AuditAction::PasswordChanged,
744 Target::default(),
745 serde_json::Value::Null,
746 )
747 .await;
748 if let Err(e) = crate::mail::account::send_password_changed(
749 state,
750 &viewer.0,
751 &forge_core::time::now_stamp(),
752 )
753 .await
754 {
755 tracing::warn!(error = %e, "could not queue the password change notice");
756 }
757 Err(see_other("/settings/security?saved=password").into())
758}
759
760#[page(POST "/settings/security/email")]
761async fn email_change(cx: &Cx, Form(form): Form<EmailForm>) -> Result<impl View> {
762 let viewer = require_csrf(cx, &form.csrf).await?;
763 let lang = i18n::lang(cx, Some(&viewer.0));
764 let state = context::<AppState>(cx);
765 let email = form.email.trim().to_owned();
766 let mut shown = Shown {
767 email_draft: Some(email.clone()),
768 ..Shown::default()
769 };
770 if let Err(refused) = require_password(lang, state, &viewer.0, &form.current_password).await? {
771 shown.email_error = Some(refused.message.into());
772 shown.throttled = refused.retry;
773 return respond(cx, viewer, shown).await;
774 }
775 match state.store.set_email(&viewer.0.id, &email).await {
776 Ok(()) => {
777 state.store.clear_email_verified(&viewer.0.id).await?;
778 let sent = crate::mail::account::send_verify(state, &viewer.0, &email).await?;
779 crate::signatures::on_keys_changed(state, &viewer.0.id).await;
780 audit::record(
781 &state.store,
782 Some(cx),
783 Actor::User(&viewer.0),
784 AuditAction::EmailChanged,
785 Target::default(),
786 serde_json::Value::Null,
787 )
788 .await;
789 let saved = if sent { "email" } else { "verify_wait" };
790 Err(see_other(format!("/settings/security?saved={saved}")).into())
791 }
792 Err(e) => match user_facing_message(&e) {
793 Some(message) => {
794 shown.email_error = Some(message);
795 respond(cx, viewer, shown).await
796 }
797 None => Err(e.into()),
798 },
799 }
800}
801
802#[route(POST "/settings/security/2fa/enable")]
803async fn two_factor_enable(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> {
804 let (user, _session) = require_csrf(cx, &form.csrf).await?;
805 let state = context::<AppState>(cx);
806 if !two_factor_enabled(&state.store, &user.id).await? {
807 let sealed = secret::seal(&state.key, &totp::new_secret())?;
808 state.store.set_totp_secret(&user.id, &sealed).await?;
809 }
810 Ok(see_other("/settings/security"))
811}
812
813#[page(POST "/settings/security/2fa/confirm")]
814async fn two_factor_confirm(cx: &Cx, Form(form): Form<EnrollForm>) -> Result<impl View> {
815 let viewer = require_csrf(cx, &form.csrf).await?;
816 let lang = i18n::lang(cx, Some(&viewer.0));
817 let state = context::<AppState>(cx);
818 let user_id = viewer.0.id.clone();
819 let Some(totp_state) = state.store.totp_state(&user_id).await? else {
820 return Err(see_other("/settings/security").into());
821 };
822 let sealed = match (&totp_state.sealed_secret, totp_state.enabled) {
823 (Some(sealed), false) => sealed.clone(),
824 _ => return Err(see_other("/settings/security").into()),
825 };
826 let mut shown = Shown::default();
827 if let Some(retry) = second_factor_blocked(state, &user_id) {
828 shown.two_factor_error = Some(t(lang, Key::ErrThrottled).into());
829 shown.throttled = Some(retry);
830 return respond(cx, viewer, shown).await;
831 }
832 let name = form.name.trim();
833 if name.chars().count() > MAX_DEVICE_NAME_CHARS || name.chars().any(char::is_control) {
834 shown.two_factor_error = Some(t(lang, Key::ErrDeviceName).into());
835 return respond(cx, viewer, shown).await;
836 }
837 let name = (!name.is_empty()).then(|| name.to_owned());
838 let shared = secret::open(&state.key, &sealed)?;
839 let key = throttle::two_factor_key(&user_id);
840 match totp::verify(
841 &shared,
842 form.code.trim(),
843 totp::step_for(forge_core::time::now_unix()),
844 totp_state.last_step,
845 ) {
846 Some(step) => {
847 state.throttle.clear(&key);
848 let (codes, hashes) = new_recovery_codes();
849 state.store.enable_totp(&user_id, step, &hashes).await?;
850 state.store.set_totp_name(&user_id, name.as_deref()).await?;
851 audit::record(
852 &state.store,
853 Some(cx),
854 Actor::User(&viewer.0),
855 AuditAction::TotpEnabled,
856 Target::default(),
857 serde_json::Value::Null,
858 )
859 .await;
860 shown.notice = Some(t(lang, Key::OkTwoFactorOn));
861 shown.codes = Some(codes);
862 respond(cx, viewer, shown).await
863 }
864 None => {
865 state.throttle.record_failure(&key, Instant::now());
866 shown.two_factor_error = Some(t(lang, Key::ErrWrongConfirmCode).into());
867 respond(cx, viewer, shown).await
868 }
869 }
870}
871
872#[page(POST "/settings/security/2fa/disable")]
873async fn two_factor_disable(cx: &Cx, Form(form): Form<DisableForm>) -> Result<impl View> {
874 let viewer = require_csrf(cx, &form.csrf).await?;
875 let lang = i18n::lang(cx, Some(&viewer.0));
876 let state = context::<AppState>(cx);
877 let user_id = viewer.0.id.clone();
878 if !two_factor_enabled(&state.store, &user_id).await? {
879 return Err(see_other("/settings/security").into());
880 }
881 let mut shown = Shown {
882 two_factor_panel: TwoFactorPanel::Disable,
883 ..Shown::default()
884 };
885 if let Err(refused) = require_password(lang, state, &viewer.0, &form.current_password).await? {
886 shown.two_factor_error = Some(refused.message.into());
887 shown.throttled = refused.retry;
888 return respond(cx, viewer, shown).await;
889 }
890 if let Err(refused) = check_second_factor(state, lang, &user_id, &form.code).await? {
891 shown.two_factor_error = Some(refused.message.into());
892 shown.throttled = refused.retry;
893 return respond(cx, viewer, shown).await;
894 }
895 state.store.disable_totp(&user_id).await?;
896 audit::record(
897 &state.store,
898 Some(cx),
899 Actor::User(&viewer.0),
900 AuditAction::TotpDisabled,
901 Target::default(),
902 serde_json::Value::Null,
903 )
904 .await;
905 Err(see_other("/settings/security?saved=2fa-off").into())
906}
907
908#[page(POST "/settings/security/delete")]
909async fn account_delete(cx: &Cx, Form(form): Form<DeleteAccountForm>) -> Result<impl View> {
910 let viewer = require_csrf(cx, &form.csrf).await?;
911 let lang = i18n::lang(cx, Some(&viewer.0));
912 let state = context::<AppState>(cx);
913 let user_id = viewer.0.id.clone();
914 if form.confirm_username != viewer.0.username {
915 let error = Some(t(lang, Key::ErrConfirmUsername).into());
916 return settings_export::respond_delete(cx, viewer, error, None).await;
917 }
918 if let Err(refused) = require_password(lang, state, &viewer.0, &form.current_password).await? {
919 let error = Some(refused.message.into());
920 return settings_export::respond_delete(cx, viewer, error, refused.retry).await;
921 }
922 if two_factor_enabled(&state.store, &user_id).await? {
923 if let Err(refused) = check_second_factor(state, lang, &user_id, &form.code).await? {
924 let error = Some(refused.message.into());
925 return settings_export::respond_delete(cx, viewer, error, refused.retry).await;
926 }
927 }
928 let ghost = state.store.ensure_ghost_user().await?;
929 match state.store.delete_user(&user_id, &ghost.id).await {
930 Ok(_) => {
931 crate::live::bump_account(state, &user_id);
932 audit::record(
933 &state.store,
934 Some(cx),
935 Actor::Anonymous,
936 AuditAction::UserDeleted,
937 Target {
938 kind: "user",
939 id: &user_id,
940 name: &viewer.0.username,
941 },
942 serde_json::json!({ "self_service": true }),
943 )
944 .await;
945 logout(cx, &viewer.1).await?;
946 Err(see_other("/").into())
947 }
948 Err(e) => match user_facing_message(&e) {
949 Some(message) => settings_export::respond_delete(cx, viewer, Some(message), None).await,
950 None => Err(e.into()),
951 },
952 }
953}
954
955#[page(POST "/settings/security/2fa/recovery")]
956async fn two_factor_recovery(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl View> {
957 let viewer = require_csrf(cx, &form.csrf).await?;
958 let lang = i18n::lang(cx, Some(&viewer.0));
959 let state = context::<AppState>(cx);
960 let user_id = viewer.0.id.clone();
961 if !two_factor_enabled(&state.store, &user_id).await? {
962 return Err(see_other("/settings/security").into());
963 }
964 let mut shown = Shown {
965 two_factor_panel: TwoFactorPanel::Regenerate,
966 ..Shown::default()
967 };
968 if let Err(refused) = require_password(lang, state, &viewer.0, &form.current_password).await? {
969 shown.two_factor_error = Some(refused.message.into());
970 shown.throttled = refused.retry;
971 return respond(cx, viewer, shown).await;
972 }
973 if let Err(refused) = check_second_factor(state, lang, &user_id, &form.code).await? {
974 shown.two_factor_error = Some(refused.message.into());
975 shown.throttled = refused.retry;
976 return respond(cx, viewer, shown).await;
977 }
978 let (codes, hashes) = new_recovery_codes();
979 state
980 .store
981 .replace_recovery_codes(&user_id, &hashes)
982 .await?;
983 audit::record(
984 &state.store,
985 Some(cx),
986 Actor::User(&viewer.0),
987 AuditAction::RecoveryCodesRegenerated,
988 Target::default(),
989 serde_json::Value::Null,
990 )
991 .await;
992 shown.notice = Some(t(lang, Key::OkRecoveryCodesNew));
993 shown.codes = Some(codes);
994 respond(cx, viewer, shown).await
995}
996
997#[cfg(test)]
998mod tests {
999 use forge_core::time::stamp_after;
1000 use forge_core::token::hash_token;
1001 use forge_core::{User, secret, totp};
1002 use topcoat::router::request::Request;
1003 use topcoat::router::{Body, Router, to_bytes};
1004
1005 use crate::auth::{SESSION_COOKIE, hash_password_async};
1006 use crate::state::AppState;
1007 use crate::throttle::{LOGIN_USER_LIMIT, user_key};
1008
1009 const TOKEN: &str = "security-test-session";
1010 const OTHER_TOKEN: &str = "security-test-other-session";
1011 const CSRF: &str = "security-test-csrf";
1012 const PASSWORD: &str = "current password 1";
1013
1014 struct Fixture {
1015 router: Router,
1016 state: AppState,
1017 user: User,
1018 _dir: tempfile::TempDir,
1019 }
1020
1021 async fn fixture() -> Fixture {
1022 let dir = tempfile::tempdir().unwrap();
1023 let state = crate::test_support::test_state(dir.path()).await;
1024 let hash = hash_password_async(PASSWORD.into()).await.unwrap();
1025 let user = state
1026 .store
1027 .create_user("tahinli", None, &hash, false)
1028 .await
1029 .unwrap();
1030 crate::test_support::create_session(&state.store, &user.id, TOKEN, CSRF).await;
1031 let router = crate::test_support::app_router(state.clone());
1032 Fixture {
1033 router,
1034 state,
1035 user,
1036 _dir: dir,
1037 }
1038 }
1039
1040 struct Reply {
1041 status: u16,
1042 location: Option<String>,
1043 body: String,
1044 }
1045
1046 async fn send(router: &Router, method: &str, uri: &str, signed_in: bool, form: &str) -> Reply {
1047 let mut builder = Request::builder().method(method).uri(uri);
1048 if signed_in {
1049 builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={TOKEN}"));
1050 }
1051 if method == "POST" {
1052 builder = builder.header("content-type", "application/x-www-form-urlencoded");
1053 }
1054 let res = router
1055 .handle(builder.body(Body::from(form.to_owned())).unwrap())
1056 .await;
1057 let status = res.status().as_u16();
1058 let location = res
1059 .headers()
1060 .get("location")
1061 .and_then(|v| v.to_str().ok())
1062 .map(str::to_owned);
1063 let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
1064 Reply {
1065 status,
1066 location,
1067 body: String::from_utf8_lossy(&bytes).into_owned(),
1068 }
1069 }
1070
1071 fn now_code(shared: &[u8]) -> String {
1072 totp::code_at(shared, totp::step_for(forge_core::time::now_unix()))
1073 }
1074
1075 async fn enable_totp_directly(fx: &Fixture) -> Vec<u8> {
1076 let shared = totp::new_secret();
1077 let sealed = secret::seal(&fx.state.key, &shared).unwrap();
1078 fx.state
1079 .store
1080 .set_totp_secret(&fx.user.id, &sealed)
1081 .await
1082 .unwrap();
1083 fx.state
1084 .store
1085 .enable_totp(&fx.user.id, 0, &[totp::recovery_code_hash("aaaa-bbbb")])
1086 .await
1087 .unwrap();
1088 shared.to_vec()
1089 }
1090
1091 #[tokio::test]
1092 async fn security_page_guards_and_the_first_email_change() {
1093 let fx = fixture().await;
1094 let anon = send(&fx.router, "GET", "/settings/security", false, "").await;
1095 assert_eq!(anon.status, 303, "anonymous page");
1096 assert!(
1097 anon.location.unwrap().starts_with("/login?next="),
1098 "anonymous page"
1099 );
1100
1101 let before = send(&fx.router, "GET", "/settings/security", true, "").await;
1102 assert!(before.body.contains("No email address"), "{}", before.body);
1103
1104 let form = format!(
1105 "csrf=wrong&current_password={PASSWORD}&new_password=a+brand+new+password&confirm_password=a+brand+new+password"
1106 );
1107 let reply = send(
1108 &fx.router,
1109 "POST",
1110 "/settings/security/password",
1111 true,
1112 &form,
1113 )
1114 .await;
1115 assert_eq!(reply.status, 403, "password change without csrf");
1116
1117 let short = format!(
1118 "csrf={CSRF}&current_password={PASSWORD}&new_password=short&confirm_password=short"
1119 );
1120 let reply = send(
1121 &fx.router,
1122 "POST",
1123 "/settings/security/password",
1124 true,
1125 &short,
1126 )
1127 .await;
1128 assert!(
1129 reply.body.contains("at least 12 characters"),
1130 "short password"
1131 );
1132 let mismatch = format!(
1133 "csrf={CSRF}&current_password={PASSWORD}&new_password=a+brand+new+one&confirm_password=a+brand+new+two"
1134 );
1135 let reply = send(
1136 &fx.router,
1137 "POST",
1138 "/settings/security/password",
1139 true,
1140 &mismatch,
1141 )
1142 .await;
1143 assert!(
1144 reply.body.contains("do not match"),
1145 "mismatched confirmation"
1146 );
1147
1148 fx.state
1149 .store
1150 .add_ssh_key(
1151 &fx.user.id,
1152 "laptop",
1153 "ssh-ed25519",
1154 &[1, 2, 3],
1155 "SHA256:test",
1156 )
1157 .await
1158 .unwrap();
1159 crate::signatures::rebuild_allowed_signers(&fx.state)
1160 .await
1161 .unwrap();
1162 let signers = fx.state.config.data_dir.join("run").join("allowed_signers");
1163 let before = std::fs::read_to_string(&signers).unwrap();
1164 assert!(before.starts_with("tahinli "), "{before}");
1165
1166 let wrong = format!("csrf={CSRF}&email=me%40example.com&current_password=nope");
1167 let reply = send(&fx.router, "POST", "/settings/security/email", true, &wrong).await;
1168 assert!(
1169 reply.body.contains("Current password is incorrect."),
1170 "email change with a wrong password"
1171 );
1172 let invalid = format!("csrf={CSRF}&email=not+an+email&current_password={PASSWORD}");
1173 let reply = send(
1174 &fx.router,
1175 "POST",
1176 "/settings/security/email",
1177 true,
1178 &invalid,
1179 )
1180 .await;
1181 assert!(
1182 reply.body.contains("Enter an email address"),
1183 "invalid address"
1184 );
1185 let ok = format!("csrf={CSRF}&email=me%40example.com&current_password={PASSWORD}");
1186 let reply = send(&fx.router, "POST", "/settings/security/email", true, &ok).await;
1187 assert_eq!(
1188 reply.location.as_deref(),
1189 Some("/settings/security?saved=email"),
1190 "valid email change"
1191 );
1192 let fresh = fx
1193 .state
1194 .store
1195 .user_by_id(&fx.user.id)
1196 .await
1197 .unwrap()
1198 .unwrap();
1199 assert_eq!(fresh.email.as_deref(), Some("me@example.com"));
1200 let after = std::fs::read_to_string(&signers).unwrap();
1201 assert!(
1202 after.starts_with("me@example.com "),
1203 "allowed_signers still has the old address: {after}"
1204 );
1205 }
1206
1207 #[tokio::test]
1208 async fn password_change_revokes_other_sessions_and_keeps_this_one() {
1209 let fx = fixture().await;
1210 let expiry = stamp_after(std::time::Duration::from_secs(3600));
1211 fx.state
1212 .store
1213 .create_session(
1214 &fx.user.id,
1215 &hash_token(OTHER_TOKEN),
1216 "other",
1217 &expiry,
1218 None,
1219 None,
1220 )
1221 .await
1222 .unwrap();
1223 let form = format!(
1224 "csrf={CSRF}&current_password={PASSWORD}&new_password=a+brand+new+password&confirm_password=a+brand+new+password"
1225 );
1226 let reply = send(
1227 &fx.router,
1228 "POST",
1229 "/settings/security/password",
1230 true,
1231 &form,
1232 )
1233 .await;
1234 assert_eq!(reply.status, 303);
1235 assert_eq!(
1236 reply.location.as_deref(),
1237 Some("/settings/security?saved=password")
1238 );
1239
1240 let store = &fx.state.store;
1241 assert!(
1242 store
1243 .session_by_token_hash(&hash_token(TOKEN))
1244 .await
1245 .unwrap()
1246 .is_some()
1247 );
1248 assert!(
1249 store
1250 .session_by_token_hash(&hash_token(OTHER_TOKEN))
1251 .await
1252 .unwrap()
1253 .is_none()
1254 );
1255 let fresh = store.user_by_id(&fx.user.id).await.unwrap().unwrap();
1256 assert!(
1257 crate::auth::verify_password_async("a brand new password".into(), fresh.password_hash)
1258 .await
1259 .unwrap()
1260 );
1261 }
1262
1263 #[tokio::test]
1264 async fn wrong_current_passwords_are_refused_and_throttle_the_login() {
1265 let fx = fixture().await;
1266 let bad = format!(
1267 "csrf={CSRF}&current_password=wrong&new_password=a+brand+new+password&confirm_password=a+brand+new+password"
1268 );
1269 for _ in 0..LOGIN_USER_LIMIT {
1270 let reply = send(
1271 &fx.router,
1272 "POST",
1273 "/settings/security/password",
1274 true,
1275 &bad,
1276 )
1277 .await;
1278 assert_eq!(reply.status, 200);
1279 assert!(reply.body.contains("Current password is incorrect."));
1280 }
1281 assert!(
1282 fx.state
1283 .throttle
1284 .check(
1285 &user_key("tahinli"),
1286 LOGIN_USER_LIMIT,
1287 std::time::Instant::now()
1288 )
1289 .is_some()
1290 );
1291 let blocked = send(
1292 &fx.router,
1293 "POST",
1294 "/settings/security/password",
1295 true,
1296 &bad,
1297 )
1298 .await;
1299 assert_eq!(blocked.status, 429);
1300 assert!(blocked.body.contains("Too many attempts"));
1301
1302 let fresh = fx
1303 .state
1304 .store
1305 .user_by_id(&fx.user.id)
1306 .await
1307 .unwrap()
1308 .unwrap();
1309 assert!(
1310 crate::auth::verify_password_async(PASSWORD.into(), fresh.password_hash)
1311 .await
1312 .unwrap()
1313 );
1314 }
1315
1316 #[tokio::test]
1317 async fn email_row_follows_the_address_from_queued_to_verified() {
1318 let fx = fixture().await;
1319 fx.state
1320 .store
1321 .set_email(&fx.user.id, "tahinli@example.com")
1322 .await
1323 .unwrap();
1324 let mail = forge_core::mail::OutgoingMail {
1325 to: "tahinli@example.com".into(),
1326 subject: "Verify your address".into(),
1327 body: "Open the link to verify.".into(),
1328 message_id: None,
1329 in_reply_to: None,
1330 kind: forge_core::mail::MailKind::Verification,
1331 user_id: Some(fx.user.id.clone()),
1332 };
1333 fx.state
1334 .store
1335 .enqueue_mail("verify:security-test", &mail)
1336 .await
1337 .unwrap();
1338 let page = send(&fx.router, "GET", "/settings/security", true, "").await;
1339 assert_eq!(page.status, 200);
1340 assert!(
1341 page.body
1342 .contains("tahinli@example.com</span> · Not verified · verification mail queued"),
1343 "{}",
1344 page.body
1345 );
1346
1347 let token = fx
1348 .state
1349 .store
1350 .create_verify_token(&fx.user.id, "tahinli@example.com")
1351 .await
1352 .unwrap();
1353 assert!(
1354 fx.state
1355 .store
1356 .redeem_verify_token(&token)
1357 .await
1358 .unwrap()
1359 .is_some()
1360 );
1361 let page = send(&fx.router, "GET", "/settings/security", true, "").await;
1362 assert_eq!(page.status, 200);
1363 assert!(
1364 page.body.contains("tahinli@example.com</span> · Verified"),
1365 "{}",
1366 page.body
1367 );
1368 }
1369
1370 #[tokio::test]
1371 async fn two_factor_enrollment_and_turn_off() {
1372 let fx = fixture().await;
1373 let enable = format!("csrf={CSRF}");
1374 let reply = send(
1375 &fx.router,
1376 "POST",
1377 "/settings/security/2fa/enable",
1378 true,
1379 &enable,
1380 )
1381 .await;
1382 assert_eq!(reply.status, 303, "enable");
1383 let pending = fx
1384 .state
1385 .store
1386 .totp_state(&fx.user.id)
1387 .await
1388 .unwrap()
1389 .unwrap();
1390 assert!(!pending.enabled);
1391 let sealed = pending.sealed_secret.expect("secret stored");
1392 let shared = secret::open(&fx.state.key, &sealed).unwrap();
1393
1394 let page = send(&fx.router, "GET", "/settings/security", true, "").await;
1395 assert!(
1396 page.body.contains(&totp::base32_encode(&shared)),
1397 "secret shown"
1398 );
1399 assert!(
1400 page.body.contains("otpauth://totp/forge:tahinli?secret="),
1401 "uri shown"
1402 );
1403
1404 let wrong = format!("csrf={CSRF}&code=000000");
1405 let reply = send(
1406 &fx.router,
1407 "POST",
1408 "/settings/security/2fa/confirm",
1409 true,
1410 &wrong,
1411 )
1412 .await;
1413 assert_eq!(reply.status, 200);
1414 assert!(reply.body.contains("That code is not right"), "wrong code");
1415 let state = fx
1416 .state
1417 .store
1418 .totp_state(&fx.user.id)
1419 .await
1420 .unwrap()
1421 .unwrap();
1422 assert!(!state.enabled, "wrong code does not enable");
1423 assert!(state.sealed_secret.is_some(), "wrong code keeps the secret");
1424
1425 let too_long = format!(
1426 "csrf={CSRF}&code={}&name={}",
1427 now_code(&shared),
1428 "x".repeat(41)
1429 );
1430 let reply = send(
1431 &fx.router,
1432 "POST",
1433 "/settings/security/2fa/confirm",
1434 true,
1435 &too_long,
1436 )
1437 .await;
1438 assert!(reply.body.contains("at most 40 characters"), "long name");
1439 assert!(
1440 !fx.state
1441 .store
1442 .totp_state(&fx.user.id)
1443 .await
1444 .unwrap()
1445 .unwrap()
1446 .enabled,
1447 "long name does not enable"
1448 );
1449
1450 let ok = format!("csrf={CSRF}&code={}&name=Work+phone", now_code(&shared));
1451 let reply = send(
1452 &fx.router,
1453 "POST",
1454 "/settings/security/2fa/confirm",
1455 true,
1456 &ok,
1457 )
1458 .await;
1459 assert_eq!(reply.status, 200);
1460 assert!(reply.body.contains("Recovery codes"), "codes shown");
1461 let codes = reply
1462 .body
1463 .split("<code>")
1464 .skip(1)
1465 .filter_map(|chunk| chunk.split("</code>").next())
1466 .filter(|code| code.len() == 9 && code.as_bytes()[4] == b'-')
1467 .count();
1468 assert_eq!(codes, super::RECOVERY_CODE_COUNT, "recovery codes shown");
1469 let on = fx
1470 .state
1471 .store
1472 .totp_state(&fx.user.id)
1473 .await
1474 .unwrap()
1475 .unwrap();
1476 assert!(on.enabled);
1477 assert_eq!(on.name.as_deref(), Some("Work phone"));
1478 assert!(on.created_at.is_some());
1479 assert!(on.last_used_at.is_some());
1480 assert_eq!(
1481 fx.state
1482 .store
1483 .unused_recovery_codes(&fx.user.id)
1484 .await
1485 .unwrap(),
1486 super::RECOVERY_CODE_COUNT as u64
1487 );
1488 let page = send(&fx.router, "GET", "/settings/security", true, "").await;
1489 assert!(page.body.contains("Work phone"), "device name shown");
1490
1491 let no_password = format!(
1492 "csrf={CSRF}&current_password=nope&code={}",
1493 now_code(&shared)
1494 );
1495 let reply = send(
1496 &fx.router,
1497 "POST",
1498 "/settings/security/2fa/disable",
1499 true,
1500 &no_password,
1501 )
1502 .await;
1503 assert!(
1504 reply.body.contains("Current password is incorrect."),
1505 "turn off with a wrong password"
1506 );
1507 assert!(
1508 fx.state
1509 .store
1510 .totp_state(&fx.user.id)
1511 .await
1512 .unwrap()
1513 .unwrap()
1514 .enabled
1515 );
1516
1517 let next = totp::code_at(&shared, totp::step_for(forge_core::time::now_unix()) + 1);
1518 let disable = format!("csrf={CSRF}&current_password={PASSWORD}&code={next}");
1519 let reply = send(
1520 &fx.router,
1521 "POST",
1522 "/settings/security/2fa/disable",
1523 true,
1524 &disable,
1525 )
1526 .await;
1527 assert_eq!(
1528 reply.location.as_deref(),
1529 Some("/settings/security?saved=2fa-off"),
1530 "turn off"
1531 );
1532 let off = fx
1533 .state
1534 .store
1535 .totp_state(&fx.user.id)
1536 .await
1537 .unwrap()
1538 .unwrap();
1539 assert!(!off.enabled);
1540 assert_eq!(off.sealed_secret, None);
1541 }
1542
1543 #[tokio::test]
1544 async fn enabled_account_shows_the_device_and_guards_its_panels() {
1545 let fx = fixture().await;
1546 let shared = enable_totp_directly(&fx).await;
1547 let page = send(&fx.router, "GET", "/settings/security", true, "").await;
1548 assert_eq!(page.status, 200);
1549 assert!(page.body.contains("Authenticator app"));
1550 assert!(page.body.contains("Added "), "{}", page.body);
1551 assert!(page.body.contains("1 of 10 recovery codes unused"));
1552 assert!(page.body.contains("Running low"));
1553 assert!(
1554 page.body.contains("<p class=\"state\">On · "),
1555 "{}",
1556 page.body
1557 );
1558
1559 let bad = format!(
1560 "csrf={CSRF}&current_password=nope&code={}",
1561 now_code(&shared)
1562 );
1563 let reply = send(
1564 &fx.router,
1565 "POST",
1566 "/settings/security/2fa/disable",
1567 true,
1568 &bad,
1569 )
1570 .await;
1571 assert!(reply.body.contains("Current password is incorrect."));
1572 let (_, opened) = reply
1573 .body
1574 .split_once("<details class=\"reveal\" open")
1575 .expect("turn-off panel should stay open");
1576 assert!(
1577 opened.contains("Turn off")
1578 && opened.split("<details").next().is_some_and(
1579 |panel| panel.contains("action=\"/settings/security/2fa/disable\"")
1580 ),
1581 "the open panel should be the turn-off form: {opened}"
1582 );
1583 assert!(
1584 !opened.contains("<details class=\"reveal\" open"),
1585 "only the turn-off panel should be open"
1586 );
1587
1588 let bad_code = format!("csrf={CSRF}&current_password={PASSWORD}&code=123456x");
1589 let reply = send(
1590 &fx.router,
1591 "POST",
1592 "/settings/security/2fa/recovery",
1593 true,
1594 &bad_code,
1595 )
1596 .await;
1597 assert!(reply.body.contains("That code is not right"), "bad code");
1598 assert_eq!(
1599 fx.state
1600 .store
1601 .unused_recovery_codes(&fx.user.id)
1602 .await
1603 .unwrap(),
1604 1,
1605 "a refused code leaves the old codes"
1606 );
1607
1608 let good = format!(
1609 "csrf={CSRF}&current_password={PASSWORD}&code={}",
1610 now_code(&shared)
1611 );
1612 let reply = send(
1613 &fx.router,
1614 "POST",
1615 "/settings/security/2fa/recovery",
1616 true,
1617 &good,
1618 )
1619 .await;
1620 assert!(reply.body.contains("Recovery codes"), "new codes shown");
1621 assert_eq!(
1622 fx.state
1623 .store
1624 .unused_recovery_codes(&fx.user.id)
1625 .await
1626 .unwrap(),
1627 super::RECOVERY_CODE_COUNT as u64
1628 );
1629 assert!(
1630 !fx.state
1631 .store
1632 .consume_recovery_code(&fx.user.id, &totp::recovery_code_hash("aaaa-bbbb"))
1633 .await
1634 .unwrap(),
1635 "the old recovery code is gone"
1636 );
1637 }
1638}