diff --git a/Cargo.lock b/Cargo.lock index e371ca6..c15f7c5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1216,6 +1216,12 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + [[package]] name = "futures-macro" version = "0.3.34" @@ -1246,9 +1252,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", + "futures-io", "futures-macro", "futures-sink", "futures-task", + "memchr", "pin-project-lite", "slab", ] @@ -1862,6 +1870,7 @@ dependencies = [ "hex", "http", "im-core", + "lettre", "qrcode", "reqwest", "serde", @@ -2137,15 +2146,26 @@ version = "0.11.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2c646bd5cc763b1087b15493e29a64be6147ba8f19342004fa52048ee596eae" dependencies = [ + "async-trait", + "base64 0.23.1", "email-encoding", "email_address", "fastrand", + "futures-io", + "futures-util", "hostname", "httpdate", "idna", "mime", "nom 8.0.0", + "percent-encoding", "quoted_printable", + "rustls", + "socket2", + "tokio", + "tokio-rustls", + "url", + "webpki-roots", ] [[package]] @@ -3243,7 +3263,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "aws-lc-rs", + "log", "once_cell", + "ring", "rustls-pki-types", "rustls-webpki", "subtle", @@ -5042,6 +5064,15 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "webpki-roots" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" diff --git a/Cargo.toml b/Cargo.toml index ce6691f..b685bbd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,7 @@ grass = "0.13.4" hex = "0.4.3" hmac = "0.13.0" image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "webp", "gif"] } +lettre = { version = "0.11.23", default-features = false, features = ["builder", "smtp-transport", "tokio1", "tokio1-rustls-tls"] } jiff = { version = "0.2.38", default-features = false, features = ["std", "tzdb-bundle-always"] } http = "1.5.0" ipnet = "2.12.2" diff --git a/config/im.example.toml b/config/im.example.toml index 30c0459..d8052d9 100644 --- a/config/im.example.toml +++ b/config/im.example.toml @@ -19,7 +19,7 @@ base_url = "http://localhost:8080" trusted_proxies = [] [mail] -# Development only: write mail to data/mail-log/ instead of sending it. +# Reserved. Has no effect yet: mail is always queued and sent through [smtp]. log_only = true [backup] @@ -39,3 +39,25 @@ require_2fa_for_admins = true max_sessions = 10 # Hard cap of a browser session, in days from sign-in. Sessions are extended while they are used, up to this. session_max_days = 30 +# Days an invitation stays usable. Between 1 and 30. +invite_days = 7 +# Minutes a password-reset link stays usable. Between 5 and 1440. +reset_minutes = 60 +# Hours both halves of an email change stay usable. Between 1 and 168. +email_change_hours = 24 + +[smtp] +# Host of the submission server. Empty means no sender: mail waits in the outbox and no attempt is spent. +host = "" +# 465 for implicit TLS, 587 for STARTTLS. +port = 465 +# "implicit", "starttls", or "none" (none is refused unless host is localhost). +tls = "implicit" +# Login name. Empty for a relay that needs no login. +username = "" +# File with the password, first line only. Must not be readable by group or others. +password_file = "" +# Address mail is sent from. +from = "" +# Display name of the sender. +from_name = "im" diff --git a/crates/im-core/src/config.rs b/crates/im-core/src/config.rs index b4f0d00..f45df5a 100644 --- a/crates/im-core/src/config.rs +++ b/crates/im-core/src/config.rs @@ -36,11 +36,75 @@ fn deserialize_trusted_proxies<'de, D: Deserializer<'de>>( #[derive(Debug, Clone, Default, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct MailConfig { - /// When true, mail is written to `data_dir/mail-log/` instead of being sent. For development - /// only; a production instance sends mail through the SMTP sender set in the admin UI. + /// Reserved for a development mail log. It has no effect yet: mail is always queued in the outbox + /// and sent through `[smtp]`. pub log_only: bool, } +/// How the SMTP connection is secured. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum SmtpTls { + /// TLS from the first byte of the connection (port 465 by convention). + #[default] + Implicit, + /// A plain connection that is upgraded with STARTTLS. The upgrade is required. + Starttls, + /// No TLS. Only for a relay on localhost, where the traffic never leaves the machine. + None, +} + +/// The outbound SMTP sender. Empty `host` means no sender: mail waits in the outbox and no attempt is +/// spent. The password is never in this file; `password_file` names a file that only the service user +/// can read (mode 0600 or stricter), and it is read again before each batch, so it can be rotated. +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct SmtpConfig { + /// Host name or address of the submission server. Empty for none. + pub host: String, + /// TCP port. 465 for implicit TLS, 587 for STARTTLS. + pub port: u16, + /// Transport security. `none` is refused unless `host` is localhost. + pub tls: SmtpTls, + /// Login name. Empty for an unauthenticated relay. + pub username: String, + /// File holding the password, first line only. Empty when there is no login. + pub password_file: PathBuf, + /// Address mail is sent from. Required when `host` is set. + pub from: String, + /// Display name of the sender. + pub from_name: String, +} + +impl Default for SmtpConfig { + fn default() -> Self { + Self { + host: String::new(), + port: 465, + tls: SmtpTls::Implicit, + username: String::new(), + password_file: PathBuf::new(), + from: String::new(), + from_name: "im".to_owned(), + } + } +} + +impl SmtpConfig { + /// True when a sender is configured. + pub fn enabled(&self) -> bool { + !self.host.is_empty() + } +} + +/// True for `localhost` and for loopback addresses, the only places plaintext SMTP is allowed. +pub fn is_localhost(host: &str) -> bool { + host.eq_ignore_ascii_case("localhost") + || host + .parse::() + .is_ok_and(|addr| addr.is_loopback()) +} + /// Scheduled backups. Off while `dir` is empty. #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields, default)] @@ -87,6 +151,12 @@ pub struct PolicyConfig { /// Hard cap of a browser session, in days from sign-in. A session is idle-extended on use (30 days /// since its last use) but never lives longer than this. Between 1 and 365. pub session_max_days: u32, + /// Days an invitation stays usable. Between 1 and 30. + pub invite_days: u32, + /// Minutes a password-reset link stays usable. Between 5 and 1440. + pub reset_minutes: u32, + /// Hours both halves of an email change stay usable. Between 1 and 168. + pub email_change_hours: u32, } impl Default for PolicyConfig { @@ -95,6 +165,9 @@ impl Default for PolicyConfig { require_2fa_for_admins: true, max_sessions: 10, session_max_days: 30, + invite_days: 7, + reset_minutes: 60, + email_change_hours: 24, } } } @@ -119,6 +192,9 @@ pub struct Config { /// Mail settings without secrets. #[serde(default)] pub mail: MailConfig, + /// The SMTP sender. + #[serde(default)] + pub smtp: SmtpConfig, /// Scheduled backups. #[serde(default)] pub backup: BackupConfig, @@ -183,6 +259,22 @@ impl Config { "[policy] session_max_days must be between 1 and 365".into(), )); } + if !(1..=30).contains(&self.policy.invite_days) { + return Err(Error::Config( + "[policy] invite_days must be between 1 and 30".into(), + )); + } + if !(5..=1440).contains(&self.policy.reset_minutes) { + return Err(Error::Config( + "[policy] reset_minutes must be between 5 and 1440".into(), + )); + } + if !(1..=168).contains(&self.policy.email_change_hours) { + return Err(Error::Config( + "[policy] email_change_hours must be between 1 and 168".into(), + )); + } + self.validate_smtp()?; let hc = &self.backup.healthcheck_url; if !hc.is_empty() && !(hc.starts_with("https://") || hc.starts_with("http://")) { return Err(Error::Config( @@ -193,6 +285,37 @@ impl Config { } } +impl Config { + /// The SMTP rules: plaintext only on localhost, a valid sender address, and a password file when + /// there is a login. Checked only when a sender is configured. + fn validate_smtp(&self) -> Result<()> { + let smtp = &self.smtp; + if !smtp.enabled() { + return Ok(()); + } + if smtp.port == 0 { + return Err(Error::Config( + "[smtp] port must be between 1 and 65535".into(), + )); + } + if smtp.tls == SmtpTls::None && !is_localhost(&smtp.host) { + return Err(Error::Config( + "[smtp] tls = \"none\" is allowed only for a localhost host".into(), + )); + } + if !smtp.username.is_empty() && smtp.password_file.as_os_str().is_empty() { + return Err(Error::Config( + "[smtp] a username needs a password_file".into(), + )); + } + crate::names::parse_email(&smtp.from) + .map_err(|_| Error::Config("[smtp] from must be an email address".into()))?; + crate::names::parse_display_name(&smtp.from_name) + .map_err(|_| Error::Config("[smtp] from_name is not a valid name".into()))?; + Ok(()) + } +} + /// Checks that `base_url` is an http(s) origin with a path of at most `/`. fn validate_base_url(url: &str) -> Result<()> { let rest = url @@ -217,4 +340,19 @@ mod tests { let typo = format!("{EXAMPLE}\nlisen = \"0.0.0.0:1\"\n"); assert!(Config::parse(&typo).is_err()); } + + #[test] + fn plaintext_smtp_is_refused_unless_the_host_is_localhost() { + let base = "database = \"d\"\ndata_dir = \"x\"\nlisten = \"127.0.0.1:1\"\nbase_url = \"http://a\"\n"; + let remote = format!( + "{base}[smtp]\nhost = \"mail.example.com\"\ntls = \"none\"\nfrom = \"im@example.com\"\n" + ); + assert!(Config::parse(&remote).is_err()); + let local = format!( + "{base}[smtp]\nhost = \"127.0.0.1\"\nport = 2525\ntls = \"none\"\nfrom = \"im@example.com\"\n" + ); + Config::parse(&local).expect("localhost may be plain"); + let no_from = format!("{base}[smtp]\nhost = \"mail.example.com\"\n"); + assert!(Config::parse(&no_from).is_err()); + } } diff --git a/crates/im-core/src/model.rs b/crates/im-core/src/model.rs index 3ad9d45..a67f30e 100644 --- a/crates/im-core/src/model.rs +++ b/crates/im-core/src/model.rs @@ -142,6 +142,22 @@ pub enum AuditAction { SessionRevoked, /// Every session except the current one was ended. SessionsRevoked, + /// An administrator invited someone. + InviteCreated, + /// An invitation was accepted and its account created. + InviteAccepted, + /// A password reset was asked for, for an account that exists and is enabled. + ResetRequested, + /// A password was set through a reset link. Every session of the person ended. + PasswordReset, + /// An email change was asked for. + EmailChangeRequested, + /// One half of an email change was confirmed. The data says which half. + EmailChangeConfirmed, + /// An email change was cancelled from its old-address link. + EmailChangeCancelled, + /// The address of an account was changed. + EmailChanged, } impl AuditAction { @@ -163,6 +179,14 @@ impl AuditAction { AuditAction::RecoveryCodesIssued => "recovery.issued", AuditAction::SessionRevoked => "session.revoked", AuditAction::SessionsRevoked => "sessions.revoked", + AuditAction::InviteCreated => "invite.created", + AuditAction::InviteAccepted => "invite.accepted", + AuditAction::ResetRequested => "reset.requested", + AuditAction::PasswordReset => "password.reset", + AuditAction::EmailChangeRequested => "email_change.requested", + AuditAction::EmailChangeConfirmed => "email_change.confirmed", + AuditAction::EmailChangeCancelled => "email_change.cancelled", + AuditAction::EmailChanged => "email.changed", } } } diff --git a/crates/im-core/src/store/invites.rs b/crates/im-core/src/store/invites.rs new file mode 100644 index 0000000..986be40 --- /dev/null +++ b/crates/im-core/src/store/invites.rs @@ -0,0 +1,290 @@ +//! Invitations: an administrator creates one for an address; the person who receives it sets a name and +//! a password and gets an account. +//! +//! The token is never stored, only its hash. Creating an invitation for an address deletes the older +//! pending ones for that address, so only the newest link works. Accepting is one conditional update +//! (`accepted_at IS NULL AND expires_at > now`): two parallel redemptions of the same link cannot both +//! succeed, because the writer serialises them and the second one finds the invitation already used. +//! The account is created in the same transaction, so a refused acceptance leaves no account behind. + +use std::time::Duration; + +use turso::Connection; + +use crate::error::{Error, Result}; +use crate::model::User; +use crate::store::directory::{ChangeKind, record_change}; +use crate::store::users::{USER_COLS, insert_error, map_user}; +use crate::store::{Store, col_opt_text, col_text, db_err, fetch_opt, finish, new_id}; +use crate::time::now_stamp; + +/// A pending or used invitation, as the store returns it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Invite { + /// Hex SHA-256 of the token in the link. + pub token_hash: String, + /// The normalised address the invitation is for. The account gets this address. + pub email_folded: String, + /// Whether the account is made an administrator. + pub is_admin: bool, + /// When the invitation stops being usable. + pub expires_at: String, + /// Set when the invitation was used. + pub accepted_at: Option, +} + +/// The result of [`Store::accept_invite`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AcceptOutcome { + /// The account was created. + Accepted(Box), + /// The link is used, expired, or the address became registered in the meantime. The three are not + /// told apart, so the answer reveals nothing about the address. + Refused, +} + +fn map_invite(row: &turso::Row) -> Result { + Ok(Invite { + token_hash: col_text(row, 0)?, + email_folded: col_text(row, 1)?, + is_admin: crate::store::col_int(row, 2)? != 0, + expires_at: col_text(row, 3)?, + accepted_at: col_opt_text(row, 4)?, + }) +} + +const INVITE_COLS: &str = "token_hash, email_folded, is_admin, expires_at, accepted_at"; + +/// Whether an invitation for `email_folded` may be created: the address must not belong to an account. +async fn address_is_free(conn: &Connection, email_folded: &str) -> Result { + let taken = fetch_opt( + conn, + "SELECT 1 FROM users WHERE email_folded = ?1", + (email_folded.to_string(),), + |_row| Ok(()), + ) + .await?; + Ok(taken.is_none()) +} + +impl Store { + /// Stores a new invitation. In one transaction: the address must not be registered yet, the older + /// pending invitations for it are deleted, and the new row is inserted. `expires_at` is a stamp. + pub async fn create_invite( + &self, + token_hash: &str, + email_folded: &str, + is_admin: bool, + invited_by: &str, + expires_at: &str, + ) -> Result<()> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + if !address_is_free(&tx, email_folded).await? { + return Err(Error::Conflict( + "that email address already has an account".into(), + )); + } + tx.execute( + "DELETE FROM invites WHERE email_folded = ?1 AND accepted_at IS NULL", + (email_folded.to_string(),), + ) + .await + .map_err(db_err)?; + tx.execute( + "INSERT INTO invites (token_hash, email_folded, is_admin, invited_by, created_at, expires_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + ( + token_hash.to_string(), + email_folded.to_string(), + i64::from(is_admin), + invited_by.to_string(), + now_stamp(), + expires_at.to_string(), + ), + ) + .await + .map_err(db_err)?; + Ok(()) + } + .await; + finish(tx, outcome).await + } + + /// The invitation with this token hash, only while it is usable (not accepted, not expired). + pub async fn live_invite(&self, token_hash: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!( + "SELECT {INVITE_COLS} FROM invites \ + WHERE token_hash = ?1 AND accepted_at IS NULL AND expires_at > ?2" + ), + (token_hash.to_string(), now_stamp()), + map_invite, + ) + .await + } + + /// Accepts an invitation and creates its account, in one transaction. + /// + /// The first statement is the conditional update that spends the link. If it touches no row, the + /// link was used or has expired, and nothing else happens. A UNIQUE clash on the address (it was + /// registered after the invitation was made) rolls the whole transaction back, so the link is not + /// spent by a refused acceptance either. `name` and `password_hash` are already checked by the caller. + pub async fn accept_invite( + &self, + token_hash: &str, + name: &str, + password_hash: &str, + ) -> Result { + let now = now_stamp(); + let id = new_id(); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result> = async { + let spent = tx + .execute( + "UPDATE invites SET accepted_at = ?2 \ + WHERE token_hash = ?1 AND accepted_at IS NULL AND expires_at > ?2", + (token_hash.to_string(), now.clone()), + ) + .await + .map_err(db_err)?; + if spent != 1 { + return Ok(None); + } + let invite = fetch_opt( + &tx, + &format!("SELECT {INVITE_COLS} FROM invites WHERE token_hash = ?1"), + (token_hash.to_string(),), + map_invite, + ) + .await? + .ok_or(Error::NotFound)?; + tx.execute( + "INSERT INTO users (id, email, email_folded, name, password_hash, is_admin, \ + created_at, updated_at) VALUES (?1, ?2, ?2, ?3, ?4, ?5, ?6, ?6)", + ( + id.clone(), + invite.email_folded.clone(), + name.to_string(), + password_hash.to_string(), + i64::from(invite.is_admin), + now.clone(), + ), + ) + .await + .map_err(insert_error)?; + record_change(&tx, &id, ChangeKind::Member).await?; + let user = fetch_opt( + &tx, + &format!("SELECT {USER_COLS} FROM users WHERE id = ?1"), + (id.clone(),), + map_user, + ) + .await? + .ok_or(Error::NotFound)?; + Ok(Some(user)) + } + .await; + // A UNIQUE clash comes back as a conflict, and finish rolls the spend back with it. + let result = match finish(tx, outcome).await { + Ok(Some(user)) => AcceptOutcome::Accepted(Box::new(user)), + Ok(None) | Err(Error::Conflict(_)) => AcceptOutcome::Refused, + Err(error) => return Err(error), + }; + drop(conn); + if matches!(result, AcceptOutcome::Accepted(_)) { + self.announce_directory(); + } + Ok(result) + } + + /// Deletes invitations that have expired. Returns how many were removed. Run by the sweeper. + pub async fn sweep_invites(&self, now: &str) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM invites WHERE expires_at <= ?1", + (now.to_string(),), + ) + .await + .map_err(db_err) + } +} + +/// How long an invitation of `days` lasts, as a duration. Used by callers that compute the stamp. +pub fn invite_lifetime(days: u32) -> Duration { + Duration::from_secs(u64::from(days) * 24 * 60 * 60) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::time::stamp_after; + + async fn store() -> (tempfile::TempDir, Store) { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("im.db")).await.unwrap(); + (dir, store) + } + + #[tokio::test] + async fn a_parallel_double_accept_creates_exactly_one_user() { + let (_dir, store) = store().await; + let admin = store + .create_user("admin@example.com", "Admin", "hash", true) + .await + .unwrap(); + store + .create_invite( + "tok-hash", + "newbie@example.com", + false, + &admin.id, + &stamp_after(invite_lifetime(7)), + ) + .await + .unwrap(); + let (a, b) = tokio::join!( + store.accept_invite("tok-hash", "First", "pw1"), + store.accept_invite("tok-hash", "Second", "pw2"), + ); + let outcomes = [a.unwrap(), b.unwrap()]; + let accepted = outcomes + .iter() + .filter(|o| matches!(o, AcceptOutcome::Accepted(_))) + .count(); + assert_eq!(accepted, 1, "{outcomes:?}"); + assert_eq!(store.user_count().await.unwrap(), 2); + } + + #[tokio::test] + async fn an_expired_invitation_is_refused_and_creates_nothing() { + let (_dir, store) = store().await; + let admin = store + .create_user("admin@example.com", "Admin", "hash", true) + .await + .unwrap(); + // Created already expired: the lifetime is negative. + let past = crate::time::stamp_before(std::time::Duration::from_secs(60)); + store + .create_invite("old-hash", "late@example.com", false, &admin.id, &past) + .await + .unwrap(); + assert!(store.live_invite("old-hash").await.unwrap().is_none()); + let outcome = store + .accept_invite("old-hash", "Late", "password-long") + .await + .unwrap(); + assert_eq!(outcome, AcceptOutcome::Refused); + assert!( + store + .user_by_email_folded("late@example.com") + .await + .unwrap() + .is_none() + ); + } +} diff --git a/crates/im-core/src/store/links.rs b/crates/im-core/src/store/links.rs new file mode 100644 index 0000000..c5920d5 --- /dev/null +++ b/crates/im-core/src/store/links.rs @@ -0,0 +1,449 @@ +//! Single-use account links: password reset, and the two halves of an email change. +//! +//! Every link is stored as the hash of its token, and every use is one conditional update, so a link +//! works once even when two requests race. The writer connection serialises the transactions here. +//! +//! An email change has two links that share a `pair_id`: `email_old` goes to the current address and +//! `email_new` to the new one. The change is applied only when both halves have been confirmed. The +//! old-address page can also cancel it, which deletes the pair. Applying the change checks that the new +//! address is still free at that moment, not when it was requested. + +use turso::Connection; + +use crate::error::{Error, Result}; +use crate::store::backchannel::EndReason; +use crate::store::directory::{ChangeKind, record_change}; +use crate::store::sessions::end_all_sessions; +use crate::store::users::insert_error; +use crate::store::{Store, col_opt_text, col_text, db_err, fetch_opt, finish, new_id}; +use crate::time::now_stamp; + +/// One row of `account_links`, as the web layer reads it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AccountLink { + /// The person the link belongs to. + pub user_id: String, + /// `reset`, `email_old` or `email_new`. + pub kind: String, + /// The two halves of one email change share this id. + pub pair_id: Option, + /// The address the change moves to (both halves carry it). + pub new_email: Option, + /// When the link stops being usable. + pub expires_at: String, +} + +/// What a confirmation of one half did. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum EmailConfirm { + /// This half is confirmed; the other half is still waiting. + Waiting, + /// Both halves are confirmed and the address was changed. + Applied { + /// The person whose address changed. + user_id: String, + /// The address before the change. + old_email: String, + /// The address after the change. + new_email: String, + }, + /// The link is not usable, or the new address was taken in the meantime. The pair is gone. + Refused, +} + +fn map_link(row: &turso::Row) -> Result { + Ok(AccountLink { + user_id: col_text(row, 0)?, + kind: col_text(row, 1)?, + pair_id: col_opt_text(row, 2)?, + new_email: col_opt_text(row, 3)?, + expires_at: col_text(row, 4)?, + }) +} + +const LINK_COLS: &str = "l.user_id, l.kind, l.pair_id, l.new_email, l.expires_at"; + +/// Marks every pending link of `user_id` as used, so none of them works any more. Runs inside the +/// caller's transaction. +pub(crate) async fn invalidate_links(conn: &Connection, user_id: &str, now: &str) -> Result<()> { + conn.execute( + "UPDATE account_links SET used_at = ?2 WHERE user_id = ?1 AND used_at IS NULL", + (user_id.to_string(), now.to_string()), + ) + .await + .map_err(db_err)?; + Ok(()) +} + +impl Store { + /// Creates a password-reset link. Older pending reset links of the person stop working. The + /// caller has checked that the person exists and is not disabled. + pub async fn create_reset_link( + &self, + user_id: &str, + token_hash: &str, + expires_at: &str, + ) -> Result<()> { + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + tx.execute( + "UPDATE account_links SET used_at = ?2 \ + WHERE user_id = ?1 AND kind = 'reset' AND used_at IS NULL", + (user_id.to_string(), now.clone()), + ) + .await + .map_err(db_err)?; + tx.execute( + "INSERT INTO account_links (token_hash, kind, user_id, created_at, expires_at) \ + VALUES (?1, 'reset', ?2, ?3, ?4)", + ( + token_hash.to_string(), + user_id.to_string(), + now, + expires_at.to_string(), + ), + ) + .await + .map_err(db_err)?; + Ok(()) + } + .await; + finish(tx, outcome).await + } + + /// A usable link of one of the given kinds, with its person enabled. `kinds` are the stored kinds. + async fn live_link(&self, token_hash: &str, kinds: &[&str]) -> Result> { + let list = kinds + .iter() + .map(|k| format!("'{k}'")) + .collect::>() + .join(", "); + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!( + "SELECT {LINK_COLS} FROM account_links l JOIN users u ON u.id = l.user_id \ + WHERE l.token_hash = ?1 AND l.kind IN ({list}) AND l.used_at IS NULL \ + AND l.expires_at > ?2 AND u.disabled_at IS NULL" + ), + (token_hash.to_string(), now_stamp()), + map_link, + ) + .await + } + + /// A usable password-reset link, or `None`. + pub async fn live_reset_link(&self, token_hash: &str) -> Result> { + self.live_link(token_hash, &["reset"]).await + } + + /// A usable half of an email change, or `None`. + pub async fn live_email_link(&self, token_hash: &str) -> Result> { + self.live_link(token_hash, &["email_old", "email_new"]) + .await + } + + /// Spends a password-reset link and sets the new password, in one transaction. + /// + /// The conditional update of the link comes first; if it touches nothing, the link was used, + /// expired or belongs to a disabled person, and nothing else changes. Otherwise the password is + /// replaced, every other pending link of the person is invalidated, and every session of the person + /// is ended with its back-channel logouts. Returns the person id, or `None` when the link was not + /// usable. The caller has checked the policy and that the password differs from the old one. + pub async fn redeem_reset_link( + &self, + token_hash: &str, + password_hash: &str, + ) -> Result> { + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result> = async { + let user_id = fetch_opt( + &tx, + "SELECT user_id FROM account_links WHERE token_hash = ?1 AND kind = 'reset'", + (token_hash.to_string(),), + |row| col_text(row, 0), + ) + .await?; + let Some(user_id) = user_id else { + return Ok(None); + }; + let spent = tx + .execute( + "UPDATE account_links SET used_at = ?2 \ + WHERE token_hash = ?1 AND kind = 'reset' AND used_at IS NULL AND expires_at > ?2 \ + AND user_id IN (SELECT id FROM users WHERE disabled_at IS NULL)", + (token_hash.to_string(), now.clone()), + ) + .await + .map_err(db_err)?; + if spent != 1 { + return Ok(None); + } + tx.execute( + "UPDATE users SET password_hash = ?2, updated_at = ?3 WHERE id = ?1", + (user_id.clone(), password_hash.to_string(), now.clone()), + ) + .await + .map_err(db_err)?; + invalidate_links(&tx, &user_id, &now).await?; + end_all_sessions(&tx, &user_id, EndReason::PasswordChanged, &now).await?; + Ok(Some(user_id)) + } + .await; + finish(tx, outcome).await + } + + /// Starts an email change: two links, one for each address, sharing a pair id. Older pending email + /// links of the person stop working. Fails with a conflict when `new_email` belongs to an account. + /// `expires_at` is the same for both halves. + pub async fn start_email_change( + &self, + user_id: &str, + new_email_folded: &str, + old_token_hash: &str, + new_token_hash: &str, + expires_at: &str, + ) -> Result<()> { + let now = now_stamp(); + let pair = new_id(); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let taken = fetch_opt( + &tx, + "SELECT 1 FROM users WHERE email_folded = ?1", + (new_email_folded.to_string(),), + |_row| Ok(()), + ) + .await?; + if taken.is_some() { + return Err(Error::Conflict( + "that email address cannot be used".into(), + )); + } + invalidate_links_of_kinds(&tx, user_id, &now).await?; + for (token_hash, kind) in [(old_token_hash, "email_old"), (new_token_hash, "email_new")] { + tx.execute( + "INSERT INTO account_links (token_hash, kind, user_id, pair_id, new_email, created_at, expires_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + ( + token_hash.to_string(), + kind, + user_id.to_string(), + pair.clone(), + new_email_folded.to_string(), + now.clone(), + expires_at.to_string(), + ), + ) + .await + .map_err(db_err)?; + } + Ok(()) + } + .await; + finish(tx, outcome).await + } + + /// Confirms one half of an email change. When this makes both halves confirmed, the address is + /// changed in the same transaction, unless the new address has been taken since the request. In + /// that case the pair is deleted and the answer is [`EmailConfirm::Refused`]. + pub async fn confirm_email_link(&self, token_hash: &str) -> Result { + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let link = fetch_opt( + &tx, + &format!( + "SELECT {LINK_COLS} FROM account_links l JOIN users u ON u.id = l.user_id \ + WHERE l.token_hash = ?1 AND l.kind IN ('email_old', 'email_new') \ + AND l.used_at IS NULL AND l.expires_at > ?2 AND u.disabled_at IS NULL" + ), + (token_hash.to_string(), now.clone()), + map_link, + ) + .await?; + let Some(link) = link else { + return Ok(EmailConfirm::Refused); + }; + let pair = link.pair_id.clone().ok_or(Error::NotFound)?; + let new_email = link.new_email.clone().ok_or(Error::NotFound)?; + tx.execute( + "UPDATE account_links SET used_at = ?2 WHERE token_hash = ?1 AND used_at IS NULL", + (token_hash.to_string(), now.clone()), + ) + .await + .map_err(db_err)?; + let confirmed = fetch_opt( + &tx, + "SELECT COUNT(*) FROM account_links WHERE pair_id = ?1 AND used_at IS NOT NULL", + (pair.clone(),), + |row| crate::store::col_int(row, 0), + ) + .await? + .unwrap_or(0); + if confirmed < 2 { + return Ok(EmailConfirm::Waiting); + } + + // Both halves are in. The address must still be free: it may have been registered since. + let taken = fetch_opt( + &tx, + "SELECT 1 FROM users WHERE email_folded = ?1 AND id <> ?2", + (new_email.clone(), link.user_id.clone()), + |_row| Ok(()), + ) + .await?; + if taken.is_some() { + tx.execute("DELETE FROM account_links WHERE pair_id = ?1", (pair,)) + .await + .map_err(db_err)?; + return Ok(EmailConfirm::Refused); + } + let old_email = fetch_opt( + &tx, + "SELECT email FROM users WHERE id = ?1", + (link.user_id.clone(),), + |row| col_text(row, 0), + ) + .await? + .ok_or(Error::NotFound)?; + tx.execute( + "UPDATE users SET email = ?2, email_folded = ?2, updated_at = ?3 WHERE id = ?1", + (link.user_id.clone(), new_email.clone(), now.clone()), + ) + .await + .map_err(insert_error)?; + record_change(&tx, &link.user_id, ChangeKind::Member).await?; + invalidate_links(&tx, &link.user_id, &now).await?; + Ok(EmailConfirm::Applied { + user_id: link.user_id, + old_email, + new_email, + }) + } + .await; + let result = finish(tx, outcome).await; + drop(conn); + if matches!(result, Ok(EmailConfirm::Applied { .. })) { + self.announce_directory(); + } + result + } + + /// Cancels an email change from one of its links: both halves are deleted. Returns the person id + /// when the link was usable, else `None`. + pub async fn cancel_email_change(&self, token_hash: &str) -> Result> { + let Some(link) = self.live_email_link(token_hash).await? else { + return Ok(None); + }; + let Some(pair) = link.pair_id else { + return Ok(None); + }; + let conn = self.inner.conn.lock().await; + conn.execute("DELETE FROM account_links WHERE pair_id = ?1", (pair,)) + .await + .map_err(db_err)?; + Ok(Some(link.user_id)) + } + + /// Deletes links that have expired. Returns how many were removed. Run by the sweeper. + pub async fn sweep_links(&self, now: &str) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM account_links WHERE expires_at <= ?1", + (now.to_string(),), + ) + .await + .map_err(db_err) + } +} + +/// Invalidates the pending email-change links of `user_id` (not its reset links). Runs inside a +/// transaction. +async fn invalidate_links_of_kinds(conn: &Connection, user_id: &str, now: &str) -> Result<()> { + conn.execute( + "UPDATE account_links SET used_at = ?2 \ + WHERE user_id = ?1 AND kind IN ('email_old', 'email_new') AND used_at IS NULL", + (user_id.to_string(), now.to_string()), + ) + .await + .map_err(db_err)?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::time::stamp_after; + use std::time::Duration; + + async fn setup() -> (tempfile::TempDir, Store, String) { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("im.db")).await.unwrap(); + let user = store + .create_user("ada@example.com", "Ada", "old-hash", false) + .await + .unwrap(); + (dir, store, user.id) + } + + #[tokio::test] + async fn a_reset_link_works_once() { + let (_dir, store, user_id) = setup().await; + store + .create_reset_link( + &user_id, + "reset-hash", + &stamp_after(Duration::from_secs(3600)), + ) + .await + .unwrap(); + assert!(store.live_reset_link("reset-hash").await.unwrap().is_some()); + let first = store + .redeem_reset_link("reset-hash", "new-hash") + .await + .unwrap(); + assert_eq!(first.as_deref(), Some(user_id.as_str())); + // Reuse is refused, and the password is not touched a second time. + let second = store + .redeem_reset_link("reset-hash", "other-hash") + .await + .unwrap(); + assert_eq!(second, None); + let user = store.user_by_id(&user_id).await.unwrap().unwrap(); + assert_eq!(user.password_hash, "new-hash"); + } + + #[tokio::test] + async fn an_email_change_is_refused_when_the_address_was_taken_before_confirm() { + let (_dir, store, user_id) = setup().await; + let later = stamp_after(Duration::from_secs(3600)); + store + .start_email_change(&user_id, "ada.new@example.com", "h-old", "h-new", &later) + .await + .unwrap(); + // Someone else registers the new address before either half is confirmed. + store + .create_user("ada.new@example.com", "Other", "hash", false) + .await + .unwrap(); + assert_eq!( + store.confirm_email_link("h-old").await.unwrap(), + EmailConfirm::Waiting + ); + assert_eq!( + store.confirm_email_link("h-new").await.unwrap(), + EmailConfirm::Refused + ); + let user = store.user_by_id(&user_id).await.unwrap().unwrap(); + assert_eq!(user.email, "ada@example.com"); + // The pair is gone, so the old half cannot be used again. + assert!(store.live_email_link("h-old").await.unwrap().is_none()); + } +} diff --git a/crates/im-core/src/store/mail.rs b/crates/im-core/src/store/mail.rs new file mode 100644 index 0000000..3a3feb3 --- /dev/null +++ b/crates/im-core/src/store/mail.rs @@ -0,0 +1,245 @@ +//! The mail outbox: rows the mail worker sends, with their retry state. +//! +//! A row keeps its body sealed under the instance key (the body can hold a single-use link). The worker +//! opens it only to send. Once a row is sent or abandoned its body is blanked, so a token-bearing body +//! survives only until its first delivery attempt succeeds or the row gives up. Sent rows are deleted +//! 30 days after they were sent. Nothing here logs a body or a recipient. + +use crate::error::Result; +use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; +use crate::time::now_stamp; + +/// What a new outbox row holds. +#[derive(Debug, Clone, Copy)] +pub struct NewMail<'a> { + /// The kind, one of the values the schema allows. + pub kind: &'a str, + /// The recipient address. Already validated by the caller. + pub to_addr: &'a str, + /// The subject. Built from fixed text only. + pub subject: &'a str, + /// The body, sealed with `secret::seal`. + pub sealed_body: &'a str, +} + +/// One row the worker should try now. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MailJob { + /// ULID. + pub id: String, + /// The kind of the mail. + pub kind: String, + /// The recipient address. + pub to_addr: String, + /// The subject. + pub subject: String, + /// The sealed body. Empty when the row was already blanked, which the worker treats as corrupt. + pub sealed_body: String, + /// Attempts made so far. + pub attempts: i64, +} + +/// The outcome the worker reports for one attempt. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum MailAttempt { + /// Delivered. The body is blanked. + Sent, + /// Failed, and another attempt is scheduled at `next_at`. + Retry { + /// The stamp of the next attempt. + next_at: String, + /// A short reason for the operator. Never contains the body. + error: String, + }, + /// Failed for the last time. The body is blanked. + Abandon { + /// A short reason for the operator. + error: String, + }, +} + +/// The fields of one outbox row that the admin pages and the tests read. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MailRow { + /// The kind of the mail. + pub kind: String, + /// `pending`, `sent`, `failed` or `abandoned`. + pub state: String, + /// Attempts made so far. + pub attempts: i64, + /// The stamp of the next attempt. + pub next_attempt_at: String, + /// The reason of the last failure, if any. + pub last_error: Option, +} + +fn map_job(row: &turso::Row) -> Result { + Ok(MailJob { + id: col_text(row, 0)?, + kind: col_text(row, 1)?, + to_addr: col_text(row, 2)?, + subject: col_text(row, 3)?, + sealed_body: col_text(row, 4)?, + attempts: col_int(row, 5)?, + }) +} + +impl Store { + /// Adds a mail to the outbox, to be sent as soon as the worker looks. Returns its id. + pub async fn enqueue_mail(&self, new: &NewMail<'_>) -> Result { + let id = new_id(); + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT INTO mail_outbox (id, kind, to_addr, subject, body_text, state, attempts, \ + next_attempt_at, created_at) VALUES (?1, ?2, ?3, ?4, ?5, 'pending', 0, ?6, ?6)", + ( + id.clone(), + new.kind.to_string(), + new.to_addr.to_string(), + new.subject.to_string(), + new.sealed_body.to_string(), + now, + ), + ) + .await + .map_err(db_err)?; + Ok(id) + } + + /// Rows that are due: never tried, or failed and whose retry time has come. Oldest first. + pub async fn due_mail(&self, now: &str, limit: i64) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT id, kind, to_addr, subject, body_text, attempts FROM mail_outbox \ + WHERE state IN ('pending', 'failed') AND next_attempt_at <= ?1 \ + ORDER BY next_attempt_at, id LIMIT ?2", + (now.to_string(), limit), + map_job, + ) + .await + } + + /// Records the outcome of one attempt. The attempt count goes up by one in the same statement. + /// A sent or abandoned row loses its body in that statement too. + pub async fn record_mail_attempt(&self, id: &str, attempt: &MailAttempt) -> Result<()> { + let conn = self.inner.conn.lock().await; + let now = now_stamp(); + let outcome = match attempt { + MailAttempt::Sent => { + conn.execute( + "UPDATE mail_outbox SET state = 'sent', attempts = attempts + 1, sent_at = ?2, \ + body_text = '', last_error = NULL WHERE id = ?1", + (id.to_string(), now), + ) + .await + } + MailAttempt::Retry { next_at, error } => { + conn.execute( + "UPDATE mail_outbox SET state = 'failed', attempts = attempts + 1, \ + next_attempt_at = ?2, last_error = ?3 WHERE id = ?1", + (id.to_string(), next_at.clone(), error.clone()), + ) + .await + } + MailAttempt::Abandon { error } => { + conn.execute( + "UPDATE mail_outbox SET state = 'abandoned', attempts = attempts + 1, \ + body_text = '', last_error = ?2 WHERE id = ?1", + (id.to_string(), error.clone()), + ) + .await + } + }; + outcome.map_err(db_err)?; + Ok(()) + } + + /// The fields of one row, or `None`. + pub async fn mail_row(&self, id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + "SELECT kind, state, attempts, next_attempt_at, last_error FROM mail_outbox WHERE id = ?1", + (id.to_string(),), + |row| { + Ok(MailRow { + kind: col_text(row, 0)?, + state: col_text(row, 1)?, + attempts: col_int(row, 2)?, + next_attempt_at: col_text(row, 3)?, + last_error: col_opt_text(row, 4)?, + }) + }, + ) + .await + } + + /// Deletes sent rows sent before `cutoff`. Returns how many were removed. Run by the sweeper. + pub async fn prune_sent_mail(&self, cutoff: &str) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM mail_outbox WHERE state = 'sent' AND sent_at < ?1", + (cutoff.to_string(),), + ) + .await + .map_err(db_err) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn a_failed_attempt_is_retried_and_the_last_one_blanks_the_body() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("im.db")).await.unwrap(); + let id = store + .enqueue_mail(&NewMail { + kind: "reset", + to_addr: "ada@example.com", + subject: "Reset", + sealed_body: "v1:sealed", + }) + .await + .unwrap(); + let now = now_stamp(); + assert_eq!(store.due_mail(&now, 10).await.unwrap().len(), 1); + store + .record_mail_attempt( + &id, + &MailAttempt::Retry { + next_at: crate::time::stamp_after(std::time::Duration::from_secs(60)), + error: "connection refused".into(), + }, + ) + .await + .unwrap(); + assert!(store.due_mail(&now, 10).await.unwrap().is_empty()); + let row = store.mail_row(&id).await.unwrap().unwrap(); + assert_eq!((row.state.as_str(), row.attempts), ("failed", 1)); + store + .record_mail_attempt( + &id, + &MailAttempt::Abandon { + error: "gave up".into(), + }, + ) + .await + .unwrap(); + let row = store.mail_row(&id).await.unwrap().unwrap(); + assert_eq!((row.state.as_str(), row.attempts), ("abandoned", 2)); + assert!( + store + .due_mail( + &crate::time::stamp_after(std::time::Duration::from_secs(3600)), + 10 + ) + .await + .unwrap() + .is_empty() + ); + } +} diff --git a/crates/im-core/src/store/mod.rs b/crates/im-core/src/store/mod.rs index 3870e6b..f09e3e2 100644 --- a/crates/im-core/src/store/mod.rs +++ b/crates/im-core/src/store/mod.rs @@ -10,7 +10,10 @@ pub mod audit; pub mod backchannel; pub mod clients; pub mod directory; +pub mod invites; pub mod keys; +pub mod links; +pub mod mail; pub mod migrate; pub mod oidc; pub mod services; diff --git a/crates/im-core/src/store/sessions.rs b/crates/im-core/src/store/sessions.rs index a8284a5..9327026 100644 --- a/crates/im-core/src/store/sessions.rs +++ b/crates/im-core/src/store/sessions.rs @@ -132,6 +132,25 @@ pub(crate) async fn end_rows( Ok(()) } +/// Ends every session of `user_id`, whatever its expiry, with the same back-channel rows as any other +/// end. Used when the password is reset. Runs inside the caller's transaction and returns the ids. +pub(crate) async fn end_all_sessions( + conn: &Connection, + user_id: &str, + reason: EndReason, + now: &str, +) -> Result> { + let ids = fetch_all( + conn, + "SELECT id FROM sessions WHERE user_id = ?1 ORDER BY created_at ASC, id ASC", + (user_id.to_string(),), + |row| col_text(row, 0), + ) + .await?; + end_rows(conn, user_id, &ids, reason, now).await?; + Ok(ids) +} + impl Store { /// Creates a session for a user who has just proved who they are. /// diff --git a/crates/im-core/src/store/users.rs b/crates/im-core/src/store/users.rs index 061edb6..4450fa6 100644 --- a/crates/im-core/src/store/users.rs +++ b/crates/im-core/src/store/users.rs @@ -53,7 +53,7 @@ pub(crate) fn map_user(row: &Row) -> Result { /// Maps an insert error. A UNIQUE violation is a conflict for the person; anything else is a /// database failure. -fn insert_error(e: turso::Error) -> Error { +pub(crate) fn insert_error(e: turso::Error) -> Error { let text = e.to_string(); if text.contains("UNIQUE") { Error::Conflict("that email address is already registered".into()) diff --git a/crates/im-web/Cargo.toml b/crates/im-web/Cargo.toml index 1b9c977..cfc65c2 100644 --- a/crates/im-web/Cargo.toml +++ b/crates/im-web/Cargo.toml @@ -14,6 +14,7 @@ base64.workspace = true futures-util.workspace = true http.workspace = true im-core.workspace = true +lettre.workspace = true qrcode.workspace = true reqwest.workspace = true serde.workspace = true diff --git a/crates/im-web/src/boot.rs b/crates/im-web/src/boot.rs index 7f41288..4ef1216 100644 --- a/crates/im-web/src/boot.rs +++ b/crates/im-web/src/boot.rs @@ -23,6 +23,7 @@ use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService use crate::api::directory::StreamSlots; use crate::backchannel; use crate::live::LiveHub; +use crate::mail; use crate::oidc::signing; use crate::pages::not_found::NotFoundLayer; use crate::pages::profile::PHOTO_ROUTE; @@ -95,6 +96,12 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { stop_rx.clone(), ); let sweeper_task = sweeper::spawn(state.store.clone(), stop_rx.clone()); + let mail_worker = mail::worker::spawn( + state.store.clone(), + state.key.clone(), + state.config.smtp.clone(), + stop_rx.clone(), + ); topcoat::serve_until( listener, @@ -105,6 +112,7 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { let _ = signing_worker.await; let _ = backchannel_worker.await; let _ = sweeper_task.await; + let _ = mail_worker.await; tracing::info!("im stopped"); Ok(()) } diff --git a/crates/im-web/src/i18n/account.rs b/crates/im-web/src/i18n/account.rs index 6259408..df98268 100644 --- a/crates/im-web/src/i18n/account.rs +++ b/crates/im-web/src/i18n/account.rs @@ -484,10 +484,10 @@ pub fn text(lang: Lang, key: Txt) -> &'static str { (Txt::PhotoOfPerson, Lang::En) => "Photo of this person", (Txt::PhotoOfPerson, Lang::Tr) => "Bu kişinin fotoğrafı", (Txt::EmailLaterNote, Lang::En) => { - "Changing your email address is not available yet. It will need a confirmation link sent to both addresses." + "To change it, use the link below. Both the current and the new address get a confirmation link." } (Txt::EmailLaterNote, Lang::Tr) => { - "E-posta adresinizi değiştirme henüz kullanılamıyor. İki adrese de onay bağlantısı gönderilecek." + "Adresi değiştirmek için aşağıdaki bağlantıyı kullanın. Mevcut ve yeni adresinize birer onay bağlantısı gönderilir." } (Txt::SavedName, Lang::En) => "Your name was saved.", (Txt::SavedName, Lang::Tr) => "Adınız kaydedildi.", diff --git a/crates/im-web/src/i18n/flows.rs b/crates/im-web/src/i18n/flows.rs new file mode 100644 index 0000000..fe32bcc --- /dev/null +++ b/crates/im-web/src/i18n/flows.rs @@ -0,0 +1,201 @@ +//! Strings of the pages that run outside a session: forgot password, reset, invitation, the admin +//! invitation form, and the email change pages. Each key has an English and a Turkish text in [`text`]; +//! the match is exhaustive. Shared phrases (email, password, policy messages) come from `account.rs`. + +use super::Lang; + +/// One phrase of the flow pages. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Flow { + /// Title of the forgot-password page, and of its link on the sign-in page. + ForgotTitle, + /// The sentence under the forgot-password title. + ForgotIntro, + /// The answer after any request. The same for known and unknown addresses. + ForgotSent, + /// The button that asks for the link. + ForgotSubmit, + /// The link back to sign-in. + BackToSignIn, + /// Title of the reset page. + ResetTitle, + /// The sentence under the reset title. + ResetIntro, + /// The button that sets the new password. + ResetSubmit, + /// Shown after a reset when the account has two-factor sign-in: it must sign in again with a code. + /// Shown on the invitation page. + InviteTitle, + /// The sentence under the invitation title. + InviteIntro, + /// The button that creates the account. + InviteSubmit, + /// Title of the administrator invitation page. + AdminInvitesTitle, + /// The sentence under that title. + AdminInvitesIntro, + /// Checkbox: the invitee becomes an administrator. + InviteAsAdmin, + /// The button that sends the invitation. + InviteSend, + /// Notice after an invitation was queued. + InviteQueued, + /// Alert: the address already has an account. + InviteAddressTaken, + /// The profile link to the email change page. + ChangeEmailLink, + /// Title of the email change request page. + EmailChangeTitle, + /// The sentence under that title. + EmailChangeIntro, + /// Label of the current address (read only). + CurrentAddress, + /// Label of the new address. + NewAddress, + /// The button that sends both links. + EmailChangeSubmit, + /// Notice after both links were queued. + 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. + EmailLinkConfirm, + /// The button that cancels the whole change. + EmailLinkCancel, + /// Sentence under the confirm and cancel buttons. + EmailLinkNote, + /// Shown after this half is confirmed while the other half is still open. + EmailLinkWaiting, + /// Shown when the address changed. + EmailLinkDone, + /// Shown when the change was cancelled. + EmailLinkCancelled, + /// Shown when the change can no longer be applied (the address was taken meanwhile). + EmailLinkRefused, +} + +/// The text of `key` in `lang`. +pub fn text(lang: Lang, key: Flow) -> &'static str { + match (key, lang) { + (Flow::ForgotTitle, Lang::En) => "Forgot your password?", + (Flow::ForgotTitle, Lang::Tr) => "Parolanızı mı unuttunuz?", + (Flow::ForgotIntro, Lang::En) => { + "Enter the address of your account. If an account exists for it, we send a link to choose a new password." + } + (Flow::ForgotIntro, Lang::Tr) => { + "Hesabınızın adresini girin. Bu adrese ait bir hesap varsa yeni parola seçmeniz için bir bağlantı göndeririz." + } + (Flow::ForgotSent, Lang::En) => { + "If an account exists for that address, a link is on its way. Check your mail." + } + (Flow::ForgotSent, Lang::Tr) => { + "Bu adrese ait bir hesap varsa bağlantı yolda. Posta kutunuzu kontrol edin." + } + (Flow::ForgotSubmit, Lang::En) => "Send the link", + (Flow::ForgotSubmit, Lang::Tr) => "Bağlantıyı gönder", + (Flow::BackToSignIn, Lang::En) => "Back to sign-in", + (Flow::BackToSignIn, Lang::Tr) => "Girişe dön", + (Flow::ResetTitle, Lang::En) => "Choose a new password", + (Flow::ResetTitle, Lang::Tr) => "Yeni bir parola seçin", + (Flow::ResetIntro, Lang::En) => { + "Set a new password for your account. The link works only once, and every signed-in session ends when you save." + } + (Flow::ResetIntro, Lang::Tr) => { + "Hesabınız için yeni bir parola belirleyin. Bağlantı yalnız bir kez çalışır ve kaydettiğinizde tüm açık oturumlar kapanır." + } + (Flow::ResetSubmit, Lang::En) => "Save the new password", + (Flow::ResetSubmit, Lang::Tr) => "Yeni parolayı kaydet", + (Flow::InviteTitle, Lang::En) => "Join im", + (Flow::InviteTitle, Lang::Tr) => "im'e katılın", + (Flow::InviteIntro, Lang::En) => { + "An administrator invited you. Choose your name and a password to create your account." + } + (Flow::InviteIntro, Lang::Tr) => { + "Bir yönetici sizi davet etti. Hesabınızı oluşturmak için adınızı ve bir parola seçin." + } + (Flow::InviteSubmit, Lang::En) => "Create my account", + (Flow::InviteSubmit, Lang::Tr) => "Hesabımı oluştur", + (Flow::AdminInvitesTitle, Lang::En) => "Invitations", + (Flow::AdminInvitesTitle, Lang::Tr) => "Davetler", + (Flow::AdminInvitesIntro, Lang::En) => { + "Send an invitation to an address. The person chooses their own name and password." + } + (Flow::AdminInvitesIntro, Lang::Tr) => { + "Bir adrese davet gönderin. Kişi kendi adını ve parolasını seçer." + } + (Flow::InviteAsAdmin, Lang::En) => "Make this person an administrator", + (Flow::InviteAsAdmin, Lang::Tr) => "Bu kişiyi yönetici yap", + (Flow::InviteSend, Lang::En) => "Send the invitation", + (Flow::InviteSend, Lang::Tr) => "Daveti gönder", + (Flow::InviteQueued, Lang::En) => "The invitation was queued for sending.", + (Flow::InviteQueued, Lang::Tr) => "Davet gönderilmek üzere kuyruğa alındı.", + (Flow::InviteAddressTaken, Lang::En) => "That address already has an account.", + (Flow::InviteAddressTaken, Lang::Tr) => "Bu adrese ait bir hesap zaten var.", + (Flow::ChangeEmailLink, Lang::En) => "Change email address", + (Flow::ChangeEmailLink, Lang::Tr) => "E-posta adresini değiştir", + (Flow::EmailChangeTitle, Lang::En) => "Change email address", + (Flow::EmailChangeTitle, Lang::Tr) => "E-posta adresini değiştir", + (Flow::EmailChangeIntro, Lang::En) => { + "We send a link to the current address and one to the new address. The change happens when both are confirmed." + } + (Flow::EmailChangeIntro, Lang::Tr) => { + "Mevcut adresinize ve yeni adresinize birer bağlantı göndeririz. İkisi de onaylanınca değişiklik gerçekleşir." + } + (Flow::CurrentAddress, Lang::En) => "Current address", + (Flow::CurrentAddress, Lang::Tr) => "Mevcut adres", + (Flow::NewAddress, Lang::En) => "New email address", + (Flow::NewAddress, Lang::Tr) => "Yeni e-posta adresi", + (Flow::EmailChangeSubmit, Lang::En) => "Send the links", + (Flow::EmailChangeSubmit, Lang::Tr) => "Bağlantıları gönder", + (Flow::EmailChangeQueued, Lang::En) => { + "Links are on their way to both addresses. The change happens when both are confirmed." + } + (Flow::EmailChangeQueued, Lang::Tr) => { + "Her iki adrese de bağlantılar yolda. İkisi de onaylanınca değişiklik gerçekleşir." + } + (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", + (Flow::EmailLinkConfirm, Lang::Tr) => "Onayla", + (Flow::EmailLinkCancel, Lang::En) => "Cancel the change", + (Flow::EmailLinkCancel, Lang::Tr) => "Değişikliği iptal et", + (Flow::EmailLinkNote, Lang::En) => { + "If this was not you, cancel the change and then change your password." + } + (Flow::EmailLinkNote, Lang::Tr) => { + "Bunu siz istemediyseniz değişikliği iptal edin ve sonra parolanızı değiştirin." + } + (Flow::EmailLinkWaiting, Lang::En) => { + "Thank you. The change happens when the other address is confirmed too." + } + (Flow::EmailLinkWaiting, Lang::Tr) => { + "Teşekkürler. Diğer adres de onaylanınca değişiklik gerçekleşir." + } + (Flow::EmailLinkDone, Lang::En) => "The address of your account has changed.", + (Flow::EmailLinkDone, Lang::Tr) => "Hesabınızın adresi değişti.", + (Flow::EmailLinkCancelled, Lang::En) => "The change was cancelled.", + (Flow::EmailLinkCancelled, Lang::Tr) => "Değişiklik iptal edildi.", + (Flow::EmailLinkRefused, Lang::En) => { + "This change can no longer be completed. Start it again from your account." + } + (Flow::EmailLinkRefused, Lang::Tr) => { + "Bu değişiklik artık tamamlanamaz. Hesabınızdan yeniden başlatın." + } + } +} + +/// The sentence on the link page that says what changes, with both addresses. +pub fn email_link_summary(lang: Lang, old: &str, new: &str) -> String { + match lang { + Lang::En => format!("The address of the account changes from {old} to {new}."), + Lang::Tr => format!("Hesabın adresi {old} adresinden {new} adresine değişiyor."), + } +} diff --git a/crates/im-web/src/i18n/mail.rs b/crates/im-web/src/i18n/mail.rs new file mode 100644 index 0000000..cc47827 --- /dev/null +++ b/crates/im-web/src/i18n/mail.rs @@ -0,0 +1,204 @@ +//! Strings of the mail: subjects, the fixed sentences of each body, and the sentences with a value. +//! +//! Every key has an English and a Turkish text in [`text`]; the match is exhaustive, so a key without a +//! translation does not compile. Sentences with values (a day count, a new address) are built by the +//! helpers below, one format string per language, so word order is each language's own. + +use super::Lang; + +/// One fixed sentence or subject of a mail. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MailKey { + /// The closing line of every mail. + Signature, + /// Under a link the person did not ask for. + Ignore, + /// Subject of the invitation. + InviteSubject, + /// Label of the invitation link. + InviteAction, + /// Subject of the password-reset mail. + ResetSubject, + /// Label of the reset link. + ResetAction, + /// Sentence after the reset link, about what the reset does. + ResetNote, + /// Subject of the notice to the old address. + EmailOldSubject, + /// Label of the link on the old-address mail. + EmailOldAction, + /// Sentence after the old-address link: what to do if it was not the person. + EmailOldNote, + /// Subject of the confirmation to the new address. + EmailNewSubject, + /// Label of the link on the new-address mail. + EmailNewAction, + /// Subject of the notice that the address changed. + EmailDoneSubject, + /// Subject: the password was changed by the person. + PasswordChangedSubject, + /// Body: the password was changed by the person. + PasswordChangedBody, + /// Subject: the password was reset through a link. + PasswordResetSubject, + /// Body: the password was reset through a link. + PasswordResetBody, + /// Subject: two-factor sign-in was turned on. + TwoFactorOnSubject, + /// Body: two-factor sign-in was turned on. + TwoFactorOnBody, + /// Subject: two-factor sign-in was turned off. + TwoFactorOffSubject, + /// Body: two-factor sign-in was turned off. + TwoFactorOffBody, + /// Subject: new recovery codes were generated. + RecoveryCodesSubject, + /// Body: new recovery codes were generated. + RecoveryCodesBody, + /// The line under every security notice. + SecurityNote, +} + +/// The text of `key` in `lang`. +pub fn text(lang: Lang, key: MailKey) -> &'static str { + match (key, lang) { + (MailKey::Signature, Lang::En) => "im, your family account service", + (MailKey::Signature, Lang::Tr) => "im, aile hesap hizmetiniz", + (MailKey::Ignore, Lang::En) => "If you did not expect this message, you can ignore it.", + (MailKey::Ignore, Lang::Tr) => "Bu iletiyi beklemiyorsanız yok sayabilirsiniz.", + (MailKey::InviteSubject, Lang::En) => "You are invited to im", + (MailKey::InviteSubject, Lang::Tr) => "im'e davet edildiniz", + (MailKey::InviteAction, Lang::En) => "Create your account", + (MailKey::InviteAction, Lang::Tr) => "Hesabınızı oluşturun", + (MailKey::ResetSubject, Lang::En) => "Reset your im password", + (MailKey::ResetSubject, Lang::Tr) => "im parolanızı sıfırlayın", + (MailKey::ResetAction, Lang::En) => "Choose a new password", + (MailKey::ResetAction, Lang::Tr) => "Yeni bir parola seçin", + (MailKey::ResetNote, Lang::En) => { + "When the password is set, every signed-in session of your account ends. If you did not ask for this, ignore this message: your password stays the same." + } + (MailKey::ResetNote, Lang::Tr) => { + "Parola belirlendiğinde hesabınızın tüm açık oturumları kapanır. Bunu siz istemediyseniz bu iletiyi yok sayın; parolanız değişmez." + } + (MailKey::EmailOldSubject, Lang::En) => { + "Confirm or cancel the email change on your im account" + } + (MailKey::EmailOldSubject, Lang::Tr) => { + "im hesabınızdaki e-posta değişikliğini onaylayın ya da iptal edin" + } + (MailKey::EmailOldAction, Lang::En) => "Review the change", + (MailKey::EmailOldAction, Lang::Tr) => "Değişikliği inceleyin", + (MailKey::EmailOldNote, Lang::En) => { + "If this was not you, open the link and cancel the change, then change your password." + } + (MailKey::EmailOldNote, Lang::Tr) => { + "Bunu siz istemediyseniz bağlantıyı açıp değişikliği iptal edin, sonra parolanızı değiştirin." + } + (MailKey::EmailNewSubject, Lang::En) => "Confirm this address for your im account", + (MailKey::EmailNewSubject, Lang::Tr) => "Bu adresi im hesabınız için onaylayın", + (MailKey::EmailNewAction, Lang::En) => "Confirm this address", + (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::PasswordChangedSubject, Lang::En) => "Your im password was changed", + (MailKey::PasswordChangedSubject, Lang::Tr) => "im parolanız değiştirildi", + (MailKey::PasswordChangedBody, Lang::En) => { + "The password of your account was changed. Your other signed-in sessions were ended." + } + (MailKey::PasswordChangedBody, Lang::Tr) => { + "Hesabınızın parolası değiştirildi. Diğer açık oturumlarınız kapatıldı." + } + (MailKey::PasswordResetSubject, Lang::En) => "Your im password was reset", + (MailKey::PasswordResetSubject, Lang::Tr) => "im parolanız sıfırlandı", + (MailKey::PasswordResetBody, Lang::En) => { + "The password of your account was reset with a link, and every session was ended." + } + (MailKey::PasswordResetBody, Lang::Tr) => { + "Hesabınızın parolası bir bağlantıyla sıfırlandı ve tüm oturumlar kapatıldı." + } + (MailKey::TwoFactorOnSubject, Lang::En) => "Two-factor sign-in was turned on", + (MailKey::TwoFactorOnSubject, Lang::Tr) => "İki adımlı giriş açıldı", + (MailKey::TwoFactorOnBody, Lang::En) => "Two-factor sign-in is now on for your account.", + (MailKey::TwoFactorOnBody, Lang::Tr) => "Hesabınızda iki adımlı giriş artık açık.", + (MailKey::TwoFactorOffSubject, Lang::En) => "Two-factor sign-in was turned off", + (MailKey::TwoFactorOffSubject, Lang::Tr) => "İki adımlı giriş kapatıldı", + (MailKey::TwoFactorOffBody, Lang::En) => "Two-factor sign-in is now off for your account.", + (MailKey::TwoFactorOffBody, Lang::Tr) => "Hesabınızda iki adımlı giriş artık kapalı.", + (MailKey::RecoveryCodesSubject, Lang::En) => "New recovery codes were generated", + (MailKey::RecoveryCodesSubject, Lang::Tr) => "Yeni kurtarma kodları üretildi", + (MailKey::RecoveryCodesBody, Lang::En) => { + "The recovery codes of your account were replaced. The old codes no longer work." + } + (MailKey::RecoveryCodesBody, Lang::Tr) => { + "Hesabınızın kurtarma kodları yenilendi. Eski kodlar artık çalışmaz." + } + (MailKey::SecurityNote, Lang::En) => "If this was not you, reset your password now.", + (MailKey::SecurityNote, Lang::Tr) => "Bunu siz yapmadıysanız hemen parolanızı sıfırlayın.", + } +} + +/// The opening word of a mail, addressed to `name` when there is one. +pub fn greeting(lang: Lang, name: Option<&str>) -> String { + match (lang, name) { + (Lang::En, Some(name)) => format!("Hello {name},"), + (Lang::En, None) => "Hello,".to_owned(), + (Lang::Tr, Some(name)) => format!("Merhaba {name},"), + (Lang::Tr, None) => "Merhaba,".to_owned(), + } +} + +/// The sentence of the invitation, with the number of days it lasts. +pub fn invite_body(lang: Lang, days: u32) -> String { + match lang { + Lang::En => format!( + "An administrator invited you to create an account. The link works for {days} days and only once." + ), + Lang::Tr => format!( + "Bir yönetici sizi bir hesap oluşturmaya davet etti. Bağlantı {days} gün boyunca ve yalnız bir kez geçerlidir." + ), + } +} + +/// The sentence of the reset mail, with the number of minutes the link lasts. +pub fn reset_body(lang: Lang, minutes: u32) -> String { + match lang { + Lang::En => format!( + "Someone asked to reset the password of your account. The link works for {minutes} minutes and only once." + ), + Lang::Tr => format!( + "Hesabınızın parolasını sıfırlamak için bir istek geldi. Bağlantı {minutes} dakika boyunca ve yalnız bir kez geçerlidir." + ), + } +} + +/// The sentence sent to the old address, naming the new one and the hours the links last. +pub fn email_old_body(lang: Lang, new_email: &str, hours: u32) -> String { + match lang { + Lang::En => format!( + "Someone asked to change the address of your account to {new_email}. The change happens only when the new address is confirmed too. The link works for {hours} hours." + ), + Lang::Tr => format!( + "Hesabınızın adresini {new_email} olarak değiştirmek için bir istek geldi. Değişiklik, yeni adres de onaylanınca gerçekleşir. Bağlantı {hours} saat boyunca geçerlidir." + ), + } +} + +/// The sentence sent to the new address. +pub fn email_new_body(lang: Lang, hours: u32) -> String { + match lang { + Lang::En => format!( + "Someone asked to use this address for an im account. Confirm it to finish the change. The link works for {hours} hours." + ), + Lang::Tr => format!( + "Bu adresin bir im hesabında kullanılması istendi. Değişikliği tamamlamak için onaylayın. Bağlantı {hours} saat boyunca geçerlidir." + ), + } +} + +/// The sentence that tells both addresses the change happened. +pub fn email_done_body(lang: Lang, new_email: &str) -> String { + match lang { + Lang::En => format!("The address of the account is now {new_email}."), + Lang::Tr => format!("Hesabın adresi artık {new_email}."), + } +} diff --git a/crates/im-web/src/i18n/mod.rs b/crates/im-web/src/i18n/mod.rs index 58ff418..9b3d215 100644 --- a/crates/im-web/src/i18n/mod.rs +++ b/crates/im-web/src/i18n/mod.rs @@ -8,6 +8,8 @@ //! helper functions next to their keys. pub mod account; +pub mod flows; +pub mod mail; pub mod oidc; pub mod shell; diff --git a/crates/im-web/src/mail/message.rs b/crates/im-web/src/mail/message.rs new file mode 100644 index 0000000..d57957a --- /dev/null +++ b/crates/im-web/src/mail/message.rs @@ -0,0 +1,138 @@ +//! The lettre message, built from typed parts only. +//! +//! A [`Recipient`] and a [`Sender`] can exist only after their name and address have passed the same +//! rules as the rest of `im`. A display name with a control character (a line break included) or a +//! bidirectional override is refused here, so no header can be injected through a name. The message +//! is then assembled by lettre's builder, which writes each header value itself. + +use im_core::config::SmtpConfig; +use im_core::names::{parse_display_name, parse_email}; +use lettre::Address; +use lettre::message::{Mailbox, Message, MultiPart}; + +/// A recipient whose name and address have been checked. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Recipient { + name: Option, + email: String, +} + +impl Recipient { + /// Checks a recipient. The name is optional; when given it must pass [`parse_display_name`]. The + /// address must pass [`parse_email`] and is stored in its normalised form. + pub fn new(name: Option<&str>, email: &str) -> Result { + let name = match name { + Some(name) => { + Some(parse_display_name(name).map_err(|_| "recipient name is not valid")?) + } + None => None, + }; + let email = parse_email(email).map_err(|_| "recipient address is not valid")?; + Ok(Self { name, email }) + } + + /// The checked display name, if any. + pub fn name(&self) -> Option<&str> { + self.name.as_deref() + } + + /// The checked address. + pub fn email(&self) -> &str { + &self.email + } + + fn mailbox(&self) -> Result { + let address: Address = self + .email + .parse() + .map_err(|_| "recipient address is not valid")?; + Ok(Mailbox::new(self.name.clone(), address)) + } +} + +/// The sender of every mail, from the SMTP section of the config. +#[derive(Debug, Clone)] +pub struct Sender { + mailbox: Mailbox, +} + +impl Sender { + /// The sender of the config. Fails when `from` or `from_name` is not valid; the config check rejects + /// those at boot, so this only guards a config built in code. + pub fn from_config(smtp: &SmtpConfig) -> Result { + let email = parse_email(&smtp.from).map_err(|_| "sender address is not valid")?; + let name = parse_display_name(&smtp.from_name).map_err(|_| "sender name is not valid")?; + let address: Address = email.parse().map_err(|_| "sender address is not valid")?; + Ok(Self { + mailbox: Mailbox::new(Some(name), address), + }) + } +} + +/// Builds a `multipart/alternative` message with a plain-text and an HTML part. The subject is the +/// only other text, and it comes from fixed strings. +pub fn build( + sender: &Sender, + to: &Recipient, + subject: &str, + text: String, + html: String, +) -> Result { + Message::builder() + .from(sender.mailbox.clone()) + .to(to.mailbox()?) + .subject(subject) + .multipart(MultiPart::alternative_plain_html(text, html)) + .map_err(|_| "message could not be built") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sender() -> Sender { + Sender::from_config(&SmtpConfig { + host: "127.0.0.1".into(), + from: "im@example.com".into(), + ..SmtpConfig::default() + }) + .expect("sender") + } + + #[test] + fn a_name_with_a_line_break_cannot_add_a_header() { + // The attack: a name that ends the To header and starts a Bcc header. + let attack = Recipient::new(Some("Ada\r\nBcc: victim@example.com"), "ada@example.com"); + assert!(attack.is_err()); + assert!(Recipient::new(Some("Ada\nBcc: x@example.com"), "ada@example.com").is_err()); + } + + #[test] + fn a_hard_name_is_encoded_and_the_headers_stay_clean() { + let to = Recipient::new(Some("Ada \"Lovelace\", Jr. Ayşe"), "ada@example.com") + .expect("valid name"); + let message = build( + &sender(), + &to, + "Subject", + "text".into(), + "

