forge
Explore
Log in

Don't you dare go Hollow

im_old

Clone
★ 0

0 watching0 forksRustGPL-3.0755.6 KiB84318dcTahinli2 months ago77 commits

auth.rs742 lines, 28.8 KiBHistoryRawDownload
1//! The form handlers behind the pages. Every one answers a plain 303: the
2//! page it lands on reads `?error=` / `?ok=` back on render — im serves no
3//! client-side script, so there is no action value to answer with.
4
5use im_core::accounts::{self, AccountError};
6use im_core::model::UserId;
7use serde::Deserialize;
8use topcoat::Result;
9use topcoat::context::Cx;
10use topcoat::router::content::Form;
11use topcoat::router::response::IntoResponse as _;
12use topcoat::router::{HeaderName, StatusCode, header, route};
13
14use crate::server::{self, PendingPurpose};
15
16pub(crate) type Redirect = Result<(StatusCode, [(HeaderName, String); 1])>;
17
18pub(crate) fn see(location: String) -> Redirect {
19 Ok((StatusCode::SEE_OTHER, [(header::LOCATION, location)]))
20}
21
22/// Percent-encodes a value for a query pair. The `back` a login carries is
23/// always a local `/authorize?...` URL, which is full of `?&=` of its own.
24fn urlencode(raw: &str) -> String {
25 let mut out = String::with_capacity(raw.len());
26 for byte in raw.bytes() {
27 match byte {
28 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
29 out.push(byte as char)
30 }
31 _ => out.push_str(&format!("%{byte:02X}")),
32 }
33 }
34 out
35}
36
37/// A `back` worth honoring: a local absolute path, never `//elsewhere` —
38/// and never a backslash, which browsers normalize like a slash, so
39/// `/\evil.com` would ride the guard out to a foreign host. Anything
40/// else — including a full URL — becomes the front door.
41fn safe_back(raw: &str) -> &str {
42 if raw.starts_with('/') && !raw.starts_with("//") && !raw.contains('\\') {
43 raw
44 } else {
45 "/"
46 }
47}
48
49/// Where a logout sends the browser. A local absolute path always
50/// qualifies — the login `back` rule. An absolute URL qualifies when its
51/// origin is exactly one of the family's stored services': the sibling app
52/// that sent the browser here gets it handed back. A foreign origin — and
53/// anything unparseable — is refused to the front door.
54fn logout_target(raw: Option<&str>, services: &[im_core::services::Service]) -> String {
55 let Some(raw) = raw else {
56 return "/".to_string();
57 };
58 if raw.starts_with('/') && !raw.starts_with("//") && !raw.contains('\\') {
59 // The backslash rule is [`safe_back`]'s: browsers normalize
60 // `/\evil.com` into a foreign navigation.
61 return raw.to_string();
62 }
63 if let Some(origin) = url_origin(raw)
64 && services
65 .iter()
66 .any(|s| url_origin(&s.url).is_some_and(|known| known == origin))
67 {
68 return raw.to_string();
69 }
70 "/".to_string()
71}
72
73/// The `scheme://authority` of an absolute http(s) URL, lowercased — the
74/// whole of what an origin match compares. `None` for anything else.
75fn url_origin(raw: &str) -> Option<String> {
76 let (scheme, rest) = raw.split_once("://")?;
77 if !scheme.eq_ignore_ascii_case("http") && !scheme.eq_ignore_ascii_case("https") {
78 return None;
79 }
80 let authority = rest.split(['/', '?', '#']).next()?;
81 if authority.is_empty() {
82 return None;
83 }
84 Some(format!(
85 "{}://{}",
86 scheme.to_ascii_lowercase(),
87 authority.to_ascii_lowercase()
88 ))
89}
90
91/// Creation-time facts for the session row: the address the browser came
92/// through and the agent it claims to be. The address is the family's shared
93/// [`server::client_label`], with `unknown` folded back to none so the
94/// sessions list keeps its dash.
95fn session_meta(cx: &Cx) -> im_core::sessions::SessionMeta {
96 let headers = topcoat::router::request::headers(cx);
97 let label = server::client_label(cx);
98 let ip = (label != "unknown").then_some(label);
99 let agent = headers
100 .get("user-agent")
101 .and_then(|value| value.to_str().ok())
102 .map(|value| value.chars().take(255).collect::<String>());
103 im_core::sessions::SessionMeta { ip, agent }
104}
105
106#[derive(Deserialize)]
107pub struct LoginForm {
108 email: String,
109 password: String,
110 #[serde(default)]
111 back: Option<String>,
112}
113
114#[route(POST "/login")]
115async fn login(cx: &Cx, Form(input): Form<LoginForm>) -> Redirect {
116 let back = safe_back(input.back.as_deref().unwrap_or("/")).to_string();
117 let store = &server::app(cx).store;
118 // The door stops listening after the panel's per-hour allowance of
119 // failures. The refusal says nothing about which step refused, as always.
120 let key = input.email.trim().to_lowercase();
121 if accounts::login_blocked(store, &key).await? {
122 server::log_event(cx, "login_limited", Some(&key), None).await;
123 return see(format!(
124 "/login?error=rate_limited&back={}",
125 urlencode(&back)
126 ));
127 }
128 match accounts::verify_login(store, &input.email, &input.password).await {
129 Ok(user) if user.totp_confirmed => {
130 let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Login, back).await;
131 server::set_pending_cookie(cx, sealed).await;
132 let _ = accounts::clear_login_failures(store, &key).await;
133 see("/login/totp".to_string())
134 }
135 Ok(user) => {
136 let _ = accounts::clear_login_failures(store, &key).await;
137 let token =
138 im_core::sessions::create_session(store, &user.id, &session_meta(cx)).await?;
139 server::set_session_cookie(cx, token.expose());
140 server::log_event(cx, "login_ok", Some(&user.email), None).await;
141 see(back)
142 }
143 Err(_) => {
144 // The failure is logged against the address tried, never the
145 // password — and never whether the address exists.
146 let _ = accounts::record_login_failure(store, &key).await;
147 server::log_event(cx, "login_fail", Some(&input.email), None).await;
148 see(format!("/login?error=bad_login&back={}", urlencode(&back)))
149 }
150 }
151}
152
153#[derive(Deserialize)]
154pub struct TotpForm {
155 code: String,
156}
157
158#[route(POST "/login/totp")]
159async fn login_totp(cx: &Cx, Form(input): Form<TotpForm>) -> Redirect {
160 let Some(pending) = server::opened_pending(cx) else {
161 return see("/login".to_string());
162 };
163 if pending.purpose != PendingPurpose::Login {
164 return see("/login".to_string());
165 }
166 let store = &server::app(cx).store;
167 let user_id = UserId::from(pending.user.clone());
168 let ok = match accounts::user_by_id(store, &user_id).await? {
169 Some(user) => match im_core::totp::totp_secret(store, &user.id).await? {
170 Some((secret, confirmed)) => {
171 // `consume_totp`, not a bare verify: the accepted timestep
172 // is burned atomically, so a code cannot mint a second
173 // session inside its drift window.
174 confirmed
175 && im_core::totp::consume_totp(
176 store,
177 &user.id,
178 &secret,
179 input.code.trim(),
180 time::OffsetDateTime::now_utc(),
181 )
182 .await?
183 }
184 None => false,
185 },
186 None => false,
187 };
188 // The second factor gets the same ceiling as the first, keyed on the
189 // account, so an attacker past the password cannot grind codes either.
190 let totp_key = format!("totp:{}", pending.user);
191 if accounts::login_blocked(store, &totp_key).await? {
192 server::log_event(cx, "login_limited", None, Some("2fa")).await;
193 server::clear_pending_cookie(cx);
194 return see("/login?error=rate_limited".to_string());
195 }
196 if !ok {
197 let _ = accounts::record_login_failure(store, &totp_key).await;
198 server::log_event(cx, "totp_fail", None, Some("login")).await;
199 return see("/login/totp?error=bad_code".to_string());
200 }
201 let _ = accounts::clear_login_failures(store, &totp_key).await;
202 let token = im_core::sessions::create_session(store, &user_id, &session_meta(cx)).await?;
203 let email = accounts::user_by_id(store, &user_id)
204 .await?
205 .map(|u| u.email);
206 server::log_event(cx, "login_ok", email.as_deref(), Some("2fa")).await;
207 server::clear_pending_cookie(cx);
208 server::set_session_cookie(cx, token.expose());
209 see(pending.back)
210}
211
212#[derive(Deserialize)]
213pub struct InviteForm {
214 token: String,
215 name: String,
216 password: String,
217 password_confirm: String,
218}
219
220#[route(POST "/invite")]
221async fn invite(cx: &Cx, Form(input): Form<InviteForm>) -> Redirect {
222 if input.password != input.password_confirm {
223 return see(format!("/invite/{}?error=passwords_differ", input.token));
224 }
225 let store = &server::app(cx).store;
226 let user = match accounts::create_user_from_invite(
227 store,
228 &input.token,
229 input.name.trim(),
230 &input.password,
231 )
232 .await
233 {
234 Ok(user) => user,
235 Err(problem) => {
236 let code = match problem {
237 AccountError::InviteInvalid => "invite_invalid",
238 AccountError::InviteExpired => "invite_expired",
239 AccountError::InviteSpent => "invite_spent",
240 AccountError::EmailTaken => "email_taken",
241 AccountError::Password(im_core::accounts::PasswordProblem::TooShort) => {
242 "password_too_short"
243 }
244 AccountError::Password(im_core::accounts::PasswordProblem::LooksLikeYou) => {
245 "password_personal"
246 }
247 _ => {
248 return Err(topcoat::Error::from(std::io::Error::other(
249 problem.to_string(),
250 )));
251 }
252 };
253 return see(format!("/invite/{}?error={code}", input.token));
254 }
255 };
256 let token = im_core::sessions::create_session(store, &user.id, &session_meta(cx)).await?;
257 server::log_event(cx, "invite_accepted", Some(&user.email), None).await;
258 // A member exists from this moment on: the roster — and every app
259 // mirroring it — learns the new row now, not on their next full list.
260 server::notify_profile(cx, &user.id).await;
261 server::set_session_cookie(cx, token.expose());
262 see("/".to_string())
263}
264
265#[route(POST "/enroll")]
266async fn enroll(cx: &Cx, Form(input): Form<TotpForm>) -> Redirect {
267 let Some(user) = server::current_user(cx).await else {
268 return see("/login".to_string());
269 };
270 if user.totp_confirmed {
271 return see("/".to_string());
272 }
273 let store = &server::app(cx).store;
274 let Some((secret, _)) = im_core::totp::totp_secret(store, &user.id).await? else {
275 return see("/enroll".to_string());
276 };
277 // The proving code burns its timestep too — the same replay rule the
278 // login enforces, applied at the moment TOTP turns on.
279 if !im_core::totp::consume_totp(
280 store,
281 &user.id,
282 &secret,
283 input.code.trim(),
284 time::OffsetDateTime::now_utc(),
285 )
286 .await?
287 {
288 return see("/enroll?error=bad_code".to_string());
289 }
290 im_core::totp::confirm_totp(store, &user.id).await?;
291 let email = accounts::user_by_id(store, &user.id)
292 .await?
293 .map(|u| u.email);
294 server::log_event(cx, "enrolled", email.as_deref(), None).await;
295 see("/?ok=enrolled".to_string())
296}
297
298/// "Sign out everywhere": the central session dies, and with it every
299/// refresh token any app is still holding — see `sessions::revoke_session`.
300#[route(POST "/logout")]
301async fn logout(cx: &Cx) -> Redirect {
302 sign_out_everywhere(cx).await?;
303 see("/".to_string())
304}
305
306/// The shared half of both logouts: the central session dies — with it
307/// every refresh token and app session bound to it — and the cookie is
308/// tidied. Where the browser goes next is each route's own business.
309async fn sign_out_everywhere(cx: &Cx) -> Result<()> {
310 if let Some(token) = server::presented_session(cx) {
311 let user = im_core::sessions::resolve_session(&server::app(cx).store, &token)
312 .await?
313 .map(|u| (u.id, u.email));
314 im_core::sessions::revoke_session(&server::app(cx).store, &token).await?;
315 // The eviction news is addressed to the dying session's own
316 // connection, so its tab leaves at once instead of at the next
317 // full refetch.
318 if let Some((id, _)) = &user {
319 server::note_revoked(cx, id.as_str(), Some(&im_core::accounts::hash_token(&token)))
320 .await;
321 }
322 server::log_event(
323 cx,
324 "logout",
325 user.as_ref().map(|(_, email)| email.as_str()),
326 None,
327 )
328 .await;
329 }
330 server::clear_session_cookie(cx);
331 Ok(())
332}
333
334/// The RP-initiated exit: a sibling app has cleared its own cookie and
335/// sent the browser here as a top-level navigation. `back` names the
336/// return address, judged by [`logout_target`] — and the central session
337/// dies whatever the answer is.
338#[route(GET "/logout")]
339async fn logout_return(cx: &Cx) -> Redirect {
340 let query = topcoat::router::request::uri(cx)
341 .query()
342 .unwrap_or("")
343 .to_string();
344 let back = crate::pages::query_value(&query, "back");
345 sign_out_everywhere(cx).await?;
346 let services = im_core::services::list(&server::app(cx).store).await?;
347 see(logout_target(back.as_deref(), &services))
348}
349
350/// The signed-in probe behind the live channel's error path: a tab whose
351/// stream died asks here whether its session still stands, and the bare
352/// status — no HTML, no redirect — is the whole answer. 204 signed in,
353/// 401 not.
354#[route(GET "/api/me")]
355async fn me_probe(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> {
356 if server::current_user(cx).await.is_some() {
357 (StatusCode::NO_CONTENT, "").into_response(cx)
358 } else {
359 (StatusCode::UNAUTHORIZED, "").into_response(cx)
360 }
361}
362
363#[derive(Deserialize)]
364pub struct ForgotForm {
365 email: String,
366}
367
368/// The self-serve reset ask. It answers every address the same — the mail
369/// either exists or it doesn't, and the page never says which. Each ask
370/// retires the address's previous live link: the newest mail is the only
371/// door. The asks themselves carry the login limiter's per-hour ceiling,
372/// keyed on the address, so a stranger cannot turn the form into a
373/// mail-bomb — and a throttled ask still answers exactly like a sent one.
374#[route(POST "/forgot")]
375async fn forgot(cx: &Cx, Form(input): Form<ForgotForm>) -> Redirect {
376 let store = &server::app(cx).store;
377 let email = input.email.trim().to_string();
378 let key = format!("forgot:{}", email.to_lowercase());
379 if accounts::login_blocked(store, &key).await? {
380 server::log_event(cx, "forgot_limited", Some(&email), None).await;
381 return see("/forgot?ok=sent".to_string());
382 }
383 // Every ask spends from the same budget, account or not — the mails
384 // are the thing being rationed, and existence is never the answer.
385 let _ = accounts::record_login_failure(store, &key).await;
386 if let Some(token) = accounts::create_reset(store, &email).await? {
387 let issuer = server::app(cx).config.issuer.clone();
388 // The mail follows the account's language; a missing account still
389 // answers identically, in English.
390 let lang = accounts::user_by_email(store, &email)
391 .await?
392 .map(|user| crate::i18n::Lang::from_code(&user.language))
393 .unwrap_or(crate::i18n::Lang::En);
394 if crate::mailer::send_reset(store, &issuer, &email, token.expose(), lang)
395 .await
396 .is_ok()
397 {
398 server::log_event(cx, "reset_sent", Some(&email), None).await;
399 }
400 }
401 see("/forgot?ok=sent".to_string())
402}
403
404#[derive(Deserialize)]
405pub struct ResetForm {
406 token: String,
407 password: String,
408 password_confirm: String,
409}
410
411/// Redeems a reset link: new password in, every session out. A dead link is
412/// sent back to the ask — the form it came from is gone with it.
413#[route(POST "/reset")]
414async fn reset(cx: &Cx, Form(input): Form<ResetForm>) -> Redirect {
415 if input.password != input.password_confirm {
416 return see(format!("/reset/{}?error=passwords_differ", input.token));
417 }
418 let store = &server::app(cx).store;
419 match accounts::redeem_reset(store, &input.token, &input.password).await {
420 Ok(user) => {
421 // redeem_reset swept every session of theirs inside the core;
422 // their tabs hear the eviction here.
423 server::note_revoked(cx, user.id.as_str(), None).await;
424 server::log_event(cx, "password_reset", Some(&user.email), None).await;
425 see("/login?ok=reset".to_string())
426 }
427 Err(AccountError::Password(problem)) => {
428 let code = match problem {
429 im_core::accounts::PasswordProblem::TooShort => "password_too_short",
430 im_core::accounts::PasswordProblem::LooksLikeYou => "password_personal",
431 _ => "passwords_differ",
432 };
433 see(format!("/reset/{}?error={code}", input.token))
434 }
435 Err(AccountError::ResetInvalid) => see("/forgot?error=reset_invalid".to_string()),
436 Err(e) => Err(topcoat::Error::from(std::io::Error::other(e.to_string()))),
437 }
438}
439
440#[derive(Deserialize)]
441struct EmailChangeForm {
442 email: String,
443}
444
445/// The landing's address change: one ask, two mails — the old address must
446/// agree to let the account go and the new one to take it on. Without a
447/// sender configured the two links come back on the redirect once — the
448/// crate's unmailed idiom, and the requester is the only person who needs
449/// them.
450#[route(POST "/email_change")]
451async fn email_change(cx: &Cx, Form(input): Form<EmailChangeForm>) -> Redirect {
452 let Some(me) = server::current_user(cx).await else {
453 return see("/".to_string());
454 };
455 let store = &server::app(cx).store;
456 let (old_token, new_token) =
457 match accounts::request_email_change(store, &me.id, &input.email).await {
458 Ok(pair) => pair,
459 Err(AccountError::InvalidEmail) => {
460 return see("/?section=password&error=bad_email".to_string());
461 }
462 Err(AccountError::SameEmail) => {
463 return see("/?section=password&error=same_email".to_string());
464 }
465 Err(AccountError::EmailTaken) => {
466 return see("/?section=password&error=email_taken".to_string());
467 }
468 Err(e) => return Err(topcoat::Error::from(std::io::Error::other(e.to_string()))),
469 };
470 let issuer = server::app(cx).config.issuer.clone();
471 // Both mails follow the account's own language.
472 let lang = crate::i18n::Lang::from_code(&me.language);
473 let old_mailed = crate::mailer::send_email_change(
474 store,
475 &issuer,
476 &me.email,
477 old_token.expose(),
478 lang,
479 false,
480 )
481 .await
482 .is_ok();
483 let new_mailed = crate::mailer::send_email_change(
484 store,
485 &issuer,
486 input.email.trim(),
487 new_token.expose(),
488 lang,
489 true,
490 )
491 .await
492 .is_ok();
493 server::log_event(
494 cx,
495 "email_change_asked",
496 Some(&me.email),
497 Some(input.email.trim().to_lowercase()).as_deref(),
498 )
499 .await;
500 if old_mailed && new_mailed {
501 see("/?section=password&ok=email_change_asked".to_string())
502 } else {
503 let links = format!(
504 "{issuer}/email/{} {issuer}/email/{}",
505 old_token.expose(),
506 new_token.expose()
507 );
508 see(format!(
509 "/?section=password&ok=email_change_asked&links={}",
510 crate::oidc::urlencode(&links)
511 ))
512 }
513}
514
515#[derive(Deserialize)]
516struct EmailConfirmForm {
517 token: String,
518}
519
520/// A confirmation link's POST — the click that counts. The first mailbox
521/// to agree only marks its side; the second applies the change. Signed-out
522/// viewers may confirm, because holding the mailbox is the proof; each
523/// lands where their state says, a session on the landing and everyone
524/// else at the front door.
525#[route(POST "/email")]
526async fn email_confirm(cx: &Cx, Form(input): Form<EmailConfirmForm>) -> Redirect {
527 let store = &server::app(cx).store;
528 match accounts::confirm_email_change(store, &input.token).await {
529 Ok(accounts::EmailChangeConfirmed::Applied(user)) => {
530 server::log_event(cx, "email_changed", Some(&user.email), None).await;
531 // Both mailboxes agreed and the address is rewritten: the
532 // roster's row moved with it.
533 server::notify_profile(cx, &user.id).await;
534 if server::current_user(cx).await.is_some() {
535 see("/?section=profile&ok=email_changed".to_string())
536 } else {
537 see("/login?ok=email_changed".to_string())
538 }
539 }
540 Ok(accounts::EmailChangeConfirmed::AwaitOther) => {
541 if server::current_user(cx).await.is_some() {
542 see("/?section=profile&ok=email_half_confirmed".to_string())
543 } else {
544 see("/login?ok=email_half_confirmed".to_string())
545 }
546 }
547 Err(AccountError::EmailTaken) => see("/login?error=email_taken".to_string()),
548 Err(AccountError::EmailChangeInvalid) => {
549 see("/login?error=email_change_invalid".to_string())
550 }
551 Err(e) => Err(topcoat::Error::from(std::io::Error::other(e.to_string()))),
552 }
553}
554#[derive(Deserialize)]
555struct SessionRevokeForm {
556 session: String,
557}
558
559/// Revokes one of the signer's own sessions. The current one signs this
560/// browser out — the server row dies and the cookie is tidied; any other
561/// just dies where it lives.
562#[route(POST "/sessions/revoke")]
563async fn revoke_session(cx: &Cx, Form(input): Form<SessionRevokeForm>) -> Redirect {
564 let Some(user) = server::current_user(cx).await else {
565 return see("/".to_string());
566 };
567 let store = &server::app(cx).store;
568 if let Some(presented) = server::presented_session(cx)
569 && im_core::accounts::hash_token(&presented) == input.session
570 {
571 im_core::sessions::revoke_session(store, &presented).await?;
572 // The news is addressed to this very session; this tab hears its
573 // own eviction and goes home like any other.
574 server::note_revoked(cx, user.id.as_str(), Some(&input.session)).await;
575 server::clear_session_cookie(cx);
576 return see("/".to_string());
577 }
578 // The row's address, when it is still there, is the useful half of the
579 // log line — which of their devices they just killed.
580 let ip = im_core::sessions::list_sessions(store, &user.id)
581 .await?
582 .into_iter()
583 .find(|s| s.token_hash == input.session)
584 .and_then(|s| s.ip);
585 if !im_core::sessions::revoke_owned_session(store, &user.id, &input.session).await? {
586 return see("/?section=sessions&error=session_unknown".to_string());
587 }
588 server::note_revoked(cx, user.id.as_str(), Some(&input.session)).await;
589 server::log_event(cx, "session_revoked", Some(&user.email), ip.as_deref()).await;
590 see("/?section=sessions&ok=session_revoked".to_string())
591}
592
593#[derive(Deserialize)]
594struct PreferencesForm {
595 theme: Option<String>,
596 ui: Option<String>,
597 language: Option<String>,
598 timezone: Option<String>,
599}
600
601/// The landing's preferences: three selects, validated against the option
602/// lists. Absent or unknown refuses the whole save — nothing half-written —
603/// and the landing reads the refusal back through `pages::error_text`.
604#[route(POST "/preferences")]
605async fn preferences(cx: &Cx, Form(input): Form<PreferencesForm>) -> Redirect {
606 let Some(user) = server::current_user(cx).await else {
607 return see("/".to_string());
608 };
609 let Some(theme) = input.theme.as_deref() else {
610 return see("/?section=preferences&error=bad_theme".to_string());
611 };
612 if theme != "light" && theme != "dark" {
613 return see("/?section=preferences&error=bad_theme".to_string());
614 }
615 let Some(ui) = input.ui.as_deref() else {
616 return see("/?section=preferences&error=bad_ui".to_string());
617 };
618 if ui != "instrument" && ui != "ledger" {
619 return see("/?section=preferences&error=bad_ui".to_string());
620 }
621 let Some(language) = input.language.as_deref() else {
622 return see("/?section=preferences&error=bad_language".to_string());
623 };
624 if language != "en" && language != "tr" {
625 return see("/?section=preferences&error=bad_language".to_string());
626 }
627 let Some(timezone) = input.timezone.as_deref() else {
628 return see("/?section=preferences&error=bad_zone".to_string());
629 };
630 if !crate::pages::zone_options().contains(&timezone.to_string()) {
631 return see("/?section=preferences&error=bad_zone".to_string());
632 }
633 let store = &server::app(cx).store;
634 im_core::accounts::set_preferences(store, &user.id, theme, language, ui, timezone).await?;
635 // The timezone rides the directory: registered siblings apply it live,
636 // the way a name or photo change announces itself.
637 server::notify_profile(cx, &user.id).await;
638 server::log_event(cx, "preferences_saved", Some(&user.email), None).await;
639 see("/?section=preferences&ok=preferences".to_string())
640}
641
642#[derive(Deserialize)]
643struct PasswordForm {
644 current: String,
645 password: String,
646 password_confirm: String,
647}
648
649/// The landing's password pane: the admin panel's account form without the
650/// admin gate — same field names, same refusal codes, and the same courtesy
651/// to the browser holding the form (every other session dies, this one
652/// proved the old password and keeps its own).
653#[route(POST "/password")]
654async fn password(cx: &Cx, Form(input): Form<PasswordForm>) -> Redirect {
655 let Some(me) = server::current_user(cx).await else {
656 return see("/".to_string());
657 };
658 if input.password != input.password_confirm {
659 return see("/?section=password&error=passwords_differ".to_string());
660 }
661 let store = &server::app(cx).store;
662 match im_core::accounts::change_password(store, &me, &input.current, &input.password).await {
663 Ok(()) => {}
664 Err(im_core::accounts::AccountError::Password(problem)) => {
665 use im_core::accounts::PasswordProblem::*;
666 let code = match problem {
667 TooShort => "password_too_short",
668 LooksLikeYou => "password_personal",
669 WrongCurrent => "password_wrong",
670 IsCurrent => "password_same",
671 };
672 return see(format!("/?section=password&error={code}"));
673 }
674 Err(e) => return Err(topcoat::Error::from(std::io::Error::other(e.to_string()))),
675 }
676 if let Some(token) = server::presented_session(cx) {
677 let revoked = im_core::sessions::revoke_user_sessions_except(store, &me.id, &token)
678 .await?;
679 // Each dead session's own tab hears its eviction; the asking
680 // browser's hash is never among them, so this tab stays.
681 for hash in &revoked {
682 server::note_revoked(cx, me.id.as_str(), Some(hash)).await;
683 }
684 }
685 server::log_event(cx, "password_changed", Some(&me.email), None).await;
686 see("/?section=password&ok=password".to_string())
687}
688
689#[cfg(test)]
690mod tests {
691 use super::*;
692
693 #[test]
694 fn back_rejects_scheme_relative_and_backslash_paths() {
695 assert_eq!(safe_back("/dashboard"), "/dashboard");
696 assert_eq!(safe_back("/authorize?client_id=x"), "/authorize?client_id=x");
697 assert_eq!(safe_back("//evil.example/path"), "/");
698 // Browsers normalize the backslash into a slash: `/\evil.example`
699 // navigates off-host exactly like `//evil.example`.
700 assert_eq!(safe_back("/\\evil.example"), "/");
701 assert_eq!(safe_back("/settings\\..\\..\\evil"), "/");
702 assert_eq!(safe_back("https://evil.example"), "/");
703 assert_eq!(safe_back("relative"), "/");
704 }
705
706 #[test]
707 fn logout_target_judges_local_paths_by_the_back_rule() {
708 let services: Vec<im_core::services::Service> = Vec::new();
709 assert_eq!(logout_target(None, &services), "/");
710 assert_eq!(logout_target(Some("/settings"), &services), "/settings");
711 assert_eq!(logout_target(Some("//evil.example"), &services), "/");
712 assert_eq!(logout_target(Some("/\\evil.example"), &services), "/");
713 assert_eq!(
714 logout_target(Some("https://stranger.example/bye"), &services),
715 "/"
716 );
717 }
718
719 #[test]
720 fn logout_target_hands_the_browser_to_a_known_family_service() {
721 let sibling = im_core::services::Service {
722 key: "in".into(),
723 name: "in".into(),
724 url: "https://in.example".into(),
725 owner: None,
726 client_id: None,
727 storage_limit_bytes: None,
728 };
729 let services = vec![sibling];
730 assert_eq!(
731 logout_target(Some("https://in.example/goodbye"), &services),
732 "https://in.example/goodbye"
733 );
734 // A look-alike origin is still a stranger.
735 assert_eq!(
736 logout_target(Some("https://in.example.evil/bye"), &services),
737 "/"
738 );
739 // The local-path rule stands beside the origin rule.
740 assert_eq!(logout_target(Some("/\\in.example"), &services), "/");
741 }
742}