🔒 email change answers alike for taken addresses and mails their owner; login audit bound per typed address; headers on photo redirects
Browse files at this commit6ff6a7361fa0ff55d162a171ad337b08264b8444Parent: 9e444859 changed files +115 -75
- crates/im-web/src/i18n/flows.rs +0 -4
- crates/im-web/src/i18n/mail.rs +17 -0
- crates/im-web/src/mail/mod.rs +6 -0
- crates/im-web/src/mail/templates.rs +9 -2
- crates/im-web/src/pages/email.rs +37 -23
- crates/im-web/src/pages/login.rs +9 -12
- crates/im-web/src/security.rs +24 -28
- crates/im-web/src/throttle.rs +7 -5
- docs/architecture.md +6 -1
crates/im-web/src/i18n/flows.rsmodified+0 -4
| @@ -52,8 +52,6 @@ pub enum Flow { | |||
| 52 | EmailChangeQueued, | 52 | EmailChangeQueued, |
| 53 | /// Alert: the new address is the current one. | 53 | /// Alert: the new address is the current one. |
| 54 | EmailChangeSame, | 54 | EmailChangeSame, |
| 55 | - /// Alert: the new address belongs to an account, or cannot be used. | ||
| 56 | - EmailChangeUnavailable, | ||
| 57 | /// Title of the page behind an email-change link. | 55 | /// Title of the page behind an email-change link. |
| 58 | EmailLinkTitle, | 56 | EmailLinkTitle, |
| 59 | /// The button that confirms this half. | 57 | /// The button that confirms this half. |
| @@ -137,8 +135,6 @@ pub fn text(lang: Lang, key: Flow) -> &'static str { | |||
| 137 | } | 135 | } |
| 138 | (Flow::EmailChangeSame, Lang::En) => "That is already the address of your account.", | 136 | (Flow::EmailChangeSame, Lang::En) => "That is already the address of your account.", |
| 139 | (Flow::EmailChangeSame, Lang::Tr) => "Bu zaten hesabınızın adresi.", | 137 | (Flow::EmailChangeSame, Lang::Tr) => "Bu zaten hesabınızın adresi.", |
| 140 | - (Flow::EmailChangeUnavailable, Lang::En) => "That address cannot be used.", | ||
| 141 | - (Flow::EmailChangeUnavailable, Lang::Tr) => "Bu adres kullanılamaz.", | ||
| 142 | (Flow::EmailLinkTitle, Lang::En) => "Confirm the email change", | 138 | (Flow::EmailLinkTitle, Lang::En) => "Confirm the email change", |
| 143 | (Flow::EmailLinkTitle, Lang::Tr) => "E-posta değişikliğini onaylayın", | 139 | (Flow::EmailLinkTitle, Lang::Tr) => "E-posta değişikliğini onaylayın", |
| 144 | (Flow::EmailLinkConfirm, Lang::En) => "Confirm", | 140 | (Flow::EmailLinkConfirm, Lang::En) => "Confirm", |
crates/im-web/src/i18n/mail.rsmodified+17 -0
| @@ -35,6 +35,8 @@ pub enum MailKey { | |||
| 35 | EmailNewAction, | 35 | EmailNewAction, |
| 36 | /// Subject of the notice that the address changed. | 36 | /// Subject of the notice that the address changed. |
| 37 | EmailDoneSubject, | 37 | EmailDoneSubject, |
| 38 | + /// Subject of the notice to the owner of an address that someone tried to use for another account. | ||
| 39 | + EmailTakenSubject, | ||
| 38 | /// Subject: the password was changed by the person. | 40 | /// Subject: the password was changed by the person. |
| 39 | PasswordChangedSubject, | 41 | PasswordChangedSubject, |
| 40 | /// Body: the password was changed by the person. | 42 | /// Body: the password was changed by the person. |
| @@ -100,6 +102,8 @@ pub fn text(lang: Lang, key: MailKey) -> &'static str { | |||
| 100 | (MailKey::EmailNewAction, Lang::Tr) => "Bu adresi onaylayın", | 102 | (MailKey::EmailNewAction, Lang::Tr) => "Bu adresi onaylayın", |
| 101 | (MailKey::EmailDoneSubject, Lang::En) => "The email address of your im account changed", | 103 | (MailKey::EmailDoneSubject, Lang::En) => "The email address of your im account changed", |
| 102 | (MailKey::EmailDoneSubject, Lang::Tr) => "im hesabınızın e-posta adresi değişti", | 104 | (MailKey::EmailDoneSubject, Lang::Tr) => "im hesabınızın e-posta adresi değişti", |
| 105 | + (MailKey::EmailTakenSubject, Lang::En) => "Someone tried to use your email address", | ||
| 106 | + (MailKey::EmailTakenSubject, Lang::Tr) => "Biri e-posta adresinizi kullanmaya çalıştı", | ||
| 103 | (MailKey::PasswordChangedSubject, Lang::En) => "Your im password was changed", | 107 | (MailKey::PasswordChangedSubject, Lang::En) => "Your im password was changed", |
| 104 | (MailKey::PasswordChangedSubject, Lang::Tr) => "im parolanız değiştirildi", | 108 | (MailKey::PasswordChangedSubject, Lang::Tr) => "im parolanız değiştirildi", |
| 105 | (MailKey::PasswordChangedBody, Lang::En) => { | 109 | (MailKey::PasswordChangedBody, Lang::En) => { |
| @@ -195,6 +199,19 @@ pub fn email_new_body(lang: Lang, hours: u32) -> String { | |||
| 195 | } | 199 | } |
| 196 | } | 200 | } |
| 197 | 201 | ||
| 202 | +/// The sentence to the owner of an address that someone tried to use for another account, naming the | ||
| 203 | +/// service. Nothing is changed for the owner, and the sentence says so. | ||
| 204 | +pub fn email_taken_body(lang: Lang, issuer: &str) -> String { | ||
| 205 | + match lang { | ||
| 206 | + Lang::En => format!( | ||
| 207 | + "Someone tried to use this address for another account at {issuer}. Your account has not changed, and you do not need to do anything." | ||
| 208 | + ), | ||
| 209 | + Lang::Tr => format!( | ||
| 210 | + "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." | ||
| 211 | + ), | ||
| 212 | + } | ||
| 213 | +} | ||
| 214 | + | ||
| 198 | /// The sentence that tells both addresses the change happened. | 215 | /// The sentence that tells both addresses the change happened. |
| 199 | pub fn email_done_body(lang: Lang, new_email: &str) -> String { | 216 | pub fn email_done_body(lang: Lang, new_email: &str) -> String { |
| 200 | match lang { | 217 | match lang { |
crates/im-web/src/mail/mod.rsmodified+6 -0
| @@ -77,6 +77,11 @@ pub enum Mail<'a> { | |||
| 77 | /// The address the account has now. | 77 | /// The address the account has now. |
| 78 | new_email: &'a str, | 78 | new_email: &'a str, |
| 79 | }, | 79 | }, |
| 80 | + /// Sent to the owner of an address that someone tried to use for another account. Nothing changed. | ||
| 81 | + EmailTaken { | ||
| 82 | + /// The service's public origin, which names the account the attempt was for. | ||
| 83 | + issuer: &'a str, | ||
| 84 | + }, | ||
| 80 | /// A security notice. | 85 | /// A security notice. |
| 81 | Security(Notice), | 86 | Security(Notice), |
| 82 | /// A message from an administrator. The subject and the body are the administrator's own words; they | 87 | /// A message from an administrator. The subject and the body are the administrator's own words; they |
| @@ -105,6 +110,7 @@ impl Mail<'_> { | |||
| 105 | Mail::EmailOld { .. } => "email_old", | 110 | Mail::EmailOld { .. } => "email_old", |
| 106 | Mail::EmailNew { .. } => "email_new", | 111 | Mail::EmailNew { .. } => "email_new", |
| 107 | Mail::EmailDone { .. } => "email_done", | 112 | Mail::EmailDone { .. } => "email_done", |
| 113 | + Mail::EmailTaken { .. } => "security", | ||
| 108 | Mail::Security(_) => "security", | 114 | Mail::Security(_) => "security", |
| 109 | Mail::Notice { .. } => "notice", | 115 | Mail::Notice { .. } => "notice", |
| 110 | Mail::Test { .. } => "test", | 116 | Mail::Test { .. } => "test", |
crates/im-web/src/mail/templates.rsmodified+9 -2
| @@ -4,8 +4,8 @@ | |||
| 4 | use super::{Mail, Notice}; | 4 | use super::{Mail, Notice}; |
| 5 | use crate::i18n::Lang; | 5 | use crate::i18n::Lang; |
| 6 | use crate::i18n::mail::{ | 6 | use crate::i18n::mail::{ |
| 7 | - MailKey, email_done_body, email_new_body, email_old_body, greeting, invite_body, reset_body, | 7 | + MailKey, email_done_body, email_new_body, email_old_body, email_taken_body, greeting, |
| 8 | - text, | 8 | + invite_body, reset_body, text, |
| 9 | }; | 9 | }; |
| 10 | 10 | ||
| 11 | /// The rendered subject, plain-text body and HTML body of one mail. | 11 | /// 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 { | |||
| 87 | action: None, | 87 | action: None, |
| 88 | closing: vec![ignore, signature], | 88 | closing: vec![ignore, signature], |
| 89 | }, | 89 | }, |
| 90 | + Mail::EmailTaken { issuer } => Parts { | ||
| 91 | + subject: key(MailKey::EmailTakenSubject), | ||
| 92 | + greeting, | ||
| 93 | + paragraphs: vec![email_taken_body(lang, issuer)], | ||
| 94 | + action: None, | ||
| 95 | + closing: vec![signature], | ||
| 96 | + }, | ||
| 90 | Mail::Security(notice) => { | 97 | Mail::Security(notice) => { |
| 91 | let (subject, body) = match notice { | 98 | let (subject, body) = match notice { |
| 92 | Notice::PasswordChanged => ( | 99 | Notice::PasswordChanged => ( |
crates/im-web/src/pages/email.rsmodified+37 -23
| @@ -2,13 +2,15 @@ | |||
| 2 | //! half of it. | 2 | //! half of it. |
| 3 | //! | 3 | //! |
| 4 | //! The request needs the current password. It sends a link to the current address (with a cancel option) | 4 | //! The request needs the current password. It sends a link to the current address (with a cancel option) |
| 5 | -//! and a link to the new one. The change is applied only when both links have been confirmed, in the store, | 5 | +//! and a link to the new one. An address that already belongs to an account gets no links: its owner is |
| 6 | -//! and the store checks the new address is still free at that moment. A link is never used by a GET: the | 6 | +//! mailed a notice, and the requester gets the same answer as for a free address. The change is applied only |
| 7 | +//! when both links have been confirmed, in the store, and the store checks the new address is still free at | ||
| 8 | +//! that moment. A link is never used by a GET: the | ||
| 7 | //! confirm and cancel buttons are POSTs with the pre-session token. | 9 | //! confirm and cancel buttons are POSTs with the pre-session token. |
| 8 | 10 | ||
| 9 | use std::time::{Duration, Instant}; | 11 | use std::time::{Duration, Instant}; |
| 10 | 12 | ||
| 11 | -use im_core::model::AuditAction; | 13 | +use im_core::model::{AuditAction, User}; |
| 12 | use im_core::names::parse_email; | 14 | use im_core::names::parse_email; |
| 13 | use im_core::store::links::EmailConfirm; | 15 | use im_core::store::links::EmailConfirm; |
| 14 | use im_core::time::stamp_after; | 16 | use im_core::time::stamp_after; |
| @@ -117,26 +119,12 @@ async fn email_request_submit(cx: &Cx, Form(form): Form<EmailRequestForm>) -> Re | |||
| 117 | Some(problem), | 119 | Some(problem), |
| 118 | )); | 120 | )); |
| 119 | } | 121 | } |
| 120 | - if state | 122 | + // An address that belongs to an account gets the same answer and the same count as a free one, so the |
| 121 | - .store | 123 | + // answer does not show who has an account. Its owner learns of the attempt by mail instead. |
| 122 | - .user_by_email_folded(&new_email) | 124 | + let taken = state.store.user_by_email_folded(&new_email).await?; |
| 123 | - .await? | ||
| 124 | - .is_some() | ||
| 125 | - { | ||
| 126 | - let problem = flow_text(lang, Flow::EmailChangeUnavailable).to_owned(); | ||
| 127 | - return Ok(request_view( | ||
| 128 | - cx, | ||
| 129 | - lang, | ||
| 130 | - ViewerInfo::of(&viewer), | ||
| 131 | - csrf, | ||
| 132 | - current, | ||
| 133 | - false, | ||
| 134 | - Some(problem), | ||
| 135 | - )); | ||
| 136 | - } | ||
| 137 | 125 | ||
| 138 | - // Counted only for a request that would send mail: the two links are the costly part, and a request the | 126 | + // Counted for every request that gets this far, free or taken: both send mail, and the count must not |
| 139 | - // store would refuse sends nothing. The limit keeps one account from mailing many addresses. | 127 | + // show which one it was. The limit keeps one account from mailing many addresses. |
| 140 | if state | 128 | if state |
| 141 | .email_changes | 129 | .email_changes |
| 142 | .reserve( | 130 | .reserve( |
| @@ -149,6 +137,11 @@ async fn email_request_submit(cx: &Cx, Form(form): Form<EmailRequestForm>) -> Re | |||
| 149 | return Ok(refuse(Txt::ErrEmailChangeLimited)); | 137 | return Ok(refuse(Txt::ErrEmailChangeLimited)); |
| 150 | } | 138 | } |
| 151 | 139 | ||
| 140 | + if let Some(owner) = taken { | ||
| 141 | + notify_taken(state, &owner, lang).await; | ||
| 142 | + return Err(see_other("/account/email?notice=sent").into()); | ||
| 143 | + } | ||
| 144 | + | ||
| 152 | let hours = state.policy().email_change_hours; | 145 | let hours = state.policy().email_change_hours; |
| 153 | let old_token = generate_token(); | 146 | let old_token = generate_token(); |
| 154 | let new_token = generate_token(); | 147 | let new_token = generate_token(); |
| @@ -189,7 +182,11 @@ async fn email_request_submit(cx: &Cx, Form(form): Form<EmailRequestForm>) -> Re | |||
| 189 | .await | 182 | .await |
| 190 | { | 183 | { |
| 191 | Ok(started) => started, | 184 | Ok(started) => started, |
| 192 | - Err(im_core::Error::Conflict(_)) => return Ok(refuse(Txt::ErrEmailInvalid)), | 185 | + // Taken between the check above and this write: answered as a taken address is, with no link. Its |
| 186 | + // owner is not mailed in this rare race. | ||
| 187 | + Err(im_core::Error::Conflict(_)) => { | ||
| 188 | + return Err(see_other("/account/email?notice=sent").into()); | ||
| 189 | + } | ||
| 193 | Err(error) => return Err(error.into()), | 190 | Err(error) => return Err(error.into()), |
| 194 | }; | 191 | }; |
| 195 | // A change dropped by the limits looks the same to the person as a sent one, as the mail limits | 192 | // 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: & | |||
| 320 | } | 317 | } |
| 321 | } | 318 | } |
| 322 | 319 | ||
| 320 | +/// Tells the owner of an address that someone tried to use it for another account. It goes through the | ||
| 321 | +/// same outbox and limits as every mail; a failure is logged and never reaches the requester. | ||
| 322 | +async fn notify_taken(state: &AppState, owner: &User, lang: Lang) { | ||
| 323 | + let issuer = state.config.base_url.as_str(); | ||
| 324 | + match Recipient::new(Some(&owner.name), &owner.email) { | ||
| 325 | + Ok(to) => { | ||
| 326 | + let mail = Mail::EmailTaken { issuer }; | ||
| 327 | + let owner_lang = mail::lang_for(owner, lang); | ||
| 328 | + if let Err(error) = mail::queue(&state.store, &state.key, &to, owner_lang, &mail).await | ||
| 329 | + { | ||
| 330 | + tracing::error!(error = %error, "email taken notice not queued"); | ||
| 331 | + } | ||
| 332 | + } | ||
| 333 | + Err(error) => tracing::error!(error, "email taken notice not queued"), | ||
| 334 | + } | ||
| 335 | +} | ||
| 336 | + | ||
| 323 | /// The request page: the current address, the new address and the password. | 337 | /// The request page: the current address, the new address and the password. |
| 324 | fn request_view( | 338 | fn request_view( |
| 325 | cx: &Cx, | 339 | cx: &Cx, |
crates/im-web/src/pages/login.rsmodified+9 -12
| @@ -34,7 +34,7 @@ use crate::i18n::account::{Txt, text}; | |||
| 34 | use crate::state::AppState; | 34 | use crate::state::AppState; |
| 35 | use crate::throttle::{ | 35 | use crate::throttle::{ |
| 36 | LOGIN_AUDIT_LIMIT, LOGIN_IP_LIMIT, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT, ip_key, | 36 | LOGIN_AUDIT_LIMIT, LOGIN_IP_LIMIT, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT, ip_key, |
| 37 | - login_audit_user_key, two_factor_key, user_key, | 37 | + login_audit_key, two_factor_key, user_key, |
| 38 | }; | 38 | }; |
| 39 | use crate::views::{alert, field, page_lang, shell}; | 39 | use crate::views::{alert, field, page_lang, shell}; |
| 40 | 40 | ||
| @@ -135,7 +135,7 @@ async fn login_submit(cx: &Cx, Form(form): Form<LoginForm>) -> Result<impl View> | |||
| 135 | let target_id = found.as_ref().map(|user| user.id.clone()); | 135 | let target_id = found.as_ref().map(|user| user.id.clone()); |
| 136 | // The attempt stays counted on every failure below. | 136 | // The attempt stays counted on every failure below. |
| 137 | let Some(user) = found.filter(|user| password_ok && !user.is_disabled()) else { | 137 | let Some(user) = found.filter(|user| password_ok && !user.is_disabled()) else { |
| 138 | - audit_failed_sign_in(cx, state, target_id).await; | 138 | + audit_failed_sign_in(cx, state, &email, target_id).await; |
| 139 | let lang = page_lang(cx, None); | 139 | let lang = page_lang(cx, None); |
| 140 | let csrf = pre_csrf_token(cx); | 140 | let csrf = pre_csrf_token(cx); |
| 141 | return Ok(login_view( | 141 | return Ok(login_view( |
| @@ -160,7 +160,7 @@ async fn login_submit(cx: &Cx, Form(form): Form<LoginForm>) -> Result<impl View> | |||
| 160 | Some(redirect) => Err(redirect), | 160 | Some(redirect) => Err(redirect), |
| 161 | // The account changed after the password was checked: the sign-in fails like a wrong password. | 161 | // The account changed after the password was checked: the sign-in fails like a wrong password. |
| 162 | None => { | 162 | None => { |
| 163 | - audit_failed_sign_in(cx, state, target_id).await; | 163 | + audit_failed_sign_in(cx, state, &email, target_id).await; |
| 164 | let lang = page_lang(cx, None); | 164 | let lang = page_lang(cx, None); |
| 165 | let csrf = pre_csrf_token(cx); | 165 | let csrf = pre_csrf_token(cx); |
| 166 | Ok(login_view( | 166 | Ok(login_view( |
| @@ -176,17 +176,14 @@ async fn login_submit(cx: &Cx, Form(form): Form<LoginForm>) -> Result<impl View> | |||
| 176 | } | 176 | } |
| 177 | } | 177 | } |
| 178 | 178 | ||
| 179 | -/// Audits a sign-in that failed after the lookup. The row is per account, or per client address when | 179 | +/// Audits a sign-in that failed after the lookup. The row is kept per normalised address, known or not, |
| 180 | -/// the account is unknown, and at most one each minute, so a flood of failures cannot grow the audit | 180 | +/// and at most one each minute, so a flood of failures cannot grow the audit log. The key does not depend |
| 181 | -/// log. The throttle still counts every failure. | 181 | +/// on whether the account exists, so a failure does the same work either way (a timing signal otherwise). |
| 182 | -async fn audit_failed_sign_in(cx: &Cx, state: &AppState, target_id: Option<String>) { | 182 | +/// The throttle still counts every failure. |
| 183 | - let audit_key = match &target_id { | 183 | +async fn audit_failed_sign_in(cx: &Cx, state: &AppState, email: &str, target_id: Option<String>) { |
| 184 | - Some(id) => login_audit_user_key(id), | ||
| 185 | - None => ip_key("login-audit-ip", client_ip(cx)), | ||
| 186 | - }; | ||
| 187 | if state | 184 | if state |
| 188 | .per_minute | 185 | .per_minute |
| 189 | - .reserve(&audit_key, LOGIN_AUDIT_LIMIT, Instant::now()) | 186 | + .reserve(&login_audit_key(email), LOGIN_AUDIT_LIMIT, Instant::now()) |
| 190 | .is_ok() | 187 | .is_ok() |
| 191 | { | 188 | { |
| 192 | let target = target_id.as_deref().map(|id| ("user", id)); | 189 | let target = target_id.as_deref().map(|id| ("user", id)); |
crates/im-web/src/security.rsmodified+24 -28
| @@ -8,8 +8,9 @@ | |||
| 8 | //! | 8 | //! |
| 9 | //! Cache policy by path: pages (everything that is not a static asset or a photo) are `no-store`, | 9 | //! Cache policy by path: pages (everything that is not a static asset or a photo) are `no-store`, |
| 10 | //! so a page with a secret (recovery codes, a TOTP secret) is never kept by a browser or a proxy. | 10 | //! so a page with a secret (recovery codes, a TOTP secret) is never kept by a browser or a proxy. |
| 11 | -//! Assets set their own long-lived policy. Photos set their own `private` policy and their own CSP | 11 | +//! Assets set their own long-lived policy. A photo that has its bytes sets its own `private` policy |
| 12 | -//! (see `pages/photo.rs`), so this layer leaves both alone. | 12 | +//! and its own CSP (see `pages/photo.rs`), and this layer leaves both alone. A photo's redirect or |
| 13 | +//! error (sign-in, 404) is a page to the browser, so it gets the page headers. | ||
| 13 | 14 | ||
| 14 | use topcoat::context::Cx; | 15 | use topcoat::context::Cx; |
| 15 | use topcoat::router::request::uri; | 16 | use topcoat::router::request::uri; |
| @@ -69,7 +70,8 @@ pub fn headers_for(base_url: &str) -> HeaderMap { | |||
| 69 | pub enum Answer { | 70 | pub enum Answer { |
| 70 | /// A static file under `/assets/`, with its own cache policy. | 71 | /// A static file under `/assets/`, with its own cache policy. |
| 71 | Asset, | 72 | Asset, |
| 72 | - /// A profile photo under `/photo/`, with its own cache policy and its own CSP. | 73 | + /// A profile photo under `/photo/`. An answer with bytes has its own cache policy and CSP; a redirect or |
| 74 | + /// error has the page headers. | ||
| 73 | Photo, | 75 | Photo, |
| 74 | /// Public OpenID metadata (discovery and the key set). Not secret, so it may be cached; the handler | 76 | /// Public OpenID metadata (discovery and the key set). Not secret, so it may be cached; the handler |
| 75 | /// sets the short cache policy. | 77 | /// sets the short cache policy. |
| @@ -91,25 +93,20 @@ pub fn answer_for(path: &str) -> Answer { | |||
| 91 | } | 93 | } |
| 92 | } | 94 | } |
| 93 | 95 | ||
| 94 | -/// Adds the security headers to every response, and `Cache-Control: no-store` to every page. | 96 | +/// Adds the security headers to every response, and `Cache-Control: no-store` to every page and every |
| 97 | +/// photo answer that is not a photo's bytes. | ||
| 95 | /// | 98 | /// |
| 96 | /// It uses the per-request response headers, which the router applies after the layers have run, | 99 | /// It uses the per-request response headers, which the router applies after the layers have run, |
| 97 | -/// so error responses (404, 500) carry them as well. A photo gets the same headers without the | 100 | +/// so error responses (404, 500, the sign-in redirect) carry them as well. A header the route set |
| 98 | -/// page CSP, because the photo handler sends a stricter one of its own. | 101 | +/// itself is never replaced, so a photo with bytes keeps its own CSP and cache policy. |
| 99 | pub struct SecurityHeaders { | 102 | pub struct SecurityHeaders { |
| 100 | headers: HeaderMap, | 103 | headers: HeaderMap, |
| 101 | - photo_headers: HeaderMap, | ||
| 102 | } | 104 | } |
| 103 | 105 | ||
| 104 | impl SecurityHeaders { | 106 | impl SecurityHeaders { |
| 105 | /// A layer that adds `headers` to every response. | 107 | /// A layer that adds `headers` to every response. |
| 106 | pub fn new(headers: HeaderMap) -> Self { | 108 | pub fn new(headers: HeaderMap) -> Self { |
| 107 | - let mut photo_headers = headers.clone(); | 109 | + Self { headers } |
| 108 | - photo_headers.remove(header::CONTENT_SECURITY_POLICY); | ||
| 109 | - Self { | ||
| 110 | - headers, | ||
| 111 | - photo_headers, | ||
| 112 | - } | ||
| 113 | } | 110 | } |
| 114 | } | 111 | } |
| 115 | 112 | ||
| @@ -120,19 +117,17 @@ impl Layer for SecurityHeaders { | |||
| 120 | 117 | ||
| 121 | fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { | 118 | fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { |
| 122 | Box::pin(async move { | 119 | Box::pin(async move { |
| 123 | - let answer = answer_for(uri(cx).path()); | 120 | + let path = uri(cx).path(); |
| 124 | - let mut headers = match answer { | 121 | + let answer = answer_for(path); |
| 125 | - Answer::Photo => self.photo_headers.clone(), | 122 | + let mut headers = self.headers.clone(); |
| 126 | - Answer::Asset | Answer::Public | Answer::Page => self.headers.clone(), | 123 | + if matches!(answer, Answer::Page | Answer::Photo) { |
| 127 | - }; | ||
| 128 | - if answer == Answer::Page { | ||
| 129 | headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(NO_STORE)); | 124 | headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(NO_STORE)); |
| 130 | - if token_path(uri(cx).path()) { | 125 | + } |
| 131 | - headers.insert( | 126 | + if answer == Answer::Page && token_path(path) { |
| 132 | - header::REFERRER_POLICY, | 127 | + headers.insert( |
| 133 | - HeaderValue::from_static(NO_REFERRER), | 128 | + header::REFERRER_POLICY, |
| 134 | - ); | 129 | + HeaderValue::from_static(NO_REFERRER), |
| 135 | - } | 130 | + ); |
| 136 | } | 131 | } |
| 137 | match next.run(cx, body).await { | 132 | match next.run(cx, body).await { |
| 138 | // A header the route set itself wins: a token answer that is already `no-store`, or a | 133 | // A header the route set itself wins: a token answer that is already `no-store`, or a |
| @@ -184,10 +179,11 @@ mod tests { | |||
| 184 | .expect("request"); | 179 | .expect("request"); |
| 185 | let response = crate::boot::router(state.clone()).handle(request).await; | 180 | let response = crate::boot::router(state.clone()).handle(request).await; |
| 186 | let headers = response.headers(); | 181 | let headers = response.headers(); |
| 187 | - // A missing photo answers without Cache-Control; a repeat is the bug under test. | 182 | + // A repeat is the bug under test. A photo redirect (to sign-in) is an error answer, so it |
| 183 | + // carries the layer's Cache-Control and CSP once each. | ||
| 188 | let cache_control = headers.get_all(header::CACHE_CONTROL).iter().count(); | 184 | let cache_control = headers.get_all(header::CACHE_CONTROL).iter().count(); |
| 189 | assert!(cache_control <= 1, "Cache-Control repeated on {path}"); | 185 | assert!(cache_control <= 1, "Cache-Control repeated on {path}"); |
| 190 | - if path == "/token" { | 186 | + if path == "/token" || path == "/photo/01HZ" { |
| 191 | assert_eq!(cache_control, 1, "Cache-Control on {path}"); | 187 | assert_eq!(cache_control, 1, "Cache-Control on {path}"); |
| 192 | } | 188 | } |
| 193 | let csp = headers | 189 | let csp = headers |
| @@ -195,7 +191,7 @@ mod tests { | |||
| 195 | .iter() | 191 | .iter() |
| 196 | .count(); | 192 | .count(); |
| 197 | assert!(csp <= 1, "CSP repeated on {path}"); | 193 | assert!(csp <= 1, "CSP repeated on {path}"); |
| 198 | - if path == "/token" { | 194 | + if path == "/token" || path == "/photo/01HZ" { |
| 199 | assert_eq!(csp, 1, "CSP on {path}"); | 195 | assert_eq!(csp, 1, "CSP on {path}"); |
| 200 | } | 196 | } |
| 201 | } | 197 | } |
crates/im-web/src/throttle.rsmodified+7 -5
| @@ -76,8 +76,9 @@ pub const TOKEN_CLIENT_LIMIT: usize = 1200; | |||
| 76 | /// `/token`. One person uses one chain or one code, so this is what limits a flood on a single one. | 76 | /// `/token`. One person uses one chain or one code, so this is what limits a flood on a single one. |
| 77 | pub const TOKEN_CHAIN_LIMIT: usize = 30; | 77 | pub const TOKEN_CHAIN_LIMIT: usize = 30; |
| 78 | 78 | ||
| 79 | -/// `LoginFailed` audit rows written per account, or per client address when the account is unknown, inside | 79 | +/// `LoginFailed` audit rows written per typed address inside [`MINUTE`], whether or not an account has that |
| 80 | -/// [`MINUTE`]. Failures beyond it are still refused and counted; only their audit rows are skipped. | 80 | +/// address, so the work done for a failure does not show which. Failures beyond it are still refused and |
| 81 | +/// counted; only their audit rows are skipped. | ||
| 81 | pub const LOGIN_AUDIT_LIMIT: usize = 1; | 82 | pub const LOGIN_AUDIT_LIMIT: usize = 1; |
| 82 | 83 | ||
| 83 | /// Maximum number of distinct keys tracked at once. A flood of random keys cannot grow memory past | 84 | /// 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 { | |||
| 362 | format!("token-code:{client_id}:{code_hash}") | 363 | format!("token-code:{client_id}:{code_hash}") |
| 363 | } | 364 | } |
| 364 | 365 | ||
| 365 | -/// Throttle key for the `LoginFailed` audit rows of one account, by user id. | 366 | +/// Throttle key for the `LoginFailed` audit rows of one normalised address. Its own key, not the sign-in |
| 366 | -pub fn login_audit_user_key(user_id: &str) -> String { | 367 | +/// counter of the address, so the audit rows do not use up the sign-in attempts. |
| 367 | - format!("login-audit-user:{user_id}") | 368 | +pub fn login_audit_key(email: &str) -> String { |
| 369 | + format!("login-audit:{}", address_part(email)) | ||
| 368 | } | 370 | } |
| 369 | 371 | ||
| 370 | /// Throttle key for an address under a named scope, such as `login-ip`. | 372 | /// Throttle key for an address under a named scope, such as `login-ip`. |
docs/architecture.mdmodified+6 -1
| @@ -143,7 +143,8 @@ row gets `resync`. | |||
| 143 | 143 | ||
| 144 | **audit_log**: per conventions section 10. Entries older than 365 days are deleted by the sweeper | 144 | **audit_log**: per conventions section 10. Entries older than 365 days are deleted by the sweeper |
| 145 | (`AUDIT_KEEP` in `sweeper.rs`, a fixed year rather than a setting). A `LoginFailed` row is written at most once per | 145 | (`AUDIT_KEEP` in `sweeper.rs`, a fixed year rather than a setting). A `LoginFailed` row is written at most once per |
| 146 | -minute per account, or per client address when the account is unknown; the throttle still counts every failure. | 146 | +minute per normalised typed address, whether or not an account has it, so a failure does the same work either |
| 147 | +way; the throttle still counts every failure. | ||
| 147 | 148 | ||
| 148 | **settings**: `key` PK, `value`, `updated_at` (UI overrides and sealed SMTP password). | 149 | **settings**: `key` PK, `value`, `updated_at` (UI overrides and sealed SMTP password). |
| 149 | 150 | ||
| @@ -224,6 +225,10 @@ redirects). Other errors redirect to the client with `error=` and `state`. | |||
| 224 | again while enabled requires the current code (old defect: re-visiting enroll reset it). Disabling TOTP | 225 | again while enabled requires the current code (old defect: re-visiting enroll reset it). Disabling TOTP |
| 225 | requires the password and a code. Admin "reset 2FA" clears TOTP and recovery codes and is audited and mailed | 226 | requires the password and a code. Admin "reset 2FA" clears TOTP and recovery codes and is audited and mailed |
| 226 | to the user. | 227 | to the user. |
| 228 | +- Email change to an address that already belongs to an account: the requester gets the same 303 to | ||
| 229 | + `?notice=sent` and the same count against the hourly limit as for a free address; no link is made, and the | ||
| 230 | + owner gets a `security` notice mail ("someone tried to use this address for another account at <issuer>"). | ||
| 231 | + Applying a change still re-checks that the address is free. | ||
| 227 | - Password policy: 10–256 chars, not containing the email local part or name words of ≥4 chars, not equal to | 232 | - Password policy: 10–256 chars, not containing the email local part or name words of ≥4 chars, not equal to |
| 228 | the current one. | 233 | the current one. |
| 229 | 234 | ||