html

".into(), + ) + .expect("message"); + let raw = String::from_utf8_lossy(&message.formatted()).into_owned(); + let headers = raw.split("\r\n\r\n").next().unwrap_or_default(); + assert!(!headers.contains("Bcc:"), "{headers}"); + let to_lines = headers + .lines() + .filter(|line| line.starts_with("To:")) + .count(); + assert_eq!(to_lines, 1, "{headers}"); + assert_eq!( + headers + .lines() + .filter(|l| l.starts_with("Subject:")) + .count(), + 1 + ); + } +} diff --git a/crates/im-web/src/mail/mod.rs b/crates/im-web/src/mail/mod.rs new file mode 100644 index 0000000..61a6192 --- /dev/null +++ b/crates/im-web/src/mail/mod.rs @@ -0,0 +1,153 @@ +//! Outbound mail: what each mail says, how it is queued, and how the queue is sent. +//! +//! A mail is queued with [`queue`]: its text is rendered in the recipient's language, then sealed under the +//! instance key and stored in `mail_outbox` (architecture section 3). The worker in [`worker`] sends the +//! queued rows with retries. Nothing in this module logs a body, a link or a recipient address. +//! +//! - [`message`] builds the lettre message from typed parts only. A name or address that is not valid is +//! refused before any header is written, so no user text can add a header. +//! - [`templates`] renders the text and HTML of each kind. Every value goes through HTML escaping. +//! - [`transport`] builds the SMTP connection from the config, reading the password file each time. + +pub mod message; +pub mod templates; +pub mod transport; +pub mod worker; + +use im_core::Result; +use im_core::model::User; +use im_core::secret; +use im_core::store::Store; +use im_core::store::mail::NewMail; +use serde_json::json; + +use crate::i18n::Lang; +pub use message::Recipient; + +/// The security notices sent to the account's own address. Each is kind `security`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Notice { + /// The password was changed on the security page. + PasswordChanged, + /// The password was set through a reset link. + PasswordReset, + /// Two-factor sign-in was turned on. + TwoFactorOn, + /// Two-factor sign-in was turned off. + TwoFactorOff, + /// The recovery codes were replaced. + RecoveryCodes, +} + +/// One kind of mail, with the values its text needs. A link is already built by the caller. +#[derive(Clone, Copy, Debug)] +pub enum Mail<'a> { + /// An administrator invited the recipient to create an account. + Invite { + /// The invitation link. + link: &'a str, + /// Days the link lasts. + days: u32, + }, + /// A password reset was asked for. + Reset { + /// The reset link. + link: &'a str, + /// Minutes the link lasts. + minutes: u32, + }, + /// Sent to the current address of an email change, with the cancel-or-confirm link. + EmailOld { + /// The link of the old half. + link: &'a str, + /// The address the account would move to. + new_email: &'a str, + /// Hours the link lasts. + hours: u32, + }, + /// Sent to the new address of an email change. + EmailNew { + /// The link of the new half. + link: &'a str, + /// Hours the link lasts. + hours: u32, + }, + /// The change happened. Sent to both addresses. + EmailDone { + /// The address the account has now. + new_email: &'a str, + }, + /// A security notice. + Security(Notice), +} + +impl Mail<'_> { + /// The stored kind, one of the values `mail_outbox.kind` allows. + pub fn kind(&self) -> &'static str { + match self { + Mail::Invite { .. } => "invite", + Mail::Reset { .. } => "reset", + Mail::EmailOld { .. } => "email_old", + Mail::EmailNew { .. } => "email_new", + Mail::EmailDone { .. } => "email_done", + Mail::Security(_) => "security", + } + } +} + +/// The language a mail to `user` is written in: the stored choice, unless the person chose the +/// browser's language. Then the language of the request that triggered the mail. +pub fn lang_for(user: &User, request: Lang) -> Lang { + if user.locale_auto { + request + } else { + Lang::from_code(&user.locale).unwrap_or(request) + } +} + +/// Renders `mail` for `to` in `lang`, seals it, and adds it to the outbox. The subject is fixed text; +/// the body (text and HTML, with the recipient's name) is sealed as one JSON document. +pub async fn queue( + store: &Store, + key: &[u8; 32], + to: &Recipient, + lang: Lang, + mail: &Mail<'_>, +) -> Result<()> { + let rendered = templates::render(lang, to.name(), mail); + let payload = json!({ + "to_name": to.name(), + "text": rendered.text, + "html": rendered.html, + }) + .to_string(); + let sealed = secret::seal(key, payload.as_bytes())?; + store + .enqueue_mail(&NewMail { + kind: mail.kind(), + to_addr: to.email(), + subject: &rendered.subject, + sealed_body: &sealed, + }) + .await?; + Ok(()) +} + +/// Queues a security notice for the account's own address, in the person's language. A failure is +/// logged and never reaches the caller: the change it reports has already been made. +pub async fn notify(store: &Store, key: &[u8; 32], user: &User, request: Lang, notice: Notice) { + let to = match Recipient::new(Some(&user.name), &user.email) { + Ok(to) => to, + Err(error) => { + tracing::error!( + error, + "security notice not queued: stored address is not valid" + ); + return; + } + }; + let lang = lang_for(user, request); + if let Err(error) = queue(store, key, &to, lang, &Mail::Security(notice)).await { + tracing::error!(error = %error, "security notice not queued"); + } +} diff --git a/crates/im-web/src/mail/templates.rs b/crates/im-web/src/mail/templates.rs new file mode 100644 index 0000000..cb2a895 --- /dev/null +++ b/crates/im-web/src/mail/templates.rs @@ -0,0 +1,194 @@ +//! The text and HTML of each mail kind. One function builds both from the same parts, so the two +//! alternatives always say the same thing. Every value is HTML-escaped, including the links. + +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, +}; + +/// The rendered subject, plain-text body and HTML body of one mail. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Rendered { + /// The subject line. + pub subject: String, + /// The plain-text alternative. + pub text: String, + /// The HTML alternative. + pub html: String, +} + +/// The parts of a mail, in reading order: a greeting, paragraphs, an optional action link with the +/// address printed under it, and a closing. +struct Parts { + subject: String, + greeting: String, + paragraphs: Vec, + action: Option<(String, String)>, + closing: Vec, +} + +/// Renders `mail` for a recipient named `name` (when known) in `lang`. +pub fn render(lang: Lang, name: Option<&str>, mail: &Mail<'_>) -> Rendered { + let parts = parts(lang, name, mail); + Rendered { + subject: parts.subject.clone(), + text: as_text(&parts), + html: as_html(&parts, lang), + } +} + +fn parts(lang: Lang, name: Option<&str>, mail: &Mail<'_>) -> Parts { + let key = |k: MailKey| text(lang, k).to_owned(); + let greeting = greeting(lang, name); + let ignore = key(MailKey::Ignore); + let signature = key(MailKey::Signature); + match *mail { + Mail::Invite { link, days } => Parts { + subject: key(MailKey::InviteSubject), + greeting, + paragraphs: vec![invite_body(lang, days)], + action: Some((key(MailKey::InviteAction), link.to_owned())), + closing: vec![ignore, signature], + }, + Mail::Reset { link, minutes } => Parts { + subject: key(MailKey::ResetSubject), + greeting, + paragraphs: vec![reset_body(lang, minutes), key(MailKey::ResetNote)], + action: Some((key(MailKey::ResetAction), link.to_owned())), + closing: vec![ignore, signature], + }, + Mail::EmailOld { + link, + new_email, + hours, + } => Parts { + subject: key(MailKey::EmailOldSubject), + greeting, + paragraphs: vec![ + email_old_body(lang, new_email, hours), + key(MailKey::EmailOldNote), + ], + action: Some((key(MailKey::EmailOldAction), link.to_owned())), + closing: vec![signature], + }, + Mail::EmailNew { link, hours } => Parts { + subject: key(MailKey::EmailNewSubject), + greeting, + paragraphs: vec![email_new_body(lang, hours)], + action: Some((key(MailKey::EmailNewAction), link.to_owned())), + closing: vec![ignore, signature], + }, + Mail::EmailDone { new_email } => Parts { + subject: key(MailKey::EmailDoneSubject), + greeting, + paragraphs: vec![email_done_body(lang, new_email)], + action: None, + closing: vec![ignore, signature], + }, + Mail::Security(notice) => { + let (subject, body) = match notice { + Notice::PasswordChanged => ( + MailKey::PasswordChangedSubject, + MailKey::PasswordChangedBody, + ), + Notice::PasswordReset => { + (MailKey::PasswordResetSubject, MailKey::PasswordResetBody) + } + Notice::TwoFactorOn => (MailKey::TwoFactorOnSubject, MailKey::TwoFactorOnBody), + Notice::TwoFactorOff => (MailKey::TwoFactorOffSubject, MailKey::TwoFactorOffBody), + Notice::RecoveryCodes => { + (MailKey::RecoveryCodesSubject, MailKey::RecoveryCodesBody) + } + }; + Parts { + subject: key(subject), + greeting, + paragraphs: vec![key(body), key(MailKey::SecurityNote)], + action: None, + closing: vec![signature], + } + } + } +} + +fn as_text(parts: &Parts) -> String { + let mut blocks = vec![parts.greeting.clone()]; + blocks.extend(parts.paragraphs.iter().cloned()); + if let Some((label, url)) = &parts.action { + blocks.push(format!("{label}: {url}")); + } + blocks.extend(parts.closing.iter().cloned()); + blocks.join("\n\n") + "\n" +} + +fn as_html(parts: &Parts, lang: Lang) -> String { + let esc = escape_html; + let mut body = format!("

{}

", esc(&parts.greeting)); + for paragraph in &parts.paragraphs { + body.push_str(&format!("

{}

", esc(paragraph))); + } + if let Some((label, url)) = &parts.action { + body.push_str(&format!( + "

{label}

{url}

", + href = esc(url), + label = esc(label), + url = esc(url), + )); + } + for line in &parts.closing { + body.push_str(&format!("

{}

", esc(line))); + } + format!( + "\n\n{title}\n\n{body}\n\n\n", + code = lang.code(), + title = esc(&parts.subject), + ) +} + +/// Escapes the five characters that are special in HTML text and in quoted attributes. +pub fn escape_html(input: &str) -> String { + let mut out = String::with_capacity(input.len()); + for c in input.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + other => out.push(other), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn values_are_escaped_in_the_html_and_the_text_keeps_them_verbatim() { + let hostile = "https://ex.test/x?a=1&b=