diff --git a/crates/im-web/src/i18n/flows.rs b/crates/im-web/src/i18n/flows.rs index 24ae3f4..5dbf298 100644 --- a/crates/im-web/src/i18n/flows.rs +++ b/crates/im-web/src/i18n/flows.rs @@ -52,8 +52,6 @@ pub enum Flow { EmailChangeQueued, /// Alert: the new address is the current one. EmailChangeSame, - /// Alert: the new address belongs to an account, or cannot be used. - EmailChangeUnavailable, /// Title of the page behind an email-change link. EmailLinkTitle, /// The button that confirms this half. @@ -137,8 +135,6 @@ pub fn text(lang: Lang, key: Flow) -> &'static str { } (Flow::EmailChangeSame, Lang::En) => "That is already the address of your account.", (Flow::EmailChangeSame, Lang::Tr) => "Bu zaten hesabınızın adresi.", - (Flow::EmailChangeUnavailable, Lang::En) => "That address cannot be used.", - (Flow::EmailChangeUnavailable, Lang::Tr) => "Bu adres kullanılamaz.", (Flow::EmailLinkTitle, Lang::En) => "Confirm the email change", (Flow::EmailLinkTitle, Lang::Tr) => "E-posta değişikliğini onaylayın", (Flow::EmailLinkConfirm, Lang::En) => "Confirm", diff --git a/crates/im-web/src/i18n/mail.rs b/crates/im-web/src/i18n/mail.rs index cc47827..fc92f98 100644 --- a/crates/im-web/src/i18n/mail.rs +++ b/crates/im-web/src/i18n/mail.rs @@ -35,6 +35,8 @@ pub enum MailKey { EmailNewAction, /// Subject of the notice that the address changed. EmailDoneSubject, + /// Subject of the notice to the owner of an address that someone tried to use for another account. + EmailTakenSubject, /// Subject: the password was changed by the person. PasswordChangedSubject, /// Body: the password was changed by the person. @@ -100,6 +102,8 @@ pub fn text(lang: Lang, key: MailKey) -> &'static str { (MailKey::EmailNewAction, Lang::Tr) => "Bu adresi onaylayın", (MailKey::EmailDoneSubject, Lang::En) => "The email address of your im account changed", (MailKey::EmailDoneSubject, Lang::Tr) => "im hesabınızın e-posta adresi değişti", + (MailKey::EmailTakenSubject, Lang::En) => "Someone tried to use your email address", + (MailKey::EmailTakenSubject, Lang::Tr) => "Biri e-posta adresinizi kullanmaya çalıştı", (MailKey::PasswordChangedSubject, Lang::En) => "Your im password was changed", (MailKey::PasswordChangedSubject, Lang::Tr) => "im parolanız değiştirildi", (MailKey::PasswordChangedBody, Lang::En) => { @@ -195,6 +199,19 @@ pub fn email_new_body(lang: Lang, hours: u32) -> String { } } +/// The sentence to the owner of an address that someone tried to use for another account, naming the +/// service. Nothing is changed for the owner, and the sentence says so. +pub fn email_taken_body(lang: Lang, issuer: &str) -> String { + match lang { + Lang::En => format!( + "Someone tried to use this address for another account at {issuer}. Your account has not changed, and you do not need to do anything." + ), + Lang::Tr => format!( + "Bu adresi {issuer} üzerinde başka bir hesap için kullanmaya çalışan biri oldu. Hesabınız değişmedi, bir şey yapmanız gerekmiyor." + ), + } +} + /// The sentence that tells both addresses the change happened. pub fn email_done_body(lang: Lang, new_email: &str) -> String { match lang { diff --git a/crates/im-web/src/mail/mod.rs b/crates/im-web/src/mail/mod.rs index 6c20e5c..da0a6f1 100644 --- a/crates/im-web/src/mail/mod.rs +++ b/crates/im-web/src/mail/mod.rs @@ -77,6 +77,11 @@ pub enum Mail<'a> { /// The address the account has now. new_email: &'a str, }, + /// Sent to the owner of an address that someone tried to use for another account. Nothing changed. + EmailTaken { + /// The service's public origin, which names the account the attempt was for. + issuer: &'a str, + }, /// A security notice. Security(Notice), /// A message from an administrator. The subject and the body are the administrator's own words; they @@ -105,6 +110,7 @@ impl Mail<'_> { Mail::EmailOld { .. } => "email_old", Mail::EmailNew { .. } => "email_new", Mail::EmailDone { .. } => "email_done", + Mail::EmailTaken { .. } => "security", Mail::Security(_) => "security", Mail::Notice { .. } => "notice", Mail::Test { .. } => "test", diff --git a/crates/im-web/src/mail/templates.rs b/crates/im-web/src/mail/templates.rs index d4d65c0..5c70fe6 100644 --- a/crates/im-web/src/mail/templates.rs +++ b/crates/im-web/src/mail/templates.rs @@ -4,8 +4,8 @@ use super::{Mail, Notice}; use crate::i18n::Lang; use crate::i18n::mail::{ - MailKey, email_done_body, email_new_body, email_old_body, greeting, invite_body, reset_body, - text, + MailKey, email_done_body, email_new_body, email_old_body, email_taken_body, greeting, + invite_body, reset_body, text, }; /// The rendered subject, plain-text body and HTML body of one mail. @@ -87,6 +87,13 @@ fn parts(lang: Lang, name: Option<&str>, mail: &Mail<'_>) -> Parts { action: None, closing: vec![ignore, signature], }, + Mail::EmailTaken { issuer } => Parts { + subject: key(MailKey::EmailTakenSubject), + greeting, + paragraphs: vec![email_taken_body(lang, issuer)], + action: None, + closing: vec![signature], + }, Mail::Security(notice) => { let (subject, body) = match notice { Notice::PasswordChanged => ( diff --git a/crates/im-web/src/pages/email.rs b/crates/im-web/src/pages/email.rs index 85b9a57..5fc17ed 100644 --- a/crates/im-web/src/pages/email.rs +++ b/crates/im-web/src/pages/email.rs @@ -2,13 +2,15 @@ //! half of it. //! //! The request needs the current password. It sends a link to the current address (with a cancel option) -//! and a link to the new one. The change is applied only when both links have been confirmed, in the store, -//! and the store checks the new address is still free at that moment. A link is never used by a GET: the +//! and a link to the new one. An address that already belongs to an account gets no links: its owner is +//! mailed a notice, and the requester gets the same answer as for a free address. The change is applied only +//! when both links have been confirmed, in the store, and the store checks the new address is still free at +//! that moment. A link is never used by a GET: the //! confirm and cancel buttons are POSTs with the pre-session token. use std::time::{Duration, Instant}; -use im_core::model::AuditAction; +use im_core::model::{AuditAction, User}; use im_core::names::parse_email; use im_core::store::links::EmailConfirm; use im_core::time::stamp_after; @@ -117,26 +119,12 @@ async fn email_request_submit(cx: &Cx, Form(form): Form) -> Re Some(problem), )); } - if state - .store - .user_by_email_folded(&new_email) - .await? - .is_some() - { - let problem = flow_text(lang, Flow::EmailChangeUnavailable).to_owned(); - return Ok(request_view( - cx, - lang, - ViewerInfo::of(&viewer), - csrf, - current, - false, - Some(problem), - )); - } + // An address that belongs to an account gets the same answer and the same count as a free one, so the + // answer does not show who has an account. Its owner learns of the attempt by mail instead. + let taken = state.store.user_by_email_folded(&new_email).await?; - // Counted only for a request that would send mail: the two links are the costly part, and a request the - // store would refuse sends nothing. The limit keeps one account from mailing many addresses. + // Counted for every request that gets this far, free or taken: both send mail, and the count must not + // show which one it was. The limit keeps one account from mailing many addresses. if state .email_changes .reserve( @@ -149,6 +137,11 @@ async fn email_request_submit(cx: &Cx, Form(form): Form) -> Re return Ok(refuse(Txt::ErrEmailChangeLimited)); } + if let Some(owner) = taken { + notify_taken(state, &owner, lang).await; + return Err(see_other("/account/email?notice=sent").into()); + } + let hours = state.policy().email_change_hours; let old_token = generate_token(); let new_token = generate_token(); @@ -189,7 +182,11 @@ async fn email_request_submit(cx: &Cx, Form(form): Form) -> Re .await { Ok(started) => started, - Err(im_core::Error::Conflict(_)) => return Ok(refuse(Txt::ErrEmailInvalid)), + // Taken between the check above and this write: answered as a taken address is, with no link. Its + // owner is not mailed in this rare race. + Err(im_core::Error::Conflict(_)) => { + return Err(see_other("/account/email?notice=sent").into()); + } Err(error) => return Err(error.into()), }; // A change dropped by the limits looks the same to the person as a sent one, as the mail limits @@ -320,6 +317,23 @@ async fn notify_both(state: &AppState, lang: Lang, old_email: &str, new_email: & } } +/// Tells the owner of an address that someone tried to use it for another account. It goes through the +/// same outbox and limits as every mail; a failure is logged and never reaches the requester. +async fn notify_taken(state: &AppState, owner: &User, lang: Lang) { + let issuer = state.config.base_url.as_str(); + match Recipient::new(Some(&owner.name), &owner.email) { + Ok(to) => { + let mail = Mail::EmailTaken { issuer }; + let owner_lang = mail::lang_for(owner, lang); + if let Err(error) = mail::queue(&state.store, &state.key, &to, owner_lang, &mail).await + { + tracing::error!(error = %error, "email taken notice not queued"); + } + } + Err(error) => tracing::error!(error, "email taken notice not queued"), + } +} + /// The request page: the current address, the new address and the password. fn request_view( cx: &Cx, diff --git a/crates/im-web/src/pages/login.rs b/crates/im-web/src/pages/login.rs index 609f5c1..4599bcc 100644 --- a/crates/im-web/src/pages/login.rs +++ b/crates/im-web/src/pages/login.rs @@ -34,7 +34,7 @@ use crate::i18n::account::{Txt, text}; use crate::state::AppState; use crate::throttle::{ LOGIN_AUDIT_LIMIT, LOGIN_IP_LIMIT, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT, ip_key, - login_audit_user_key, two_factor_key, user_key, + login_audit_key, two_factor_key, user_key, }; use crate::views::{alert, field, page_lang, shell}; @@ -135,7 +135,7 @@ async fn login_submit(cx: &Cx, Form(form): Form) -> Result let target_id = found.as_ref().map(|user| user.id.clone()); // The attempt stays counted on every failure below. let Some(user) = found.filter(|user| password_ok && !user.is_disabled()) else { - audit_failed_sign_in(cx, state, target_id).await; + audit_failed_sign_in(cx, state, &email, target_id).await; let lang = page_lang(cx, None); let csrf = pre_csrf_token(cx); return Ok(login_view( @@ -160,7 +160,7 @@ async fn login_submit(cx: &Cx, Form(form): Form) -> Result Some(redirect) => Err(redirect), // The account changed after the password was checked: the sign-in fails like a wrong password. None => { - audit_failed_sign_in(cx, state, target_id).await; + audit_failed_sign_in(cx, state, &email, target_id).await; let lang = page_lang(cx, None); let csrf = pre_csrf_token(cx); Ok(login_view( @@ -176,17 +176,14 @@ async fn login_submit(cx: &Cx, Form(form): Form) -> Result } } -/// Audits a sign-in that failed after the lookup. The row is per account, or per client address when -/// the account is unknown, and at most one each minute, so a flood of failures cannot grow the audit -/// log. The throttle still counts every failure. -async fn audit_failed_sign_in(cx: &Cx, state: &AppState, target_id: Option) { - let audit_key = match &target_id { - Some(id) => login_audit_user_key(id), - None => ip_key("login-audit-ip", client_ip(cx)), - }; +/// Audits a sign-in that failed after the lookup. The row is kept per normalised address, known or not, +/// and at most one each minute, so a flood of failures cannot grow the audit log. The key does not depend +/// on whether the account exists, so a failure does the same work either way (a timing signal otherwise). +/// The throttle still counts every failure. +async fn audit_failed_sign_in(cx: &Cx, state: &AppState, email: &str, target_id: Option) { if state .per_minute - .reserve(&audit_key, LOGIN_AUDIT_LIMIT, Instant::now()) + .reserve(&login_audit_key(email), LOGIN_AUDIT_LIMIT, Instant::now()) .is_ok() { let target = target_id.as_deref().map(|id| ("user", id)); diff --git a/crates/im-web/src/security.rs b/crates/im-web/src/security.rs index 055a943..7eb4b0d 100644 --- a/crates/im-web/src/security.rs +++ b/crates/im-web/src/security.rs @@ -8,8 +8,9 @@ //! //! Cache policy by path: pages (everything that is not a static asset or a photo) are `no-store`, //! so a page with a secret (recovery codes, a TOTP secret) is never kept by a browser or a proxy. -//! Assets set their own long-lived policy. Photos set their own `private` policy and their own CSP -//! (see `pages/photo.rs`), so this layer leaves both alone. +//! Assets set their own long-lived policy. A photo that has its bytes sets its own `private` policy +//! and its own CSP (see `pages/photo.rs`), and this layer leaves both alone. A photo's redirect or +//! error (sign-in, 404) is a page to the browser, so it gets the page headers. use topcoat::context::Cx; use topcoat::router::request::uri; @@ -69,7 +70,8 @@ pub fn headers_for(base_url: &str) -> HeaderMap { pub enum Answer { /// A static file under `/assets/`, with its own cache policy. Asset, - /// A profile photo under `/photo/`, with its own cache policy and its own CSP. + /// A profile photo under `/photo/`. An answer with bytes has its own cache policy and CSP; a redirect or + /// error has the page headers. Photo, /// Public OpenID metadata (discovery and the key set). Not secret, so it may be cached; the handler /// sets the short cache policy. @@ -91,25 +93,20 @@ pub fn answer_for(path: &str) -> Answer { } } -/// Adds the security headers to every response, and `Cache-Control: no-store` to every page. +/// Adds the security headers to every response, and `Cache-Control: no-store` to every page and every +/// photo answer that is not a photo's bytes. /// /// It uses the per-request response headers, which the router applies after the layers have run, -/// so error responses (404, 500) carry them as well. A photo gets the same headers without the -/// page CSP, because the photo handler sends a stricter one of its own. +/// so error responses (404, 500, the sign-in redirect) carry them as well. A header the route set +/// itself is never replaced, so a photo with bytes keeps its own CSP and cache policy. pub struct SecurityHeaders { headers: HeaderMap, - photo_headers: HeaderMap, } impl SecurityHeaders { /// A layer that adds `headers` to every response. pub fn new(headers: HeaderMap) -> Self { - let mut photo_headers = headers.clone(); - photo_headers.remove(header::CONTENT_SECURITY_POLICY); - Self { - headers, - photo_headers, - } + Self { headers } } } @@ -120,19 +117,17 @@ impl Layer for SecurityHeaders { fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { Box::pin(async move { - let answer = answer_for(uri(cx).path()); - let mut headers = match answer { - Answer::Photo => self.photo_headers.clone(), - Answer::Asset | Answer::Public | Answer::Page => self.headers.clone(), - }; - if answer == Answer::Page { + let path = uri(cx).path(); + let answer = answer_for(path); + let mut headers = self.headers.clone(); + if matches!(answer, Answer::Page | Answer::Photo) { headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(NO_STORE)); - if token_path(uri(cx).path()) { - headers.insert( - header::REFERRER_POLICY, - HeaderValue::from_static(NO_REFERRER), - ); - } + } + if answer == Answer::Page && token_path(path) { + headers.insert( + header::REFERRER_POLICY, + HeaderValue::from_static(NO_REFERRER), + ); } match next.run(cx, body).await { // A header the route set itself wins: a token answer that is already `no-store`, or a @@ -184,10 +179,11 @@ mod tests { .expect("request"); let response = crate::boot::router(state.clone()).handle(request).await; let headers = response.headers(); - // A missing photo answers without Cache-Control; a repeat is the bug under test. + // A repeat is the bug under test. A photo redirect (to sign-in) is an error answer, so it + // carries the layer's Cache-Control and CSP once each. let cache_control = headers.get_all(header::CACHE_CONTROL).iter().count(); assert!(cache_control <= 1, "Cache-Control repeated on {path}"); - if path == "/token" { + if path == "/token" || path == "/photo/01HZ" { assert_eq!(cache_control, 1, "Cache-Control on {path}"); } let csp = headers @@ -195,7 +191,7 @@ mod tests { .iter() .count(); assert!(csp <= 1, "CSP repeated on {path}"); - if path == "/token" { + if path == "/token" || path == "/photo/01HZ" { assert_eq!(csp, 1, "CSP on {path}"); } } diff --git a/crates/im-web/src/throttle.rs b/crates/im-web/src/throttle.rs index 741740a..0515608 100644 --- a/crates/im-web/src/throttle.rs +++ b/crates/im-web/src/throttle.rs @@ -76,8 +76,9 @@ pub const TOKEN_CLIENT_LIMIT: usize = 1200; /// `/token`. One person uses one chain or one code, so this is what limits a flood on a single one. pub const TOKEN_CHAIN_LIMIT: usize = 30; -/// `LoginFailed` audit rows written per account, or per client address when the account is unknown, inside -/// [`MINUTE`]. Failures beyond it are still refused and counted; only their audit rows are skipped. +/// `LoginFailed` audit rows written per typed address inside [`MINUTE`], whether or not an account has that +/// address, so the work done for a failure does not show which. Failures beyond it are still refused and +/// counted; only their audit rows are skipped. pub const LOGIN_AUDIT_LIMIT: usize = 1; /// Maximum number of distinct keys tracked at once. A flood of random keys cannot grow memory past @@ -362,9 +363,10 @@ pub fn token_code_key(client_id: &str, code_hash: &str) -> String { format!("token-code:{client_id}:{code_hash}") } -/// Throttle key for the `LoginFailed` audit rows of one account, by user id. -pub fn login_audit_user_key(user_id: &str) -> String { - format!("login-audit-user:{user_id}") +/// Throttle key for the `LoginFailed` audit rows of one normalised address. Its own key, not the sign-in +/// counter of the address, so the audit rows do not use up the sign-in attempts. +pub fn login_audit_key(email: &str) -> String { + format!("login-audit:{}", address_part(email)) } /// Throttle key for an address under a named scope, such as `login-ip`. diff --git a/docs/architecture.md b/docs/architecture.md index 0661f73..028b89a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -143,7 +143,8 @@ row gets `resync`. **audit_log**: per conventions section 10. Entries older than 365 days are deleted by the sweeper (`AUDIT_KEEP` in `sweeper.rs`, a fixed year rather than a setting). A `LoginFailed` row is written at most once per -minute per account, or per client address when the account is unknown; the throttle still counts every failure. +minute per normalised typed address, whether or not an account has it, so a failure does the same work either +way; the throttle still counts every failure. **settings**: `key` PK, `value`, `updated_at` (UI overrides and sealed SMTP password). @@ -224,6 +225,10 @@ redirects). Other errors redirect to the client with `error=` and `state`. again while enabled requires the current code (old defect: re-visiting enroll reset it). Disabling TOTP requires the password and a code. Admin "reset 2FA" clears TOTP and recovery codes and is audited and mailed to the user. +- Email change to an address that already belongs to an account: the requester gets the same 303 to + `?notice=sent` and the same count against the hourly limit as for a free address; no link is made, and the + owner gets a `security` notice mail ("someone tried to use this address for another account at "). + Applying a change still re-checks that the address is free. - Password policy: 10–256 chars, not containing the email local part or name words of ≥4 chars, not equal to the current one.