forge
Explore
Log in

Don't you dare go Hollow

Mail outbox and SMTP worker, invites, password reset, two-sided email change, security notices

Browse files at this commit

50b7e2fbe7ac0c5cd579d56ed0b6124151151b97Ahmet Kaan GümüşParent: 1274ea0
  • feat
    • mail outbox and SMTP worker, invites, password reset, two-sided email change, security notices
Show full message
✨ feat: mail outbox and SMTP worker, invites, password reset, two-sided email change, security notices
Cargo.lockmodified+31 -0
@@ -1216,6 +1216,12 @@ version = "0.3.34"
1216 source = "registry+https://github.com/rust-lang/crates.io-index"1216 source = "registry+https://github.com/rust-lang/crates.io-index"
1217 checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"1217 checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
1218 1218
1219+[[package]]
1220+name = "futures-io"
1221+version = "0.3.34"
1222+source = "registry+https://github.com/rust-lang/crates.io-index"
1223+checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
1224+
1219 [[package]]1225 [[package]]
1220 name = "futures-macro"1226 name = "futures-macro"
1221 version = "0.3.34"1227 version = "0.3.34"
@@ -1246,9 +1252,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
1246 checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"1252 checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
1247 dependencies = [1253 dependencies = [
1248 "futures-core",1254 "futures-core",
1255+ "futures-io",
1249 "futures-macro",1256 "futures-macro",
1250 "futures-sink",1257 "futures-sink",
1251 "futures-task",1258 "futures-task",
1259+ "memchr",
1252 "pin-project-lite",1260 "pin-project-lite",
1253 "slab",1261 "slab",
1254 ]1262 ]
@@ -1862,6 +1870,7 @@ dependencies = [
1862 "hex",1870 "hex",
1863 "http",1871 "http",
1864 "im-core",1872 "im-core",
1873+ "lettre",
1865 "qrcode",1874 "qrcode",
1866 "reqwest",1875 "reqwest",
1867 "serde",1876 "serde",
@@ -2137,15 +2146,26 @@ version = "0.11.23"
2137 source = "registry+https://github.com/rust-lang/crates.io-index"2146 source = "registry+https://github.com/rust-lang/crates.io-index"
2138 checksum = "f2c646bd5cc763b1087b15493e29a64be6147ba8f19342004fa52048ee596eae"2147 checksum = "f2c646bd5cc763b1087b15493e29a64be6147ba8f19342004fa52048ee596eae"
2139 dependencies = [2148 dependencies = [
2149+ "async-trait",
2150+ "base64 0.23.1",
2140 "email-encoding",2151 "email-encoding",
2141 "email_address",2152 "email_address",
2142 "fastrand",2153 "fastrand",
2154+ "futures-io",
2155+ "futures-util",
2143 "hostname",2156 "hostname",
2144 "httpdate",2157 "httpdate",
2145 "idna",2158 "idna",
2146 "mime",2159 "mime",
2147 "nom 8.0.0",2160 "nom 8.0.0",
2161+ "percent-encoding",
2148 "quoted_printable",2162 "quoted_printable",
2163+ "rustls",
2164+ "socket2",
2165+ "tokio",
2166+ "tokio-rustls",
2167+ "url",
2168+ "webpki-roots",
2149 ]2169 ]
2150 2170
2151 [[package]]2171 [[package]]
@@ -3243,7 +3263,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
3243 checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"3263 checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
3244 dependencies = [3264 dependencies = [
3245 "aws-lc-rs",3265 "aws-lc-rs",
3266+ "log",
3246 "once_cell",3267 "once_cell",
3268+ "ring",
3247 "rustls-pki-types",3269 "rustls-pki-types",
3248 "rustls-webpki",3270 "rustls-webpki",
3249 "subtle",3271 "subtle",
@@ -5042,6 +5064,15 @@ dependencies = [
5042 "rustls-pki-types",5064 "rustls-pki-types",
5043 ]5065 ]
5044 5066
5067+[[package]]
5068+name = "webpki-roots"
5069+version = "1.0.11"
5070+source = "registry+https://github.com/rust-lang/crates.io-index"
5071+checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171"
5072+dependencies = [
5073+ "rustls-pki-types",
5074+]
5075+
5045 [[package]]5076 [[package]]
5046 name = "weezl"5077 name = "weezl"
5047 version = "0.1.12"5078 version = "0.1.12"
Cargo.tomlmodified+1 -0
@@ -20,6 +20,7 @@ grass = "0.13.4"
20 hex = "0.4.3"20 hex = "0.4.3"
21 hmac = "0.13.0"21 hmac = "0.13.0"
22 image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "webp", "gif"] }22 image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "webp", "gif"] }
23+lettre = { version = "0.11.23", default-features = false, features = ["builder", "smtp-transport", "tokio1", "tokio1-rustls-tls"] }
23 jiff = { version = "0.2.38", default-features = false, features = ["std", "tzdb-bundle-always"] }24 jiff = { version = "0.2.38", default-features = false, features = ["std", "tzdb-bundle-always"] }
24 http = "1.5.0"25 http = "1.5.0"
25 ipnet = "2.12.2"26 ipnet = "2.12.2"
config/im.example.tomlmodified+23 -1
@@ -19,7 +19,7 @@ base_url = "http://localhost:8080"
19 trusted_proxies = []19 trusted_proxies = []
20 20
21 [mail]21 [mail]
22-# Development only: write mail to data/mail-log/ instead of sending it.22+# Reserved. Has no effect yet: mail is always queued and sent through [smtp].
23 log_only = true23 log_only = true
24 24
25 [backup]25 [backup]
@@ -39,3 +39,25 @@ require_2fa_for_admins = true
39 max_sessions = 1039 max_sessions = 10
40 # Hard cap of a browser session, in days from sign-in. Sessions are extended while they are used, up to this.40 # Hard cap of a browser session, in days from sign-in. Sessions are extended while they are used, up to this.
41 session_max_days = 3041 session_max_days = 30
42+# Days an invitation stays usable. Between 1 and 30.
43+invite_days = 7
44+# Minutes a password-reset link stays usable. Between 5 and 1440.
45+reset_minutes = 60
46+# Hours both halves of an email change stay usable. Between 1 and 168.
47+email_change_hours = 24
48+
49+[smtp]
50+# Host of the submission server. Empty means no sender: mail waits in the outbox and no attempt is spent.
51+host = ""
52+# 465 for implicit TLS, 587 for STARTTLS.
53+port = 465
54+# "implicit", "starttls", or "none" (none is refused unless host is localhost).
55+tls = "implicit"
56+# Login name. Empty for a relay that needs no login.
57+username = ""
58+# File with the password, first line only. Must not be readable by group or others.
59+password_file = ""
60+# Address mail is sent from.
61+from = ""
62+# Display name of the sender.
63+from_name = "im"
crates/im-core/src/config.rsmodified+140 -2
@@ -36,11 +36,75 @@ fn deserialize_trusted_proxies<'de, D: Deserializer<'de>>(
36 #[derive(Debug, Clone, Default, Deserialize)]36 #[derive(Debug, Clone, Default, Deserialize)]
37 #[serde(deny_unknown_fields, default)]37 #[serde(deny_unknown_fields, default)]
38 pub struct MailConfig {38 pub struct MailConfig {
39- /// When true, mail is written to `data_dir/mail-log/` instead of being sent. For development39+ /// Reserved for a development mail log. It has no effect yet: mail is always queued in the outbox
40- /// only; a production instance sends mail through the SMTP sender set in the admin UI.40+ /// and sent through `[smtp]`.
41 pub log_only: bool,41 pub log_only: bool,
42 }42 }
43 43
44+/// How the SMTP connection is secured.
45+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
46+#[serde(rename_all = "lowercase")]
47+pub enum SmtpTls {
48+ /// TLS from the first byte of the connection (port 465 by convention).
49+ #[default]
50+ Implicit,
51+ /// A plain connection that is upgraded with STARTTLS. The upgrade is required.
52+ Starttls,
53+ /// No TLS. Only for a relay on localhost, where the traffic never leaves the machine.
54+ None,
55+}
56+
57+/// The outbound SMTP sender. Empty `host` means no sender: mail waits in the outbox and no attempt is
58+/// spent. The password is never in this file; `password_file` names a file that only the service user
59+/// can read (mode 0600 or stricter), and it is read again before each batch, so it can be rotated.
60+#[derive(Debug, Clone, Deserialize)]
61+#[serde(deny_unknown_fields, default)]
62+pub struct SmtpConfig {
63+ /// Host name or address of the submission server. Empty for none.
64+ pub host: String,
65+ /// TCP port. 465 for implicit TLS, 587 for STARTTLS.
66+ pub port: u16,
67+ /// Transport security. `none` is refused unless `host` is localhost.
68+ pub tls: SmtpTls,
69+ /// Login name. Empty for an unauthenticated relay.
70+ pub username: String,
71+ /// File holding the password, first line only. Empty when there is no login.
72+ pub password_file: PathBuf,
73+ /// Address mail is sent from. Required when `host` is set.
74+ pub from: String,
75+ /// Display name of the sender.
76+ pub from_name: String,
77+}
78+
79+impl Default for SmtpConfig {
80+ fn default() -> Self {
81+ Self {
82+ host: String::new(),
83+ port: 465,
84+ tls: SmtpTls::Implicit,
85+ username: String::new(),
86+ password_file: PathBuf::new(),
87+ from: String::new(),
88+ from_name: "im".to_owned(),
89+ }
90+ }
91+}
92+
93+impl SmtpConfig {
94+ /// True when a sender is configured.
95+ pub fn enabled(&self) -> bool {
96+ !self.host.is_empty()
97+ }
98+}
99+
100+/// True for `localhost` and for loopback addresses, the only places plaintext SMTP is allowed.
101+pub fn is_localhost(host: &str) -> bool {
102+ host.eq_ignore_ascii_case("localhost")
103+ || host
104+ .parse::<std::net::IpAddr>()
105+ .is_ok_and(|addr| addr.is_loopback())
106+}
107+
44 /// Scheduled backups. Off while `dir` is empty.108 /// Scheduled backups. Off while `dir` is empty.
45 #[derive(Debug, Clone, Deserialize)]109 #[derive(Debug, Clone, Deserialize)]
46 #[serde(deny_unknown_fields, default)]110 #[serde(deny_unknown_fields, default)]
@@ -87,6 +151,12 @@ pub struct PolicyConfig {
87 /// Hard cap of a browser session, in days from sign-in. A session is idle-extended on use (30 days151 /// Hard cap of a browser session, in days from sign-in. A session is idle-extended on use (30 days
88 /// since its last use) but never lives longer than this. Between 1 and 365.152 /// since its last use) but never lives longer than this. Between 1 and 365.
89 pub session_max_days: u32,153 pub session_max_days: u32,
154+ /// Days an invitation stays usable. Between 1 and 30.
155+ pub invite_days: u32,
156+ /// Minutes a password-reset link stays usable. Between 5 and 1440.
157+ pub reset_minutes: u32,
158+ /// Hours both halves of an email change stay usable. Between 1 and 168.
159+ pub email_change_hours: u32,
90 }160 }
91 161
92 impl Default for PolicyConfig {162 impl Default for PolicyConfig {
@@ -95,6 +165,9 @@ impl Default for PolicyConfig {
95 require_2fa_for_admins: true,165 require_2fa_for_admins: true,
96 max_sessions: 10,166 max_sessions: 10,
97 session_max_days: 30,167 session_max_days: 30,
168+ invite_days: 7,
169+ reset_minutes: 60,
170+ email_change_hours: 24,
98 }171 }
99 }172 }
100 }173 }
@@ -119,6 +192,9 @@ pub struct Config {
119 /// Mail settings without secrets.192 /// Mail settings without secrets.
120 #[serde(default)]193 #[serde(default)]
121 pub mail: MailConfig,194 pub mail: MailConfig,
195+ /// The SMTP sender.
196+ #[serde(default)]
197+ pub smtp: SmtpConfig,
122 /// Scheduled backups.198 /// Scheduled backups.
123 #[serde(default)]199 #[serde(default)]
124 pub backup: BackupConfig,200 pub backup: BackupConfig,
@@ -183,6 +259,22 @@ impl Config {
183 "[policy] session_max_days must be between 1 and 365".into(),259 "[policy] session_max_days must be between 1 and 365".into(),
184 ));260 ));
185 }261 }
262+ if !(1..=30).contains(&self.policy.invite_days) {
263+ return Err(Error::Config(
264+ "[policy] invite_days must be between 1 and 30".into(),
265+ ));
266+ }
267+ if !(5..=1440).contains(&self.policy.reset_minutes) {
268+ return Err(Error::Config(
269+ "[policy] reset_minutes must be between 5 and 1440".into(),
270+ ));
271+ }
272+ if !(1..=168).contains(&self.policy.email_change_hours) {
273+ return Err(Error::Config(
274+ "[policy] email_change_hours must be between 1 and 168".into(),
275+ ));
276+ }
277+ self.validate_smtp()?;
186 let hc = &self.backup.healthcheck_url;278 let hc = &self.backup.healthcheck_url;
187 if !hc.is_empty() && !(hc.starts_with("https://") || hc.starts_with("http://")) {279 if !hc.is_empty() && !(hc.starts_with("https://") || hc.starts_with("http://")) {
188 return Err(Error::Config(280 return Err(Error::Config(
@@ -193,6 +285,37 @@ impl Config {
193 }285 }
194 }286 }
195 287
288+impl Config {
289+ /// The SMTP rules: plaintext only on localhost, a valid sender address, and a password file when
290+ /// there is a login. Checked only when a sender is configured.
291+ fn validate_smtp(&self) -> Result<()> {
292+ let smtp = &self.smtp;
293+ if !smtp.enabled() {
294+ return Ok(());
295+ }
296+ if smtp.port == 0 {
297+ return Err(Error::Config(
298+ "[smtp] port must be between 1 and 65535".into(),
299+ ));
300+ }
301+ if smtp.tls == SmtpTls::None && !is_localhost(&smtp.host) {
302+ return Err(Error::Config(
303+ "[smtp] tls = \"none\" is allowed only for a localhost host".into(),
304+ ));
305+ }
306+ if !smtp.username.is_empty() && smtp.password_file.as_os_str().is_empty() {
307+ return Err(Error::Config(
308+ "[smtp] a username needs a password_file".into(),
309+ ));
310+ }
311+ crate::names::parse_email(&smtp.from)
312+ .map_err(|_| Error::Config("[smtp] from must be an email address".into()))?;
313+ crate::names::parse_display_name(&smtp.from_name)
314+ .map_err(|_| Error::Config("[smtp] from_name is not a valid name".into()))?;
315+ Ok(())
316+ }
317+}
318+
196 /// Checks that `base_url` is an http(s) origin with a path of at most `/`.319 /// Checks that `base_url` is an http(s) origin with a path of at most `/`.
197 fn validate_base_url(url: &str) -> Result<()> {320 fn validate_base_url(url: &str) -> Result<()> {
198 let rest = url321 let rest = url
@@ -217,4 +340,19 @@ mod tests {
217 let typo = format!("{EXAMPLE}\nlisen = \"0.0.0.0:1\"\n");340 let typo = format!("{EXAMPLE}\nlisen = \"0.0.0.0:1\"\n");
218 assert!(Config::parse(&typo).is_err());341 assert!(Config::parse(&typo).is_err());
219 }342 }
343+
344+ #[test]
345+ fn plaintext_smtp_is_refused_unless_the_host_is_localhost() {
346+ let base = "database = \"d\"\ndata_dir = \"x\"\nlisten = \"127.0.0.1:1\"\nbase_url = \"http://a\"\n";
347+ let remote = format!(
348+ "{base}[smtp]\nhost = \"mail.example.com\"\ntls = \"none\"\nfrom = \"im@example.com\"\n"
349+ );
350+ assert!(Config::parse(&remote).is_err());
351+ let local = format!(
352+ "{base}[smtp]\nhost = \"127.0.0.1\"\nport = 2525\ntls = \"none\"\nfrom = \"im@example.com\"\n"
353+ );
354+ Config::parse(&local).expect("localhost may be plain");
355+ let no_from = format!("{base}[smtp]\nhost = \"mail.example.com\"\n");
356+ assert!(Config::parse(&no_from).is_err());
357+ }
220 }358 }
crates/im-core/src/model.rsmodified+24 -0
@@ -142,6 +142,22 @@ pub enum AuditAction {
142 SessionRevoked,142 SessionRevoked,
143 /// Every session except the current one was ended.143 /// Every session except the current one was ended.
144 SessionsRevoked,144 SessionsRevoked,
145+ /// An administrator invited someone.
146+ InviteCreated,
147+ /// An invitation was accepted and its account created.
148+ InviteAccepted,
149+ /// A password reset was asked for, for an account that exists and is enabled.
150+ ResetRequested,
151+ /// A password was set through a reset link. Every session of the person ended.
152+ PasswordReset,
153+ /// An email change was asked for.
154+ EmailChangeRequested,
155+ /// One half of an email change was confirmed. The data says which half.
156+ EmailChangeConfirmed,
157+ /// An email change was cancelled from its old-address link.
158+ EmailChangeCancelled,
159+ /// The address of an account was changed.
160+ EmailChanged,
145 }161 }
146 162
147 impl AuditAction {163 impl AuditAction {
@@ -163,6 +179,14 @@ impl AuditAction {
163 AuditAction::RecoveryCodesIssued => "recovery.issued",179 AuditAction::RecoveryCodesIssued => "recovery.issued",
164 AuditAction::SessionRevoked => "session.revoked",180 AuditAction::SessionRevoked => "session.revoked",
165 AuditAction::SessionsRevoked => "sessions.revoked",181 AuditAction::SessionsRevoked => "sessions.revoked",
182+ AuditAction::InviteCreated => "invite.created",
183+ AuditAction::InviteAccepted => "invite.accepted",
184+ AuditAction::ResetRequested => "reset.requested",
185+ AuditAction::PasswordReset => "password.reset",
186+ AuditAction::EmailChangeRequested => "email_change.requested",
187+ AuditAction::EmailChangeConfirmed => "email_change.confirmed",
188+ AuditAction::EmailChangeCancelled => "email_change.cancelled",
189+ AuditAction::EmailChanged => "email.changed",
166 }190 }
167 }191 }
168 }192 }
crates/im-core/src/store/invites.rsadded+290 -0
@@ -0,0 +1,290 @@
1+//! Invitations: an administrator creates one for an address; the person who receives it sets a name and
2+//! a password and gets an account.
3+//!
4+//! The token is never stored, only its hash. Creating an invitation for an address deletes the older
5+//! pending ones for that address, so only the newest link works. Accepting is one conditional update
6+//! (`accepted_at IS NULL AND expires_at > now`): two parallel redemptions of the same link cannot both
7+//! succeed, because the writer serialises them and the second one finds the invitation already used.
8+//! The account is created in the same transaction, so a refused acceptance leaves no account behind.
9+
10+use std::time::Duration;
11+
12+use turso::Connection;
13+
14+use crate::error::{Error, Result};
15+use crate::model::User;
16+use crate::store::directory::{ChangeKind, record_change};
17+use crate::store::users::{USER_COLS, insert_error, map_user};
18+use crate::store::{Store, col_opt_text, col_text, db_err, fetch_opt, finish, new_id};
19+use crate::time::now_stamp;
20+
21+/// A pending or used invitation, as the store returns it.
22+#[derive(Debug, Clone, PartialEq, Eq)]
23+pub struct Invite {
24+ /// Hex SHA-256 of the token in the link.
25+ pub token_hash: String,
26+ /// The normalised address the invitation is for. The account gets this address.
27+ pub email_folded: String,
28+ /// Whether the account is made an administrator.
29+ pub is_admin: bool,
30+ /// When the invitation stops being usable.
31+ pub expires_at: String,
32+ /// Set when the invitation was used.
33+ pub accepted_at: Option<String>,
34+}
35+
36+/// The result of [`Store::accept_invite`].
37+#[derive(Debug, Clone, PartialEq, Eq)]
38+pub enum AcceptOutcome {
39+ /// The account was created.
40+ Accepted(Box<User>),
41+ /// The link is used, expired, or the address became registered in the meantime. The three are not
42+ /// told apart, so the answer reveals nothing about the address.
43+ Refused,
44+}
45+
46+fn map_invite(row: &turso::Row) -> Result<Invite> {
47+ Ok(Invite {
48+ token_hash: col_text(row, 0)?,
49+ email_folded: col_text(row, 1)?,
50+ is_admin: crate::store::col_int(row, 2)? != 0,
51+ expires_at: col_text(row, 3)?,
52+ accepted_at: col_opt_text(row, 4)?,
53+ })
54+}
55+
56+const INVITE_COLS: &str = "token_hash, email_folded, is_admin, expires_at, accepted_at";
57+
58+/// Whether an invitation for `email_folded` may be created: the address must not belong to an account.
59+async fn address_is_free(conn: &Connection, email_folded: &str) -> Result<bool> {
60+ let taken = fetch_opt(
61+ conn,
62+ "SELECT 1 FROM users WHERE email_folded = ?1",
63+ (email_folded.to_string(),),
64+ |_row| Ok(()),
65+ )
66+ .await?;
67+ Ok(taken.is_none())
68+}
69+
70+impl Store {
71+ /// Stores a new invitation. In one transaction: the address must not be registered yet, the older
72+ /// pending invitations for it are deleted, and the new row is inserted. `expires_at` is a stamp.
73+ pub async fn create_invite(
74+ &self,
75+ token_hash: &str,
76+ email_folded: &str,
77+ is_admin: bool,
78+ invited_by: &str,
79+ expires_at: &str,
80+ ) -> Result<()> {
81+ let conn = self.inner.conn.lock().await;
82+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
83+ let outcome: Result<()> = async {
84+ if !address_is_free(&tx, email_folded).await? {
85+ return Err(Error::Conflict(
86+ "that email address already has an account".into(),
87+ ));
88+ }
89+ tx.execute(
90+ "DELETE FROM invites WHERE email_folded = ?1 AND accepted_at IS NULL",
91+ (email_folded.to_string(),),
92+ )
93+ .await
94+ .map_err(db_err)?;
95+ tx.execute(
96+ "INSERT INTO invites (token_hash, email_folded, is_admin, invited_by, created_at, expires_at) \
97+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
98+ (
99+ token_hash.to_string(),
100+ email_folded.to_string(),
101+ i64::from(is_admin),
102+ invited_by.to_string(),
103+ now_stamp(),
104+ expires_at.to_string(),
105+ ),
106+ )
107+ .await
108+ .map_err(db_err)?;
109+ Ok(())
110+ }
111+ .await;
112+ finish(tx, outcome).await
113+ }
114+
115+ /// The invitation with this token hash, only while it is usable (not accepted, not expired).
116+ pub async fn live_invite(&self, token_hash: &str) -> Result<Option<Invite>> {
117+ let conn = self.read_conn().await;
118+ fetch_opt(
119+ &conn,
120+ &format!(
121+ "SELECT {INVITE_COLS} FROM invites \
122+ WHERE token_hash = ?1 AND accepted_at IS NULL AND expires_at > ?2"
123+ ),
124+ (token_hash.to_string(), now_stamp()),
125+ map_invite,
126+ )
127+ .await
128+ }
129+
130+ /// Accepts an invitation and creates its account, in one transaction.
131+ ///
132+ /// The first statement is the conditional update that spends the link. If it touches no row, the
133+ /// link was used or has expired, and nothing else happens. A UNIQUE clash on the address (it was
134+ /// registered after the invitation was made) rolls the whole transaction back, so the link is not
135+ /// spent by a refused acceptance either. `name` and `password_hash` are already checked by the caller.
136+ pub async fn accept_invite(
137+ &self,
138+ token_hash: &str,
139+ name: &str,
140+ password_hash: &str,
141+ ) -> Result<AcceptOutcome> {
142+ let now = now_stamp();
143+ let id = new_id();
144+ let conn = self.inner.conn.lock().await;
145+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
146+ let outcome: Result<Option<User>> = async {
147+ let spent = tx
148+ .execute(
149+ "UPDATE invites SET accepted_at = ?2 \
150+ WHERE token_hash = ?1 AND accepted_at IS NULL AND expires_at > ?2",
151+ (token_hash.to_string(), now.clone()),
152+ )
153+ .await
154+ .map_err(db_err)?;
155+ if spent != 1 {
156+ return Ok(None);
157+ }
158+ let invite = fetch_opt(
159+ &tx,
160+ &format!("SELECT {INVITE_COLS} FROM invites WHERE token_hash = ?1"),
161+ (token_hash.to_string(),),
162+ map_invite,
163+ )
164+ .await?
165+ .ok_or(Error::NotFound)?;
166+ tx.execute(
167+ "INSERT INTO users (id, email, email_folded, name, password_hash, is_admin, \
168+ created_at, updated_at) VALUES (?1, ?2, ?2, ?3, ?4, ?5, ?6, ?6)",
169+ (
170+ id.clone(),
171+ invite.email_folded.clone(),
172+ name.to_string(),
173+ password_hash.to_string(),
174+ i64::from(invite.is_admin),
175+ now.clone(),
176+ ),
177+ )
178+ .await
179+ .map_err(insert_error)?;
180+ record_change(&tx, &id, ChangeKind::Member).await?;
181+ let user = fetch_opt(
182+ &tx,
183+ &format!("SELECT {USER_COLS} FROM users WHERE id = ?1"),
184+ (id.clone(),),
185+ map_user,
186+ )
187+ .await?
188+ .ok_or(Error::NotFound)?;
189+ Ok(Some(user))
190+ }
191+ .await;
192+ // A UNIQUE clash comes back as a conflict, and finish rolls the spend back with it.
193+ let result = match finish(tx, outcome).await {
194+ Ok(Some(user)) => AcceptOutcome::Accepted(Box::new(user)),
195+ Ok(None) | Err(Error::Conflict(_)) => AcceptOutcome::Refused,
196+ Err(error) => return Err(error),
197+ };
198+ drop(conn);
199+ if matches!(result, AcceptOutcome::Accepted(_)) {
200+ self.announce_directory();
201+ }
202+ Ok(result)
203+ }
204+
205+ /// Deletes invitations that have expired. Returns how many were removed. Run by the sweeper.
206+ pub async fn sweep_invites(&self, now: &str) -> Result<u64> {
207+ let conn = self.inner.conn.lock().await;
208+ conn.execute(
209+ "DELETE FROM invites WHERE expires_at <= ?1",
210+ (now.to_string(),),
211+ )
212+ .await
213+ .map_err(db_err)
214+ }
215+}
216+
217+/// How long an invitation of `days` lasts, as a duration. Used by callers that compute the stamp.
218+pub fn invite_lifetime(days: u32) -> Duration {
219+ Duration::from_secs(u64::from(days) * 24 * 60 * 60)
220+}
221+
222+#[cfg(test)]
223+mod tests {
224+ use super::*;
225+ use crate::time::stamp_after;
226+
227+ async fn store() -> (tempfile::TempDir, Store) {
228+ let dir = tempfile::tempdir().unwrap();
229+ let store = Store::open(&dir.path().join("im.db")).await.unwrap();
230+ (dir, store)
231+ }
232+
233+ #[tokio::test]
234+ async fn a_parallel_double_accept_creates_exactly_one_user() {
235+ let (_dir, store) = store().await;
236+ let admin = store
237+ .create_user("admin@example.com", "Admin", "hash", true)
238+ .await
239+ .unwrap();
240+ store
241+ .create_invite(
242+ "tok-hash",
243+ "newbie@example.com",
244+ false,
245+ &admin.id,
246+ &stamp_after(invite_lifetime(7)),
247+ )
248+ .await
249+ .unwrap();
250+ let (a, b) = tokio::join!(
251+ store.accept_invite("tok-hash", "First", "pw1"),
252+ store.accept_invite("tok-hash", "Second", "pw2"),
253+ );
254+ let outcomes = [a.unwrap(), b.unwrap()];
255+ let accepted = outcomes
256+ .iter()
257+ .filter(|o| matches!(o, AcceptOutcome::Accepted(_)))
258+ .count();
259+ assert_eq!(accepted, 1, "{outcomes:?}");
260+ assert_eq!(store.user_count().await.unwrap(), 2);
261+ }
262+
263+ #[tokio::test]
264+ async fn an_expired_invitation_is_refused_and_creates_nothing() {
265+ let (_dir, store) = store().await;
266+ let admin = store
267+ .create_user("admin@example.com", "Admin", "hash", true)
268+ .await
269+ .unwrap();
270+ // Created already expired: the lifetime is negative.
271+ let past = crate::time::stamp_before(std::time::Duration::from_secs(60));
272+ store
273+ .create_invite("old-hash", "late@example.com", false, &admin.id, &past)
274+ .await
275+ .unwrap();
276+ assert!(store.live_invite("old-hash").await.unwrap().is_none());
277+ let outcome = store
278+ .accept_invite("old-hash", "Late", "password-long")
279+ .await
280+ .unwrap();
281+ assert_eq!(outcome, AcceptOutcome::Refused);
282+ assert!(
283+ store
284+ .user_by_email_folded("late@example.com")
285+ .await
286+ .unwrap()
287+ .is_none()
288+ );
289+ }
290+}
crates/im-core/src/store/links.rsadded+449 -0
@@ -0,0 +1,449 @@
1+//! Single-use account links: password reset, and the two halves of an email change.
2+//!
3+//! Every link is stored as the hash of its token, and every use is one conditional update, so a link
4+//! works once even when two requests race. The writer connection serialises the transactions here.
5+//!
6+//! An email change has two links that share a `pair_id`: `email_old` goes to the current address and
7+//! `email_new` to the new one. The change is applied only when both halves have been confirmed. The
8+//! old-address page can also cancel it, which deletes the pair. Applying the change checks that the new
9+//! address is still free at that moment, not when it was requested.
10+
11+use turso::Connection;
12+
13+use crate::error::{Error, Result};
14+use crate::store::backchannel::EndReason;
15+use crate::store::directory::{ChangeKind, record_change};
16+use crate::store::sessions::end_all_sessions;
17+use crate::store::users::insert_error;
18+use crate::store::{Store, col_opt_text, col_text, db_err, fetch_opt, finish, new_id};
19+use crate::time::now_stamp;
20+
21+/// One row of `account_links`, as the web layer reads it.
22+#[derive(Debug, Clone, PartialEq, Eq)]
23+pub struct AccountLink {
24+ /// The person the link belongs to.
25+ pub user_id: String,
26+ /// `reset`, `email_old` or `email_new`.
27+ pub kind: String,
28+ /// The two halves of one email change share this id.
29+ pub pair_id: Option<String>,
30+ /// The address the change moves to (both halves carry it).
31+ pub new_email: Option<String>,
32+ /// When the link stops being usable.
33+ pub expires_at: String,
34+}
35+
36+/// What a confirmation of one half did.
37+#[derive(Debug, Clone, PartialEq, Eq)]
38+pub enum EmailConfirm {
39+ /// This half is confirmed; the other half is still waiting.
40+ Waiting,
41+ /// Both halves are confirmed and the address was changed.
42+ Applied {
43+ /// The person whose address changed.
44+ user_id: String,
45+ /// The address before the change.
46+ old_email: String,
47+ /// The address after the change.
48+ new_email: String,
49+ },
50+ /// The link is not usable, or the new address was taken in the meantime. The pair is gone.
51+ Refused,
52+}
53+
54+fn map_link(row: &turso::Row) -> Result<AccountLink> {
55+ Ok(AccountLink {
56+ user_id: col_text(row, 0)?,
57+ kind: col_text(row, 1)?,
58+ pair_id: col_opt_text(row, 2)?,
59+ new_email: col_opt_text(row, 3)?,
60+ expires_at: col_text(row, 4)?,
61+ })
62+}
63+
64+const LINK_COLS: &str = "l.user_id, l.kind, l.pair_id, l.new_email, l.expires_at";
65+
66+/// Marks every pending link of `user_id` as used, so none of them works any more. Runs inside the
67+/// caller's transaction.
68+pub(crate) async fn invalidate_links(conn: &Connection, user_id: &str, now: &str) -> Result<()> {
69+ conn.execute(
70+ "UPDATE account_links SET used_at = ?2 WHERE user_id = ?1 AND used_at IS NULL",
71+ (user_id.to_string(), now.to_string()),
72+ )
73+ .await
74+ .map_err(db_err)?;
75+ Ok(())
76+}
77+
78+impl Store {
79+ /// Creates a password-reset link. Older pending reset links of the person stop working. The
80+ /// caller has checked that the person exists and is not disabled.
81+ pub async fn create_reset_link(
82+ &self,
83+ user_id: &str,
84+ token_hash: &str,
85+ expires_at: &str,
86+ ) -> Result<()> {
87+ let now = now_stamp();
88+ let conn = self.inner.conn.lock().await;
89+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
90+ let outcome: Result<()> = async {
91+ tx.execute(
92+ "UPDATE account_links SET used_at = ?2 \
93+ WHERE user_id = ?1 AND kind = 'reset' AND used_at IS NULL",
94+ (user_id.to_string(), now.clone()),
95+ )
96+ .await
97+ .map_err(db_err)?;
98+ tx.execute(
99+ "INSERT INTO account_links (token_hash, kind, user_id, created_at, expires_at) \
100+ VALUES (?1, 'reset', ?2, ?3, ?4)",
101+ (
102+ token_hash.to_string(),
103+ user_id.to_string(),
104+ now,
105+ expires_at.to_string(),
106+ ),
107+ )
108+ .await
109+ .map_err(db_err)?;
110+ Ok(())
111+ }
112+ .await;
113+ finish(tx, outcome).await
114+ }
115+
116+ /// A usable link of one of the given kinds, with its person enabled. `kinds` are the stored kinds.
117+ async fn live_link(&self, token_hash: &str, kinds: &[&str]) -> Result<Option<AccountLink>> {
118+ let list = kinds
119+ .iter()
120+ .map(|k| format!("'{k}'"))
121+ .collect::<Vec<_>>()
122+ .join(", ");
123+ let conn = self.read_conn().await;
124+ fetch_opt(
125+ &conn,
126+ &format!(
127+ "SELECT {LINK_COLS} FROM account_links l JOIN users u ON u.id = l.user_id \
128+ WHERE l.token_hash = ?1 AND l.kind IN ({list}) AND l.used_at IS NULL \
129+ AND l.expires_at > ?2 AND u.disabled_at IS NULL"
130+ ),
131+ (token_hash.to_string(), now_stamp()),
132+ map_link,
133+ )
134+ .await
135+ }
136+
137+ /// A usable password-reset link, or `None`.
138+ pub async fn live_reset_link(&self, token_hash: &str) -> Result<Option<AccountLink>> {
139+ self.live_link(token_hash, &["reset"]).await
140+ }
141+
142+ /// A usable half of an email change, or `None`.
143+ pub async fn live_email_link(&self, token_hash: &str) -> Result<Option<AccountLink>> {
144+ self.live_link(token_hash, &["email_old", "email_new"])
145+ .await
146+ }
147+
148+ /// Spends a password-reset link and sets the new password, in one transaction.
149+ ///
150+ /// The conditional update of the link comes first; if it touches nothing, the link was used,
151+ /// expired or belongs to a disabled person, and nothing else changes. Otherwise the password is
152+ /// replaced, every other pending link of the person is invalidated, and every session of the person
153+ /// is ended with its back-channel logouts. Returns the person id, or `None` when the link was not
154+ /// usable. The caller has checked the policy and that the password differs from the old one.
155+ pub async fn redeem_reset_link(
156+ &self,
157+ token_hash: &str,
158+ password_hash: &str,
159+ ) -> Result<Option<String>> {
160+ let now = now_stamp();
161+ let conn = self.inner.conn.lock().await;
162+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
163+ let outcome: Result<Option<String>> = async {
164+ let user_id = fetch_opt(
165+ &tx,
166+ "SELECT user_id FROM account_links WHERE token_hash = ?1 AND kind = 'reset'",
167+ (token_hash.to_string(),),
168+ |row| col_text(row, 0),
169+ )
170+ .await?;
171+ let Some(user_id) = user_id else {
172+ return Ok(None);
173+ };
174+ let spent = tx
175+ .execute(
176+ "UPDATE account_links SET used_at = ?2 \
177+ WHERE token_hash = ?1 AND kind = 'reset' AND used_at IS NULL AND expires_at > ?2 \
178+ AND user_id IN (SELECT id FROM users WHERE disabled_at IS NULL)",
179+ (token_hash.to_string(), now.clone()),
180+ )
181+ .await
182+ .map_err(db_err)?;
183+ if spent != 1 {
184+ return Ok(None);
185+ }
186+ tx.execute(
187+ "UPDATE users SET password_hash = ?2, updated_at = ?3 WHERE id = ?1",
188+ (user_id.clone(), password_hash.to_string(), now.clone()),
189+ )
190+ .await
191+ .map_err(db_err)?;
192+ invalidate_links(&tx, &user_id, &now).await?;
193+ end_all_sessions(&tx, &user_id, EndReason::PasswordChanged, &now).await?;
194+ Ok(Some(user_id))
195+ }
196+ .await;
197+ finish(tx, outcome).await
198+ }
199+
200+ /// Starts an email change: two links, one for each address, sharing a pair id. Older pending email
201+ /// links of the person stop working. Fails with a conflict when `new_email` belongs to an account.
202+ /// `expires_at` is the same for both halves.
203+ pub async fn start_email_change(
204+ &self,
205+ user_id: &str,
206+ new_email_folded: &str,
207+ old_token_hash: &str,
208+ new_token_hash: &str,
209+ expires_at: &str,
210+ ) -> Result<()> {
211+ let now = now_stamp();
212+ let pair = new_id();
213+ let conn = self.inner.conn.lock().await;
214+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
215+ let outcome: Result<()> = async {
216+ let taken = fetch_opt(
217+ &tx,
218+ "SELECT 1 FROM users WHERE email_folded = ?1",
219+ (new_email_folded.to_string(),),
220+ |_row| Ok(()),
221+ )
222+ .await?;
223+ if taken.is_some() {
224+ return Err(Error::Conflict(
225+ "that email address cannot be used".into(),
226+ ));
227+ }
228+ invalidate_links_of_kinds(&tx, user_id, &now).await?;
229+ for (token_hash, kind) in [(old_token_hash, "email_old"), (new_token_hash, "email_new")] {
230+ tx.execute(
231+ "INSERT INTO account_links (token_hash, kind, user_id, pair_id, new_email, created_at, expires_at) \
232+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
233+ (
234+ token_hash.to_string(),
235+ kind,
236+ user_id.to_string(),
237+ pair.clone(),
238+ new_email_folded.to_string(),
239+ now.clone(),
240+ expires_at.to_string(),
241+ ),
242+ )
243+ .await
244+ .map_err(db_err)?;
245+ }
246+ Ok(())
247+ }
248+ .await;
249+ finish(tx, outcome).await
250+ }
251+
252+ /// Confirms one half of an email change. When this makes both halves confirmed, the address is
253+ /// changed in the same transaction, unless the new address has been taken since the request. In
254+ /// that case the pair is deleted and the answer is [`EmailConfirm::Refused`].
255+ pub async fn confirm_email_link(&self, token_hash: &str) -> Result<EmailConfirm> {
256+ let now = now_stamp();
257+ let conn = self.inner.conn.lock().await;
258+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
259+ let outcome: Result<EmailConfirm> = async {
260+ let link = fetch_opt(
261+ &tx,
262+ &format!(
263+ "SELECT {LINK_COLS} FROM account_links l JOIN users u ON u.id = l.user_id \
264+ WHERE l.token_hash = ?1 AND l.kind IN ('email_old', 'email_new') \
265+ AND l.used_at IS NULL AND l.expires_at > ?2 AND u.disabled_at IS NULL"
266+ ),
267+ (token_hash.to_string(), now.clone()),
268+ map_link,
269+ )
270+ .await?;
271+ let Some(link) = link else {
272+ return Ok(EmailConfirm::Refused);
273+ };
274+ let pair = link.pair_id.clone().ok_or(Error::NotFound)?;
275+ let new_email = link.new_email.clone().ok_or(Error::NotFound)?;
276+ tx.execute(
277+ "UPDATE account_links SET used_at = ?2 WHERE token_hash = ?1 AND used_at IS NULL",
278+ (token_hash.to_string(), now.clone()),
279+ )
280+ .await
281+ .map_err(db_err)?;
282+ let confirmed = fetch_opt(
283+ &tx,
284+ "SELECT COUNT(*) FROM account_links WHERE pair_id = ?1 AND used_at IS NOT NULL",
285+ (pair.clone(),),
286+ |row| crate::store::col_int(row, 0),
287+ )
288+ .await?
289+ .unwrap_or(0);
290+ if confirmed < 2 {
291+ return Ok(EmailConfirm::Waiting);
292+ }
293+
294+ // Both halves are in. The address must still be free: it may have been registered since.
295+ let taken = fetch_opt(
296+ &tx,
297+ "SELECT 1 FROM users WHERE email_folded = ?1 AND id <> ?2",
298+ (new_email.clone(), link.user_id.clone()),
299+ |_row| Ok(()),
300+ )
301+ .await?;
302+ if taken.is_some() {
303+ tx.execute("DELETE FROM account_links WHERE pair_id = ?1", (pair,))
304+ .await
305+ .map_err(db_err)?;
306+ return Ok(EmailConfirm::Refused);
307+ }
308+ let old_email = fetch_opt(
309+ &tx,
310+ "SELECT email FROM users WHERE id = ?1",
311+ (link.user_id.clone(),),
312+ |row| col_text(row, 0),
313+ )
314+ .await?
315+ .ok_or(Error::NotFound)?;
316+ tx.execute(
317+ "UPDATE users SET email = ?2, email_folded = ?2, updated_at = ?3 WHERE id = ?1",
318+ (link.user_id.clone(), new_email.clone(), now.clone()),
319+ )
320+ .await
321+ .map_err(insert_error)?;
322+ record_change(&tx, &link.user_id, ChangeKind::Member).await?;
323+ invalidate_links(&tx, &link.user_id, &now).await?;
324+ Ok(EmailConfirm::Applied {
325+ user_id: link.user_id,
326+ old_email,
327+ new_email,
328+ })
329+ }
330+ .await;
331+ let result = finish(tx, outcome).await;
332+ drop(conn);
333+ if matches!(result, Ok(EmailConfirm::Applied { .. })) {
334+ self.announce_directory();
335+ }
336+ result
337+ }
338+
339+ /// Cancels an email change from one of its links: both halves are deleted. Returns the person id
340+ /// when the link was usable, else `None`.
341+ pub async fn cancel_email_change(&self, token_hash: &str) -> Result<Option<String>> {
342+ let Some(link) = self.live_email_link(token_hash).await? else {
343+ return Ok(None);
344+ };
345+ let Some(pair) = link.pair_id else {
346+ return Ok(None);
347+ };
348+ let conn = self.inner.conn.lock().await;
349+ conn.execute("DELETE FROM account_links WHERE pair_id = ?1", (pair,))
350+ .await
351+ .map_err(db_err)?;
352+ Ok(Some(link.user_id))
353+ }
354+
355+ /// Deletes links that have expired. Returns how many were removed. Run by the sweeper.
356+ pub async fn sweep_links(&self, now: &str) -> Result<u64> {
357+ let conn = self.inner.conn.lock().await;
358+ conn.execute(
359+ "DELETE FROM account_links WHERE expires_at <= ?1",
360+ (now.to_string(),),
361+ )
362+ .await
363+ .map_err(db_err)
364+ }
365+}
366+
367+/// Invalidates the pending email-change links of `user_id` (not its reset links). Runs inside a
368+/// transaction.
369+async fn invalidate_links_of_kinds(conn: &Connection, user_id: &str, now: &str) -> Result<()> {
370+ conn.execute(
371+ "UPDATE account_links SET used_at = ?2 \
372+ WHERE user_id = ?1 AND kind IN ('email_old', 'email_new') AND used_at IS NULL",
373+ (user_id.to_string(), now.to_string()),
374+ )
375+ .await
376+ .map_err(db_err)?;
377+ Ok(())
378+}
379+
380+#[cfg(test)]
381+mod tests {
382+ use super::*;
383+ use crate::time::stamp_after;
384+ use std::time::Duration;
385+
386+ async fn setup() -> (tempfile::TempDir, Store, String) {
387+ let dir = tempfile::tempdir().unwrap();
388+ let store = Store::open(&dir.path().join("im.db")).await.unwrap();
389+ let user = store
390+ .create_user("ada@example.com", "Ada", "old-hash", false)
391+ .await
392+ .unwrap();
393+ (dir, store, user.id)
394+ }
395+
396+ #[tokio::test]
397+ async fn a_reset_link_works_once() {
398+ let (_dir, store, user_id) = setup().await;
399+ store
400+ .create_reset_link(
401+ &user_id,
402+ "reset-hash",
403+ &stamp_after(Duration::from_secs(3600)),
404+ )
405+ .await
406+ .unwrap();
407+ assert!(store.live_reset_link("reset-hash").await.unwrap().is_some());
408+ let first = store
409+ .redeem_reset_link("reset-hash", "new-hash")
410+ .await
411+ .unwrap();
412+ assert_eq!(first.as_deref(), Some(user_id.as_str()));
413+ // Reuse is refused, and the password is not touched a second time.
414+ let second = store
415+ .redeem_reset_link("reset-hash", "other-hash")
416+ .await
417+ .unwrap();
418+ assert_eq!(second, None);
419+ let user = store.user_by_id(&user_id).await.unwrap().unwrap();
420+ assert_eq!(user.password_hash, "new-hash");
421+ }
422+
423+ #[tokio::test]
424+ async fn an_email_change_is_refused_when_the_address_was_taken_before_confirm() {
425+ let (_dir, store, user_id) = setup().await;
426+ let later = stamp_after(Duration::from_secs(3600));
427+ store
428+ .start_email_change(&user_id, "ada.new@example.com", "h-old", "h-new", &later)
429+ .await
430+ .unwrap();
431+ // Someone else registers the new address before either half is confirmed.
432+ store
433+ .create_user("ada.new@example.com", "Other", "hash", false)
434+ .await
435+ .unwrap();
436+ assert_eq!(
437+ store.confirm_email_link("h-old").await.unwrap(),
438+ EmailConfirm::Waiting
439+ );
440+ assert_eq!(
441+ store.confirm_email_link("h-new").await.unwrap(),
442+ EmailConfirm::Refused
443+ );
444+ let user = store.user_by_id(&user_id).await.unwrap().unwrap();
445+ assert_eq!(user.email, "ada@example.com");
446+ // The pair is gone, so the old half cannot be used again.
447+ assert!(store.live_email_link("h-old").await.unwrap().is_none());
448+ }
449+}
crates/im-core/src/store/mail.rsadded+245 -0
@@ -0,0 +1,245 @@
1+//! The mail outbox: rows the mail worker sends, with their retry state.
2+//!
3+//! A row keeps its body sealed under the instance key (the body can hold a single-use link). The worker
4+//! opens it only to send. Once a row is sent or abandoned its body is blanked, so a token-bearing body
5+//! survives only until its first delivery attempt succeeds or the row gives up. Sent rows are deleted
6+//! 30 days after they were sent. Nothing here logs a body or a recipient.
7+
8+use crate::error::Result;
9+use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id};
10+use crate::time::now_stamp;
11+
12+/// What a new outbox row holds.
13+#[derive(Debug, Clone, Copy)]
14+pub struct NewMail<'a> {
15+ /// The kind, one of the values the schema allows.
16+ pub kind: &'a str,
17+ /// The recipient address. Already validated by the caller.
18+ pub to_addr: &'a str,
19+ /// The subject. Built from fixed text only.
20+ pub subject: &'a str,
21+ /// The body, sealed with `secret::seal`.
22+ pub sealed_body: &'a str,
23+}
24+
25+/// One row the worker should try now.
26+#[derive(Debug, Clone, PartialEq, Eq)]
27+pub struct MailJob {
28+ /// ULID.
29+ pub id: String,
30+ /// The kind of the mail.
31+ pub kind: String,
32+ /// The recipient address.
33+ pub to_addr: String,
34+ /// The subject.
35+ pub subject: String,
36+ /// The sealed body. Empty when the row was already blanked, which the worker treats as corrupt.
37+ pub sealed_body: String,
38+ /// Attempts made so far.
39+ pub attempts: i64,
40+}
41+
42+/// The outcome the worker reports for one attempt.
43+#[derive(Debug, Clone, PartialEq, Eq)]
44+pub enum MailAttempt {
45+ /// Delivered. The body is blanked.
46+ Sent,
47+ /// Failed, and another attempt is scheduled at `next_at`.
48+ Retry {
49+ /// The stamp of the next attempt.
50+ next_at: String,
51+ /// A short reason for the operator. Never contains the body.
52+ error: String,
53+ },
54+ /// Failed for the last time. The body is blanked.
55+ Abandon {
56+ /// A short reason for the operator.
57+ error: String,
58+ },
59+}
60+
61+/// The fields of one outbox row that the admin pages and the tests read.
62+#[derive(Debug, Clone, PartialEq, Eq)]
63+pub struct MailRow {
64+ /// The kind of the mail.
65+ pub kind: String,
66+ /// `pending`, `sent`, `failed` or `abandoned`.
67+ pub state: String,
68+ /// Attempts made so far.
69+ pub attempts: i64,
70+ /// The stamp of the next attempt.
71+ pub next_attempt_at: String,
72+ /// The reason of the last failure, if any.
73+ pub last_error: Option<String>,
74+}
75+
76+fn map_job(row: &turso::Row) -> Result<MailJob> {
77+ Ok(MailJob {
78+ id: col_text(row, 0)?,
79+ kind: col_text(row, 1)?,
80+ to_addr: col_text(row, 2)?,
81+ subject: col_text(row, 3)?,
82+ sealed_body: col_text(row, 4)?,
83+ attempts: col_int(row, 5)?,
84+ })
85+}
86+
87+impl Store {
88+ /// Adds a mail to the outbox, to be sent as soon as the worker looks. Returns its id.
89+ pub async fn enqueue_mail(&self, new: &NewMail<'_>) -> Result<String> {
90+ let id = new_id();
91+ let now = now_stamp();
92+ let conn = self.inner.conn.lock().await;
93+ conn.execute(
94+ "INSERT INTO mail_outbox (id, kind, to_addr, subject, body_text, state, attempts, \
95+ next_attempt_at, created_at) VALUES (?1, ?2, ?3, ?4, ?5, 'pending', 0, ?6, ?6)",
96+ (
97+ id.clone(),
98+ new.kind.to_string(),
99+ new.to_addr.to_string(),
100+ new.subject.to_string(),
101+ new.sealed_body.to_string(),
102+ now,
103+ ),
104+ )
105+ .await
106+ .map_err(db_err)?;
107+ Ok(id)
108+ }
109+
110+ /// Rows that are due: never tried, or failed and whose retry time has come. Oldest first.
111+ pub async fn due_mail(&self, now: &str, limit: i64) -> Result<Vec<MailJob>> {
112+ let conn = self.read_conn().await;
113+ fetch_all(
114+ &conn,
115+ "SELECT id, kind, to_addr, subject, body_text, attempts FROM mail_outbox \
116+ WHERE state IN ('pending', 'failed') AND next_attempt_at <= ?1 \
117+ ORDER BY next_attempt_at, id LIMIT ?2",
118+ (now.to_string(), limit),
119+ map_job,
120+ )
121+ .await
122+ }
123+
124+ /// Records the outcome of one attempt. The attempt count goes up by one in the same statement.
125+ /// A sent or abandoned row loses its body in that statement too.
126+ pub async fn record_mail_attempt(&self, id: &str, attempt: &MailAttempt) -> Result<()> {
127+ let conn = self.inner.conn.lock().await;
128+ let now = now_stamp();
129+ let outcome = match attempt {
130+ MailAttempt::Sent => {
131+ conn.execute(
132+ "UPDATE mail_outbox SET state = 'sent', attempts = attempts + 1, sent_at = ?2, \
133+ body_text = '', last_error = NULL WHERE id = ?1",
134+ (id.to_string(), now),
135+ )
136+ .await
137+ }
138+ MailAttempt::Retry { next_at, error } => {
139+ conn.execute(
140+ "UPDATE mail_outbox SET state = 'failed', attempts = attempts + 1, \
141+ next_attempt_at = ?2, last_error = ?3 WHERE id = ?1",
142+ (id.to_string(), next_at.clone(), error.clone()),
143+ )
144+ .await
145+ }
146+ MailAttempt::Abandon { error } => {
147+ conn.execute(
148+ "UPDATE mail_outbox SET state = 'abandoned', attempts = attempts + 1, \
149+ body_text = '', last_error = ?2 WHERE id = ?1",
150+ (id.to_string(), error.clone()),
151+ )
152+ .await
153+ }
154+ };
155+ outcome.map_err(db_err)?;
156+ Ok(())
157+ }
158+
159+ /// The fields of one row, or `None`.
160+ pub async fn mail_row(&self, id: &str) -> Result<Option<MailRow>> {
161+ let conn = self.read_conn().await;
162+ fetch_opt(
163+ &conn,
164+ "SELECT kind, state, attempts, next_attempt_at, last_error FROM mail_outbox WHERE id = ?1",
165+ (id.to_string(),),
166+ |row| {
167+ Ok(MailRow {
168+ kind: col_text(row, 0)?,
169+ state: col_text(row, 1)?,
170+ attempts: col_int(row, 2)?,
171+ next_attempt_at: col_text(row, 3)?,
172+ last_error: col_opt_text(row, 4)?,
173+ })
174+ },
175+ )
176+ .await
177+ }
178+
179+ /// Deletes sent rows sent before `cutoff`. Returns how many were removed. Run by the sweeper.
180+ pub async fn prune_sent_mail(&self, cutoff: &str) -> Result<u64> {
181+ let conn = self.inner.conn.lock().await;
182+ conn.execute(
183+ "DELETE FROM mail_outbox WHERE state = 'sent' AND sent_at < ?1",
184+ (cutoff.to_string(),),
185+ )
186+ .await
187+ .map_err(db_err)
188+ }
189+}
190+
191+#[cfg(test)]
192+mod tests {
193+ use super::*;
194+
195+ #[tokio::test]
196+ async fn a_failed_attempt_is_retried_and_the_last_one_blanks_the_body() {
197+ let dir = tempfile::tempdir().unwrap();
198+ let store = Store::open(&dir.path().join("im.db")).await.unwrap();
199+ let id = store
200+ .enqueue_mail(&NewMail {
201+ kind: "reset",
202+ to_addr: "ada@example.com",
203+ subject: "Reset",
204+ sealed_body: "v1:sealed",
205+ })
206+ .await
207+ .unwrap();
208+ let now = now_stamp();
209+ assert_eq!(store.due_mail(&now, 10).await.unwrap().len(), 1);
210+ store
211+ .record_mail_attempt(
212+ &id,
213+ &MailAttempt::Retry {
214+ next_at: crate::time::stamp_after(std::time::Duration::from_secs(60)),
215+ error: "connection refused".into(),
216+ },
217+ )
218+ .await
219+ .unwrap();
220+ assert!(store.due_mail(&now, 10).await.unwrap().is_empty());
221+ let row = store.mail_row(&id).await.unwrap().unwrap();
222+ assert_eq!((row.state.as_str(), row.attempts), ("failed", 1));
223+ store
224+ .record_mail_attempt(
225+ &id,
226+ &MailAttempt::Abandon {
227+ error: "gave up".into(),
228+ },
229+ )
230+ .await
231+ .unwrap();
232+ let row = store.mail_row(&id).await.unwrap().unwrap();
233+ assert_eq!((row.state.as_str(), row.attempts), ("abandoned", 2));
234+ assert!(
235+ store
236+ .due_mail(
237+ &crate::time::stamp_after(std::time::Duration::from_secs(3600)),
238+ 10
239+ )
240+ .await
241+ .unwrap()
242+ .is_empty()
243+ );
244+ }
245+}
crates/im-core/src/store/mod.rsmodified+3 -0
@@ -10,7 +10,10 @@ pub mod audit;
10 pub mod backchannel;10 pub mod backchannel;
11 pub mod clients;11 pub mod clients;
12 pub mod directory;12 pub mod directory;
13+pub mod invites;
13 pub mod keys;14 pub mod keys;
15+pub mod links;
16+pub mod mail;
14 pub mod migrate;17 pub mod migrate;
15 pub mod oidc;18 pub mod oidc;
16 pub mod services;19 pub mod services;
crates/im-core/src/store/sessions.rsmodified+19 -0
@@ -132,6 +132,25 @@ pub(crate) async fn end_rows(
132 Ok(())132 Ok(())
133 }133 }
134 134
135+/// Ends every session of `user_id`, whatever its expiry, with the same back-channel rows as any other
136+/// end. Used when the password is reset. Runs inside the caller's transaction and returns the ids.
137+pub(crate) async fn end_all_sessions(
138+ conn: &Connection,
139+ user_id: &str,
140+ reason: EndReason,
141+ now: &str,
142+) -> Result<Vec<String>> {
143+ let ids = fetch_all(
144+ conn,
145+ "SELECT id FROM sessions WHERE user_id = ?1 ORDER BY created_at ASC, id ASC",
146+ (user_id.to_string(),),
147+ |row| col_text(row, 0),
148+ )
149+ .await?;
150+ end_rows(conn, user_id, &ids, reason, now).await?;
151+ Ok(ids)
152+}
153+
135 impl Store {154 impl Store {
136 /// Creates a session for a user who has just proved who they are.155 /// Creates a session for a user who has just proved who they are.
137 ///156 ///
crates/im-core/src/store/users.rsmodified+1 -1
@@ -53,7 +53,7 @@ pub(crate) fn map_user(row: &Row) -> Result<User> {
53 53
54 /// Maps an insert error. A UNIQUE violation is a conflict for the person; anything else is a54 /// Maps an insert error. A UNIQUE violation is a conflict for the person; anything else is a
55 /// database failure.55 /// database failure.
56-fn insert_error(e: turso::Error) -> Error {56+pub(crate) fn insert_error(e: turso::Error) -> Error {
57 let text = e.to_string();57 let text = e.to_string();
58 if text.contains("UNIQUE") {58 if text.contains("UNIQUE") {
59 Error::Conflict("that email address is already registered".into())59 Error::Conflict("that email address is already registered".into())
crates/im-web/Cargo.tomlmodified+1 -0
@@ -14,6 +14,7 @@ base64.workspace = true
14 futures-util.workspace = true14 futures-util.workspace = true
15 http.workspace = true15 http.workspace = true
16 im-core.workspace = true16 im-core.workspace = true
17+lettre.workspace = true
17 qrcode.workspace = true18 qrcode.workspace = true
18 reqwest.workspace = true19 reqwest.workspace = true
19 serde.workspace = true20 serde.workspace = true
crates/im-web/src/boot.rsmodified+8 -0
@@ -23,6 +23,7 @@ use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService
23 use crate::api::directory::StreamSlots;23 use crate::api::directory::StreamSlots;
24 use crate::backchannel;24 use crate::backchannel;
25 use crate::live::LiveHub;25 use crate::live::LiveHub;
26+use crate::mail;
26 use crate::oidc::signing;27 use crate::oidc::signing;
27 use crate::pages::not_found::NotFoundLayer;28 use crate::pages::not_found::NotFoundLayer;
28 use crate::pages::profile::PHOTO_ROUTE;29 use crate::pages::profile::PHOTO_ROUTE;
@@ -95,6 +96,12 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> {
95 stop_rx.clone(),96 stop_rx.clone(),
96 );97 );
97 let sweeper_task = sweeper::spawn(state.store.clone(), stop_rx.clone());98 let sweeper_task = sweeper::spawn(state.store.clone(), stop_rx.clone());
99+ let mail_worker = mail::worker::spawn(
100+ state.store.clone(),
101+ state.key.clone(),
102+ state.config.smtp.clone(),
103+ stop_rx.clone(),
104+ );
98 105
99 topcoat::serve_until(106 topcoat::serve_until(
100 listener,107 listener,
@@ -105,6 +112,7 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> {
105 let _ = signing_worker.await;112 let _ = signing_worker.await;
106 let _ = backchannel_worker.await;113 let _ = backchannel_worker.await;
107 let _ = sweeper_task.await;114 let _ = sweeper_task.await;
115+ let _ = mail_worker.await;
108 tracing::info!("im stopped");116 tracing::info!("im stopped");
109 Ok(())117 Ok(())
110 }118 }
crates/im-web/src/i18n/account.rsmodified+2 -2
@@ -484,10 +484,10 @@ pub fn text(lang: Lang, key: Txt) -> &'static str {
484 (Txt::PhotoOfPerson, Lang::En) => "Photo of this person",484 (Txt::PhotoOfPerson, Lang::En) => "Photo of this person",
485 (Txt::PhotoOfPerson, Lang::Tr) => "Bu kişinin fotoğrafı",485 (Txt::PhotoOfPerson, Lang::Tr) => "Bu kişinin fotoğrafı",
486 (Txt::EmailLaterNote, Lang::En) => {486 (Txt::EmailLaterNote, Lang::En) => {
487- "Changing your email address is not available yet. It will need a confirmation link sent to both addresses."487+ "To change it, use the link below. Both the current and the new address get a confirmation link."
488 }488 }
489 (Txt::EmailLaterNote, Lang::Tr) => {489 (Txt::EmailLaterNote, Lang::Tr) => {
490- "E-posta adresinizi değiştirme henüz kullanılamıyor. İki adrese de onay bağlantısı gönderilecek."490+ "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."
491 }491 }
492 (Txt::SavedName, Lang::En) => "Your name was saved.",492 (Txt::SavedName, Lang::En) => "Your name was saved.",
493 (Txt::SavedName, Lang::Tr) => "Adınız kaydedildi.",493 (Txt::SavedName, Lang::Tr) => "Adınız kaydedildi.",
crates/im-web/src/i18n/flows.rsadded+201 -0
@@ -0,0 +1,201 @@
1+//! Strings of the pages that run outside a session: forgot password, reset, invitation, the admin
2+//! invitation form, and the email change pages. Each key has an English and a Turkish text in [`text`];
3+//! the match is exhaustive. Shared phrases (email, password, policy messages) come from `account.rs`.
4+
5+use super::Lang;
6+
7+/// One phrase of the flow pages.
8+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9+pub enum Flow {
10+ /// Title of the forgot-password page, and of its link on the sign-in page.
11+ ForgotTitle,
12+ /// The sentence under the forgot-password title.
13+ ForgotIntro,
14+ /// The answer after any request. The same for known and unknown addresses.
15+ ForgotSent,
16+ /// The button that asks for the link.
17+ ForgotSubmit,
18+ /// The link back to sign-in.
19+ BackToSignIn,
20+ /// Title of the reset page.
21+ ResetTitle,
22+ /// The sentence under the reset title.
23+ ResetIntro,
24+ /// The button that sets the new password.
25+ ResetSubmit,
26+ /// Shown after a reset when the account has two-factor sign-in: it must sign in again with a code.
27+ /// Shown on the invitation page.
28+ InviteTitle,
29+ /// The sentence under the invitation title.
30+ InviteIntro,
31+ /// The button that creates the account.
32+ InviteSubmit,
33+ /// Title of the administrator invitation page.
34+ AdminInvitesTitle,
35+ /// The sentence under that title.
36+ AdminInvitesIntro,
37+ /// Checkbox: the invitee becomes an administrator.
38+ InviteAsAdmin,
39+ /// The button that sends the invitation.
40+ InviteSend,
41+ /// Notice after an invitation was queued.
42+ InviteQueued,
43+ /// Alert: the address already has an account.
44+ InviteAddressTaken,
45+ /// The profile link to the email change page.
46+ ChangeEmailLink,
47+ /// Title of the email change request page.
48+ EmailChangeTitle,
49+ /// The sentence under that title.
50+ EmailChangeIntro,
51+ /// Label of the current address (read only).
52+ CurrentAddress,
53+ /// Label of the new address.
54+ NewAddress,
55+ /// The button that sends both links.
56+ EmailChangeSubmit,
57+ /// Notice after both links were queued.
58+ EmailChangeQueued,
59+ /// Alert: the new address is the current one.
60+ EmailChangeSame,
61+ /// Alert: the new address belongs to an account, or cannot be used.
62+ EmailChangeUnavailable,
63+ /// Title of the page behind an email-change link.
64+ EmailLinkTitle,
65+ /// The button that confirms this half.
66+ EmailLinkConfirm,
67+ /// The button that cancels the whole change.
68+ EmailLinkCancel,
69+ /// Sentence under the confirm and cancel buttons.
70+ EmailLinkNote,
71+ /// Shown after this half is confirmed while the other half is still open.
72+ EmailLinkWaiting,
73+ /// Shown when the address changed.
74+ EmailLinkDone,
75+ /// Shown when the change was cancelled.
76+ EmailLinkCancelled,
77+ /// Shown when the change can no longer be applied (the address was taken meanwhile).
78+ EmailLinkRefused,
79+}
80+
81+/// The text of `key` in `lang`.
82+pub fn text(lang: Lang, key: Flow) -> &'static str {
83+ match (key, lang) {
84+ (Flow::ForgotTitle, Lang::En) => "Forgot your password?",
85+ (Flow::ForgotTitle, Lang::Tr) => "Parolanızı mı unuttunuz?",
86+ (Flow::ForgotIntro, Lang::En) => {
87+ "Enter the address of your account. If an account exists for it, we send a link to choose a new password."
88+ }
89+ (Flow::ForgotIntro, Lang::Tr) => {
90+ "Hesabınızın adresini girin. Bu adrese ait bir hesap varsa yeni parola seçmeniz için bir bağlantı göndeririz."
91+ }
92+ (Flow::ForgotSent, Lang::En) => {
93+ "If an account exists for that address, a link is on its way. Check your mail."
94+ }
95+ (Flow::ForgotSent, Lang::Tr) => {
96+ "Bu adrese ait bir hesap varsa bağlantı yolda. Posta kutunuzu kontrol edin."
97+ }
98+ (Flow::ForgotSubmit, Lang::En) => "Send the link",
99+ (Flow::ForgotSubmit, Lang::Tr) => "Bağlantıyı gönder",
100+ (Flow::BackToSignIn, Lang::En) => "Back to sign-in",
101+ (Flow::BackToSignIn, Lang::Tr) => "Girişe dön",
102+ (Flow::ResetTitle, Lang::En) => "Choose a new password",
103+ (Flow::ResetTitle, Lang::Tr) => "Yeni bir parola seçin",
104+ (Flow::ResetIntro, Lang::En) => {
105+ "Set a new password for your account. The link works only once, and every signed-in session ends when you save."
106+ }
107+ (Flow::ResetIntro, Lang::Tr) => {
108+ "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."
109+ }
110+ (Flow::ResetSubmit, Lang::En) => "Save the new password",
111+ (Flow::ResetSubmit, Lang::Tr) => "Yeni parolayı kaydet",
112+ (Flow::InviteTitle, Lang::En) => "Join im",
113+ (Flow::InviteTitle, Lang::Tr) => "im'e katılın",
114+ (Flow::InviteIntro, Lang::En) => {
115+ "An administrator invited you. Choose your name and a password to create your account."
116+ }
117+ (Flow::InviteIntro, Lang::Tr) => {
118+ "Bir yönetici sizi davet etti. Hesabınızı oluşturmak için adınızı ve bir parola seçin."
119+ }
120+ (Flow::InviteSubmit, Lang::En) => "Create my account",
121+ (Flow::InviteSubmit, Lang::Tr) => "Hesabımı oluştur",
122+ (Flow::AdminInvitesTitle, Lang::En) => "Invitations",
123+ (Flow::AdminInvitesTitle, Lang::Tr) => "Davetler",
124+ (Flow::AdminInvitesIntro, Lang::En) => {
125+ "Send an invitation to an address. The person chooses their own name and password."
126+ }
127+ (Flow::AdminInvitesIntro, Lang::Tr) => {
128+ "Bir adrese davet gönderin. Kişi kendi adını ve parolasını seçer."
129+ }
130+ (Flow::InviteAsAdmin, Lang::En) => "Make this person an administrator",
131+ (Flow::InviteAsAdmin, Lang::Tr) => "Bu kişiyi yönetici yap",
132+ (Flow::InviteSend, Lang::En) => "Send the invitation",
133+ (Flow::InviteSend, Lang::Tr) => "Daveti gönder",
134+ (Flow::InviteQueued, Lang::En) => "The invitation was queued for sending.",
135+ (Flow::InviteQueued, Lang::Tr) => "Davet gönderilmek üzere kuyruğa alındı.",
136+ (Flow::InviteAddressTaken, Lang::En) => "That address already has an account.",
137+ (Flow::InviteAddressTaken, Lang::Tr) => "Bu adrese ait bir hesap zaten var.",
138+ (Flow::ChangeEmailLink, Lang::En) => "Change email address",
139+ (Flow::ChangeEmailLink, Lang::Tr) => "E-posta adresini değiştir",
140+ (Flow::EmailChangeTitle, Lang::En) => "Change email address",
141+ (Flow::EmailChangeTitle, Lang::Tr) => "E-posta adresini değiştir",
142+ (Flow::EmailChangeIntro, Lang::En) => {
143+ "We send a link to the current address and one to the new address. The change happens when both are confirmed."
144+ }
145+ (Flow::EmailChangeIntro, Lang::Tr) => {
146+ "Mevcut adresinize ve yeni adresinize birer bağlantı göndeririz. İkisi de onaylanınca değişiklik gerçekleşir."
147+ }
148+ (Flow::CurrentAddress, Lang::En) => "Current address",
149+ (Flow::CurrentAddress, Lang::Tr) => "Mevcut adres",
150+ (Flow::NewAddress, Lang::En) => "New email address",
151+ (Flow::NewAddress, Lang::Tr) => "Yeni e-posta adresi",
152+ (Flow::EmailChangeSubmit, Lang::En) => "Send the links",
153+ (Flow::EmailChangeSubmit, Lang::Tr) => "Bağlantıları gönder",
154+ (Flow::EmailChangeQueued, Lang::En) => {
155+ "Links are on their way to both addresses. The change happens when both are confirmed."
156+ }
157+ (Flow::EmailChangeQueued, Lang::Tr) => {
158+ "Her iki adrese de bağlantılar yolda. İkisi de onaylanınca değişiklik gerçekleşir."
159+ }
160+ (Flow::EmailChangeSame, Lang::En) => "That is already the address of your account.",
161+ (Flow::EmailChangeSame, Lang::Tr) => "Bu zaten hesabınızın adresi.",
162+ (Flow::EmailChangeUnavailable, Lang::En) => "That address cannot be used.",
163+ (Flow::EmailChangeUnavailable, Lang::Tr) => "Bu adres kullanılamaz.",
164+ (Flow::EmailLinkTitle, Lang::En) => "Confirm the email change",
165+ (Flow::EmailLinkTitle, Lang::Tr) => "E-posta değişikliğini onaylayın",
166+ (Flow::EmailLinkConfirm, Lang::En) => "Confirm",
167+ (Flow::EmailLinkConfirm, Lang::Tr) => "Onayla",
168+ (Flow::EmailLinkCancel, Lang::En) => "Cancel the change",
169+ (Flow::EmailLinkCancel, Lang::Tr) => "Değişikliği iptal et",
170+ (Flow::EmailLinkNote, Lang::En) => {
171+ "If this was not you, cancel the change and then change your password."
172+ }
173+ (Flow::EmailLinkNote, Lang::Tr) => {
174+ "Bunu siz istemediyseniz değişikliği iptal edin ve sonra parolanızı değiştirin."
175+ }
176+ (Flow::EmailLinkWaiting, Lang::En) => {
177+ "Thank you. The change happens when the other address is confirmed too."
178+ }
179+ (Flow::EmailLinkWaiting, Lang::Tr) => {
180+ "Teşekkürler. Diğer adres de onaylanınca değişiklik gerçekleşir."
181+ }
182+ (Flow::EmailLinkDone, Lang::En) => "The address of your account has changed.",
183+ (Flow::EmailLinkDone, Lang::Tr) => "Hesabınızın adresi değişti.",
184+ (Flow::EmailLinkCancelled, Lang::En) => "The change was cancelled.",
185+ (Flow::EmailLinkCancelled, Lang::Tr) => "Değişiklik iptal edildi.",
186+ (Flow::EmailLinkRefused, Lang::En) => {
187+ "This change can no longer be completed. Start it again from your account."
188+ }
189+ (Flow::EmailLinkRefused, Lang::Tr) => {
190+ "Bu değişiklik artık tamamlanamaz. Hesabınızdan yeniden başlatın."
191+ }
192+ }
193+}
194+
195+/// The sentence on the link page that says what changes, with both addresses.
196+pub fn email_link_summary(lang: Lang, old: &str, new: &str) -> String {
197+ match lang {
198+ Lang::En => format!("The address of the account changes from {old} to {new}."),
199+ Lang::Tr => format!("Hesabın adresi {old} adresinden {new} adresine değişiyor."),
200+ }
201+}
crates/im-web/src/i18n/mail.rsadded+204 -0
@@ -0,0 +1,204 @@
1+//! Strings of the mail: subjects, the fixed sentences of each body, and the sentences with a value.
2+//!
3+//! Every key has an English and a Turkish text in [`text`]; the match is exhaustive, so a key without a
4+//! translation does not compile. Sentences with values (a day count, a new address) are built by the
5+//! helpers below, one format string per language, so word order is each language's own.
6+
7+use super::Lang;
8+
9+/// One fixed sentence or subject of a mail.
10+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11+pub enum MailKey {
12+ /// The closing line of every mail.
13+ Signature,
14+ /// Under a link the person did not ask for.
15+ Ignore,
16+ /// Subject of the invitation.
17+ InviteSubject,
18+ /// Label of the invitation link.
19+ InviteAction,
20+ /// Subject of the password-reset mail.
21+ ResetSubject,
22+ /// Label of the reset link.
23+ ResetAction,
24+ /// Sentence after the reset link, about what the reset does.
25+ ResetNote,
26+ /// Subject of the notice to the old address.
27+ EmailOldSubject,
28+ /// Label of the link on the old-address mail.
29+ EmailOldAction,
30+ /// Sentence after the old-address link: what to do if it was not the person.
31+ EmailOldNote,
32+ /// Subject of the confirmation to the new address.
33+ EmailNewSubject,
34+ /// Label of the link on the new-address mail.
35+ EmailNewAction,
36+ /// Subject of the notice that the address changed.
37+ EmailDoneSubject,
38+ /// Subject: the password was changed by the person.
39+ PasswordChangedSubject,
40+ /// Body: the password was changed by the person.
41+ PasswordChangedBody,
42+ /// Subject: the password was reset through a link.
43+ PasswordResetSubject,
44+ /// Body: the password was reset through a link.
45+ PasswordResetBody,
46+ /// Subject: two-factor sign-in was turned on.
47+ TwoFactorOnSubject,
48+ /// Body: two-factor sign-in was turned on.
49+ TwoFactorOnBody,
50+ /// Subject: two-factor sign-in was turned off.
51+ TwoFactorOffSubject,
52+ /// Body: two-factor sign-in was turned off.
53+ TwoFactorOffBody,
54+ /// Subject: new recovery codes were generated.
55+ RecoveryCodesSubject,
56+ /// Body: new recovery codes were generated.
57+ RecoveryCodesBody,
58+ /// The line under every security notice.
59+ SecurityNote,
60+}
61+
62+/// The text of `key` in `lang`.
63+pub fn text(lang: Lang, key: MailKey) -> &'static str {
64+ match (key, lang) {
65+ (MailKey::Signature, Lang::En) => "im, your family account service",
66+ (MailKey::Signature, Lang::Tr) => "im, aile hesap hizmetiniz",
67+ (MailKey::Ignore, Lang::En) => "If you did not expect this message, you can ignore it.",
68+ (MailKey::Ignore, Lang::Tr) => "Bu iletiyi beklemiyorsanız yok sayabilirsiniz.",
69+ (MailKey::InviteSubject, Lang::En) => "You are invited to im",
70+ (MailKey::InviteSubject, Lang::Tr) => "im'e davet edildiniz",
71+ (MailKey::InviteAction, Lang::En) => "Create your account",
72+ (MailKey::InviteAction, Lang::Tr) => "Hesabınızı oluşturun",
73+ (MailKey::ResetSubject, Lang::En) => "Reset your im password",
74+ (MailKey::ResetSubject, Lang::Tr) => "im parolanızı sıfırlayın",
75+ (MailKey::ResetAction, Lang::En) => "Choose a new password",
76+ (MailKey::ResetAction, Lang::Tr) => "Yeni bir parola seçin",
77+ (MailKey::ResetNote, Lang::En) => {
78+ "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."
79+ }
80+ (MailKey::ResetNote, Lang::Tr) => {
81+ "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."
82+ }
83+ (MailKey::EmailOldSubject, Lang::En) => {
84+ "Confirm or cancel the email change on your im account"
85+ }
86+ (MailKey::EmailOldSubject, Lang::Tr) => {
87+ "im hesabınızdaki e-posta değişikliğini onaylayın ya da iptal edin"
88+ }
89+ (MailKey::EmailOldAction, Lang::En) => "Review the change",
90+ (MailKey::EmailOldAction, Lang::Tr) => "Değişikliği inceleyin",
91+ (MailKey::EmailOldNote, Lang::En) => {
92+ "If this was not you, open the link and cancel the change, then change your password."
93+ }
94+ (MailKey::EmailOldNote, Lang::Tr) => {
95+ "Bunu siz istemediyseniz bağlantıyı açıp değişikliği iptal edin, sonra parolanızı değiştirin."
96+ }
97+ (MailKey::EmailNewSubject, Lang::En) => "Confirm this address for your im account",
98+ (MailKey::EmailNewSubject, Lang::Tr) => "Bu adresi im hesabınız için onaylayın",
99+ (MailKey::EmailNewAction, Lang::En) => "Confirm this address",
100+ (MailKey::EmailNewAction, Lang::Tr) => "Bu adresi onaylayın",
101+ (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",
103+ (MailKey::PasswordChangedSubject, Lang::En) => "Your im password was changed",
104+ (MailKey::PasswordChangedSubject, Lang::Tr) => "im parolanız değiştirildi",
105+ (MailKey::PasswordChangedBody, Lang::En) => {
106+ "The password of your account was changed. Your other signed-in sessions were ended."
107+ }
108+ (MailKey::PasswordChangedBody, Lang::Tr) => {
109+ "Hesabınızın parolası değiştirildi. Diğer açık oturumlarınız kapatıldı."
110+ }
111+ (MailKey::PasswordResetSubject, Lang::En) => "Your im password was reset",
112+ (MailKey::PasswordResetSubject, Lang::Tr) => "im parolanız sıfırlandı",
113+ (MailKey::PasswordResetBody, Lang::En) => {
114+ "The password of your account was reset with a link, and every session was ended."
115+ }
116+ (MailKey::PasswordResetBody, Lang::Tr) => {
117+ "Hesabınızın parolası bir bağlantıyla sıfırlandı ve tüm oturumlar kapatıldı."
118+ }
119+ (MailKey::TwoFactorOnSubject, Lang::En) => "Two-factor sign-in was turned on",
120+ (MailKey::TwoFactorOnSubject, Lang::Tr) => "İki adımlı giriş açıldı",
121+ (MailKey::TwoFactorOnBody, Lang::En) => "Two-factor sign-in is now on for your account.",
122+ (MailKey::TwoFactorOnBody, Lang::Tr) => "Hesabınızda iki adımlı giriş artık açık.",
123+ (MailKey::TwoFactorOffSubject, Lang::En) => "Two-factor sign-in was turned off",
124+ (MailKey::TwoFactorOffSubject, Lang::Tr) => "İki adımlı giriş kapatıldı",
125+ (MailKey::TwoFactorOffBody, Lang::En) => "Two-factor sign-in is now off for your account.",
126+ (MailKey::TwoFactorOffBody, Lang::Tr) => "Hesabınızda iki adımlı giriş artık kapalı.",
127+ (MailKey::RecoveryCodesSubject, Lang::En) => "New recovery codes were generated",
128+ (MailKey::RecoveryCodesSubject, Lang::Tr) => "Yeni kurtarma kodları üretildi",
129+ (MailKey::RecoveryCodesBody, Lang::En) => {
130+ "The recovery codes of your account were replaced. The old codes no longer work."
131+ }
132+ (MailKey::RecoveryCodesBody, Lang::Tr) => {
133+ "Hesabınızın kurtarma kodları yenilendi. Eski kodlar artık çalışmaz."
134+ }
135+ (MailKey::SecurityNote, Lang::En) => "If this was not you, reset your password now.",
136+ (MailKey::SecurityNote, Lang::Tr) => "Bunu siz yapmadıysanız hemen parolanızı sıfırlayın.",
137+ }
138+}
139+
140+/// The opening word of a mail, addressed to `name` when there is one.
141+pub fn greeting(lang: Lang, name: Option<&str>) -> String {
142+ match (lang, name) {
143+ (Lang::En, Some(name)) => format!("Hello {name},"),
144+ (Lang::En, None) => "Hello,".to_owned(),
145+ (Lang::Tr, Some(name)) => format!("Merhaba {name},"),
146+ (Lang::Tr, None) => "Merhaba,".to_owned(),
147+ }
148+}
149+
150+/// The sentence of the invitation, with the number of days it lasts.
151+pub fn invite_body(lang: Lang, days: u32) -> String {
152+ match lang {
153+ Lang::En => format!(
154+ "An administrator invited you to create an account. The link works for {days} days and only once."
155+ ),
156+ Lang::Tr => format!(
157+ "Bir yönetici sizi bir hesap oluşturmaya davet etti. Bağlantı {days} gün boyunca ve yalnız bir kez geçerlidir."
158+ ),
159+ }
160+}
161+
162+/// The sentence of the reset mail, with the number of minutes the link lasts.
163+pub fn reset_body(lang: Lang, minutes: u32) -> String {
164+ match lang {
165+ Lang::En => format!(
166+ "Someone asked to reset the password of your account. The link works for {minutes} minutes and only once."
167+ ),
168+ Lang::Tr => format!(
169+ "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."
170+ ),
171+ }
172+}
173+
174+/// The sentence sent to the old address, naming the new one and the hours the links last.
175+pub fn email_old_body(lang: Lang, new_email: &str, hours: u32) -> String {
176+ match lang {
177+ Lang::En => format!(
178+ "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."
179+ ),
180+ Lang::Tr => format!(
181+ "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."
182+ ),
183+ }
184+}
185+
186+/// The sentence sent to the new address.
187+pub fn email_new_body(lang: Lang, hours: u32) -> String {
188+ match lang {
189+ Lang::En => format!(
190+ "Someone asked to use this address for an im account. Confirm it to finish the change. The link works for {hours} hours."
191+ ),
192+ Lang::Tr => format!(
193+ "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."
194+ ),
195+ }
196+}
197+
198+/// The sentence that tells both addresses the change happened.
199+pub fn email_done_body(lang: Lang, new_email: &str) -> String {
200+ match lang {
201+ Lang::En => format!("The address of the account is now {new_email}."),
202+ Lang::Tr => format!("Hesabın adresi artık {new_email}."),
203+ }
204+}
crates/im-web/src/i18n/mod.rsmodified+2 -0
@@ -8,6 +8,8 @@
8 //! helper functions next to their keys.8 //! helper functions next to their keys.
9 9
10 pub mod account;10 pub mod account;
11+pub mod flows;
12+pub mod mail;
11 pub mod oidc;13 pub mod oidc;
12 pub mod shell;14 pub mod shell;
13 15
crates/im-web/src/mail/message.rsadded+138 -0
@@ -0,0 +1,138 @@
1+//! The lettre message, built from typed parts only.
2+//!
3+//! A [`Recipient`] and a [`Sender`] can exist only after their name and address have passed the same
4+//! rules as the rest of `im`. A display name with a control character (a line break included) or a
5+//! bidirectional override is refused here, so no header can be injected through a name. The message
6+//! is then assembled by lettre's builder, which writes each header value itself.
7+
8+use im_core::config::SmtpConfig;
9+use im_core::names::{parse_display_name, parse_email};
10+use lettre::Address;
11+use lettre::message::{Mailbox, Message, MultiPart};
12+
13+/// A recipient whose name and address have been checked.
14+#[derive(Debug, Clone, PartialEq, Eq)]
15+pub struct Recipient {
16+ name: Option<String>,
17+ email: String,
18+}
19+
20+impl Recipient {
21+ /// Checks a recipient. The name is optional; when given it must pass [`parse_display_name`]. The
22+ /// address must pass [`parse_email`] and is stored in its normalised form.
23+ pub fn new(name: Option<&str>, email: &str) -> Result<Self, &'static str> {
24+ let name = match name {
25+ Some(name) => {
26+ Some(parse_display_name(name).map_err(|_| "recipient name is not valid")?)
27+ }
28+ None => None,
29+ };
30+ let email = parse_email(email).map_err(|_| "recipient address is not valid")?;
31+ Ok(Self { name, email })
32+ }
33+
34+ /// The checked display name, if any.
35+ pub fn name(&self) -> Option<&str> {
36+ self.name.as_deref()
37+ }
38+
39+ /// The checked address.
40+ pub fn email(&self) -> &str {
41+ &self.email
42+ }
43+
44+ fn mailbox(&self) -> Result<Mailbox, &'static str> {
45+ let address: Address = self
46+ .email
47+ .parse()
48+ .map_err(|_| "recipient address is not valid")?;
49+ Ok(Mailbox::new(self.name.clone(), address))
50+ }
51+}
52+
53+/// The sender of every mail, from the SMTP section of the config.
54+#[derive(Debug, Clone)]
55+pub struct Sender {
56+ mailbox: Mailbox,
57+}
58+
59+impl Sender {
60+ /// The sender of the config. Fails when `from` or `from_name` is not valid; the config check rejects
61+ /// those at boot, so this only guards a config built in code.
62+ pub fn from_config(smtp: &SmtpConfig) -> Result<Self, &'static str> {
63+ let email = parse_email(&smtp.from).map_err(|_| "sender address is not valid")?;
64+ let name = parse_display_name(&smtp.from_name).map_err(|_| "sender name is not valid")?;
65+ let address: Address = email.parse().map_err(|_| "sender address is not valid")?;
66+ Ok(Self {
67+ mailbox: Mailbox::new(Some(name), address),
68+ })
69+ }
70+}
71+
72+/// Builds a `multipart/alternative` message with a plain-text and an HTML part. The subject is the
73+/// only other text, and it comes from fixed strings.
74+pub fn build(
75+ sender: &Sender,
76+ to: &Recipient,
77+ subject: &str,
78+ text: String,
79+ html: String,
80+) -> Result<Message, &'static str> {
81+ Message::builder()
82+ .from(sender.mailbox.clone())
83+ .to(to.mailbox()?)
84+ .subject(subject)
85+ .multipart(MultiPart::alternative_plain_html(text, html))
86+ .map_err(|_| "message could not be built")
87+}
88+
89+#[cfg(test)]
90+mod tests {
91+ use super::*;
92+
93+ fn sender() -> Sender {
94+ Sender::from_config(&SmtpConfig {
95+ host: "127.0.0.1".into(),
96+ from: "im@example.com".into(),
97+ ..SmtpConfig::default()
98+ })
99+ .expect("sender")
100+ }
101+
102+ #[test]
103+ fn a_name_with_a_line_break_cannot_add_a_header() {
104+ // The attack: a name that ends the To header and starts a Bcc header.
105+ let attack = Recipient::new(Some("Ada\r\nBcc: victim@example.com"), "ada@example.com");
106+ assert!(attack.is_err());
107+ assert!(Recipient::new(Some("Ada\nBcc: x@example.com"), "ada@example.com").is_err());
108+ }
109+
110+ #[test]
111+ fn a_hard_name_is_encoded_and_the_headers_stay_clean() {
112+ let to = Recipient::new(Some("Ada \"Lovelace\", Jr. Ayşe"), "ada@example.com")
113+ .expect("valid name");
114+ let message = build(
115+ &sender(),
116+ &to,
117+ "Subject",
118+ "text".into(),
119+ "<p>html</p>".into(),
120+ )
121+ .expect("message");
122+ let raw = String::from_utf8_lossy(&message.formatted()).into_owned();
123+ let headers = raw.split("\r\n\r\n").next().unwrap_or_default();
124+ assert!(!headers.contains("Bcc:"), "{headers}");
125+ let to_lines = headers
126+ .lines()
127+ .filter(|line| line.starts_with("To:"))
128+ .count();
129+ assert_eq!(to_lines, 1, "{headers}");
130+ assert_eq!(
131+ headers
132+ .lines()
133+ .filter(|l| l.starts_with("Subject:"))
134+ .count(),
135+ 1
136+ );
137+ }
138+}
crates/im-web/src/mail/mod.rsadded+153 -0
@@ -0,0 +1,153 @@
1+//! Outbound mail: what each mail says, how it is queued, and how the queue is sent.
2+//!
3+//! A mail is queued with [`queue`]: its text is rendered in the recipient's language, then sealed under the
4+//! instance key and stored in `mail_outbox` (architecture section 3). The worker in [`worker`] sends the
5+//! queued rows with retries. Nothing in this module logs a body, a link or a recipient address.
6+//!
7+//! - [`message`] builds the lettre message from typed parts only. A name or address that is not valid is
8+//! refused before any header is written, so no user text can add a header.
9+//! - [`templates`] renders the text and HTML of each kind. Every value goes through HTML escaping.
10+//! - [`transport`] builds the SMTP connection from the config, reading the password file each time.
11+
12+pub mod message;
13+pub mod templates;
14+pub mod transport;
15+pub mod worker;
16+
17+use im_core::Result;
18+use im_core::model::User;
19+use im_core::secret;
20+use im_core::store::Store;
21+use im_core::store::mail::NewMail;
22+use serde_json::json;
23+
24+use crate::i18n::Lang;
25+pub use message::Recipient;
26+
27+/// The security notices sent to the account's own address. Each is kind `security`.
28+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29+pub enum Notice {
30+ /// The password was changed on the security page.
31+ PasswordChanged,
32+ /// The password was set through a reset link.
33+ PasswordReset,
34+ /// Two-factor sign-in was turned on.
35+ TwoFactorOn,
36+ /// Two-factor sign-in was turned off.
37+ TwoFactorOff,
38+ /// The recovery codes were replaced.
39+ RecoveryCodes,
40+}
41+
42+/// One kind of mail, with the values its text needs. A link is already built by the caller.
43+#[derive(Clone, Copy, Debug)]
44+pub enum Mail<'a> {
45+ /// An administrator invited the recipient to create an account.
46+ Invite {
47+ /// The invitation link.
48+ link: &'a str,
49+ /// Days the link lasts.
50+ days: u32,
51+ },
52+ /// A password reset was asked for.
53+ Reset {
54+ /// The reset link.
55+ link: &'a str,
56+ /// Minutes the link lasts.
57+ minutes: u32,
58+ },
59+ /// Sent to the current address of an email change, with the cancel-or-confirm link.
60+ EmailOld {
61+ /// The link of the old half.
62+ link: &'a str,
63+ /// The address the account would move to.
64+ new_email: &'a str,
65+ /// Hours the link lasts.
66+ hours: u32,
67+ },
68+ /// Sent to the new address of an email change.
69+ EmailNew {
70+ /// The link of the new half.
71+ link: &'a str,
72+ /// Hours the link lasts.
73+ hours: u32,
74+ },
75+ /// The change happened. Sent to both addresses.
76+ EmailDone {
77+ /// The address the account has now.
78+ new_email: &'a str,
79+ },
80+ /// A security notice.
81+ Security(Notice),
82+}
83+
84+impl Mail<'_> {
85+ /// The stored kind, one of the values `mail_outbox.kind` allows.
86+ pub fn kind(&self) -> &'static str {
87+ match self {
88+ Mail::Invite { .. } => "invite",
89+ Mail::Reset { .. } => "reset",
90+ Mail::EmailOld { .. } => "email_old",
91+ Mail::EmailNew { .. } => "email_new",
92+ Mail::EmailDone { .. } => "email_done",
93+ Mail::Security(_) => "security",
94+ }
95+ }
96+}
97+
98+/// The language a mail to `user` is written in: the stored choice, unless the person chose the
99+/// browser's language. Then the language of the request that triggered the mail.
100+pub fn lang_for(user: &User, request: Lang) -> Lang {
101+ if user.locale_auto {
102+ request
103+ } else {
104+ Lang::from_code(&user.locale).unwrap_or(request)
105+ }
106+}
107+
108+/// Renders `mail` for `to` in `lang`, seals it, and adds it to the outbox. The subject is fixed text;
109+/// the body (text and HTML, with the recipient's name) is sealed as one JSON document.
110+pub async fn queue(
111+ store: &Store,
112+ key: &[u8; 32],
113+ to: &Recipient,
114+ lang: Lang,
115+ mail: &Mail<'_>,
116+) -> Result<()> {
117+ let rendered = templates::render(lang, to.name(), mail);
118+ let payload = json!({
119+ "to_name": to.name(),
120+ "text": rendered.text,
121+ "html": rendered.html,
122+ })
123+ .to_string();
124+ let sealed = secret::seal(key, payload.as_bytes())?;
125+ store
126+ .enqueue_mail(&NewMail {
127+ kind: mail.kind(),
128+ to_addr: to.email(),
129+ subject: &rendered.subject,
130+ sealed_body: &sealed,
131+ })
132+ .await?;
133+ Ok(())
134+}
135+
136+/// Queues a security notice for the account's own address, in the person's language. A failure is
137+/// logged and never reaches the caller: the change it reports has already been made.
138+pub async fn notify(store: &Store, key: &[u8; 32], user: &User, request: Lang, notice: Notice) {
139+ let to = match Recipient::new(Some(&user.name), &user.email) {
140+ Ok(to) => to,
141+ Err(error) => {
142+ tracing::error!(
143+ error,
144+ "security notice not queued: stored address is not valid"
145+ );
146+ return;
147+ }
148+ };
149+ let lang = lang_for(user, request);
150+ if let Err(error) = queue(store, key, &to, lang, &Mail::Security(notice)).await {
151+ tracing::error!(error = %error, "security notice not queued");
152+ }
153+}
crates/im-web/src/mail/templates.rsadded+194 -0
@@ -0,0 +1,194 @@
1+//! The text and HTML of each mail kind. One function builds both from the same parts, so the two
2+//! alternatives always say the same thing. Every value is HTML-escaped, including the links.
3+
4+use super::{Mail, Notice};
5+use crate::i18n::Lang;
6+use crate::i18n::mail::{
7+ MailKey, email_done_body, email_new_body, email_old_body, greeting, invite_body, reset_body,
8+ text,
9+};
10+
11+/// The rendered subject, plain-text body and HTML body of one mail.
12+#[derive(Debug, Clone, PartialEq, Eq)]
13+pub struct Rendered {
14+ /// The subject line.
15+ pub subject: String,
16+ /// The plain-text alternative.
17+ pub text: String,
18+ /// The HTML alternative.
19+ pub html: String,
20+}
21+
22+/// The parts of a mail, in reading order: a greeting, paragraphs, an optional action link with the
23+/// address printed under it, and a closing.
24+struct Parts {
25+ subject: String,
26+ greeting: String,
27+ paragraphs: Vec<String>,
28+ action: Option<(String, String)>,
29+ closing: Vec<String>,
30+}
31+
32+/// Renders `mail` for a recipient named `name` (when known) in `lang`.
33+pub fn render(lang: Lang, name: Option<&str>, mail: &Mail<'_>) -> Rendered {
34+ let parts = parts(lang, name, mail);
35+ Rendered {
36+ subject: parts.subject.clone(),
37+ text: as_text(&parts),
38+ html: as_html(&parts, lang),
39+ }
40+}
41+
42+fn parts(lang: Lang, name: Option<&str>, mail: &Mail<'_>) -> Parts {
43+ let key = |k: MailKey| text(lang, k).to_owned();
44+ let greeting = greeting(lang, name);
45+ let ignore = key(MailKey::Ignore);
46+ let signature = key(MailKey::Signature);
47+ match *mail {
48+ Mail::Invite { link, days } => Parts {
49+ subject: key(MailKey::InviteSubject),
50+ greeting,
51+ paragraphs: vec![invite_body(lang, days)],
52+ action: Some((key(MailKey::InviteAction), link.to_owned())),
53+ closing: vec![ignore, signature],
54+ },
55+ Mail::Reset { link, minutes } => Parts {
56+ subject: key(MailKey::ResetSubject),
57+ greeting,
58+ paragraphs: vec![reset_body(lang, minutes), key(MailKey::ResetNote)],
59+ action: Some((key(MailKey::ResetAction), link.to_owned())),
60+ closing: vec![ignore, signature],
61+ },
62+ Mail::EmailOld {
63+ link,
64+ new_email,
65+ hours,
66+ } => Parts {
67+ subject: key(MailKey::EmailOldSubject),
68+ greeting,
69+ paragraphs: vec![
70+ email_old_body(lang, new_email, hours),
71+ key(MailKey::EmailOldNote),
72+ ],
73+ action: Some((key(MailKey::EmailOldAction), link.to_owned())),
74+ closing: vec![signature],
75+ },
76+ Mail::EmailNew { link, hours } => Parts {
77+ subject: key(MailKey::EmailNewSubject),
78+ greeting,
79+ paragraphs: vec![email_new_body(lang, hours)],
80+ action: Some((key(MailKey::EmailNewAction), link.to_owned())),
81+ closing: vec![ignore, signature],
82+ },
83+ Mail::EmailDone { new_email } => Parts {
84+ subject: key(MailKey::EmailDoneSubject),
85+ greeting,
86+ paragraphs: vec![email_done_body(lang, new_email)],
87+ action: None,
88+ closing: vec![ignore, signature],
89+ },
90+ Mail::Security(notice) => {
91+ let (subject, body) = match notice {
92+ Notice::PasswordChanged => (
93+ MailKey::PasswordChangedSubject,
94+ MailKey::PasswordChangedBody,
95+ ),
96+ Notice::PasswordReset => {
97+ (MailKey::PasswordResetSubject, MailKey::PasswordResetBody)
98+ }
99+ Notice::TwoFactorOn => (MailKey::TwoFactorOnSubject, MailKey::TwoFactorOnBody),
100+ Notice::TwoFactorOff => (MailKey::TwoFactorOffSubject, MailKey::TwoFactorOffBody),
101+ Notice::RecoveryCodes => {
102+ (MailKey::RecoveryCodesSubject, MailKey::RecoveryCodesBody)
103+ }
104+ };
105+ Parts {
106+ subject: key(subject),
107+ greeting,
108+ paragraphs: vec![key(body), key(MailKey::SecurityNote)],
109+ action: None,
110+ closing: vec![signature],
111+ }
112+ }
113+ }
114+}
115+
116+fn as_text(parts: &Parts) -> String {
117+ let mut blocks = vec![parts.greeting.clone()];
118+ blocks.extend(parts.paragraphs.iter().cloned());
119+ if let Some((label, url)) = &parts.action {
120+ blocks.push(format!("{label}: {url}"));
121+ }
122+ blocks.extend(parts.closing.iter().cloned());
123+ blocks.join("\n\n") + "\n"
124+}
125+
126+fn as_html(parts: &Parts, lang: Lang) -> String {
127+ let esc = escape_html;
128+ let mut body = format!("<p>{}</p>", esc(&parts.greeting));
129+ for paragraph in &parts.paragraphs {
130+ body.push_str(&format!("<p>{}</p>", esc(paragraph)));
131+ }
132+ if let Some((label, url)) = &parts.action {
133+ body.push_str(&format!(
134+ "<p><a href=\"{href}\">{label}</a></p><p>{url}</p>",
135+ href = esc(url),
136+ label = esc(label),
137+ url = esc(url),
138+ ));
139+ }
140+ for line in &parts.closing {
141+ body.push_str(&format!("<p>{}</p>", esc(line)));
142+ }
143+ format!(
144+ "<!DOCTYPE html>\n<html lang=\"{code}\">\n<head><meta charset=\"utf-8\"><title>{title}</title></head>\n<body>\n{body}\n</body>\n</html>\n",
145+ code = lang.code(),
146+ title = esc(&parts.subject),
147+ )
148+}
149+
150+/// Escapes the five characters that are special in HTML text and in quoted attributes.
151+pub fn escape_html(input: &str) -> String {
152+ let mut out = String::with_capacity(input.len());
153+ for c in input.chars() {
154+ match c {
155+ '&' => out.push_str("&amp;"),
156+ '<' => out.push_str("&lt;"),
157+ '>' => out.push_str("&gt;"),
158+ '"' => out.push_str("&quot;"),
159+ '\'' => out.push_str("&#x27;"),
160+ other => out.push(other),
161+ }
162+ }
163+ out
164+}
165+
166+#[cfg(test)]
167+mod tests {
168+ use super::*;
169+
170+ #[test]
171+ fn values_are_escaped_in_the_html_and_the_text_keeps_them_verbatim() {
172+ let hostile = "https://ex.test/x?a=1&b=<script>";
173+ let rendered = render(
174+ Lang::En,
175+ None,
176+ &Mail::Invite {
177+ link: hostile,
178+ days: 7,
179+ },
180+ );
181+ assert!(rendered.html.contains("&lt;script&gt;"));
182+ assert!(!rendered.html.contains("<script>"));
183+ assert!(rendered.text.contains(hostile));
184+ assert!(rendered.html.contains("lang=\"en\""));
185+ }
186+
187+ #[test]
188+ fn both_languages_render_their_own_subject() {
189+ let en = render(Lang::En, None, &Mail::Security(Notice::TwoFactorOn));
190+ let tr = render(Lang::Tr, None, &Mail::Security(Notice::TwoFactorOn));
191+ assert_ne!(en.subject, tr.subject);
192+ assert!(tr.html.contains("lang=\"tr\""));
193+ }
194+}
crates/im-web/src/mail/transport.rsadded+60 -0
@@ -0,0 +1,60 @@
1+//! The SMTP connection, built from the `[smtp]` config.
2+//!
3+//! Implicit TLS and STARTTLS both verify the server certificate against the bundled web PKI roots (the
4+//! `tokio1-rustls-tls` feature). Plain SMTP is only built for localhost, and the config already refuses it
5+//! for any other host. The password is read from its file on every call, so a rotated file takes effect
6+//! at the next batch without a restart.
7+
8+use std::path::Path;
9+use std::time::Duration;
10+
11+use im_core::config::{SmtpConfig, SmtpTls};
12+use lettre::transport::smtp::authentication::Credentials;
13+use lettre::{AsyncSmtpTransport, Tokio1Executor};
14+
15+/// The concrete transport the worker uses.
16+pub type SmtpTransport = AsyncSmtpTransport<Tokio1Executor>;
17+
18+/// How long one SMTP conversation may take before it counts as a failed attempt.
19+const TIMEOUT: Duration = Duration::from_secs(30);
20+
21+/// Reads the first line of the password file. Refused when the file is readable by group or others,
22+/// because the password would then be readable by other local users.
23+pub fn read_password(path: &Path) -> Result<String, String> {
24+ #[cfg(unix)]
25+ {
26+ use std::os::unix::fs::PermissionsExt;
27+ let mode = std::fs::metadata(path)
28+ .map_err(|e| format!("password file: {e}"))?
29+ .permissions()
30+ .mode();
31+ if mode & 0o077 != 0 {
32+ return Err("password file is readable by group or others; expected 0600".into());
33+ }
34+ }
35+ let text = std::fs::read_to_string(path).map_err(|e| format!("password file: {e}"))?;
36+ let line = text.lines().next().unwrap_or_default().trim_end();
37+ if line.is_empty() {
38+ return Err("password file is empty".into());
39+ }
40+ Ok(line.to_owned())
41+}
42+
43+/// Builds the transport for `smtp`. `password` is used only when the config names a username.
44+pub fn build(smtp: &SmtpConfig, password: Option<String>) -> Result<SmtpTransport, String> {
45+ let host = smtp.host.as_str();
46+ let builder = match smtp.tls {
47+ SmtpTls::Implicit => AsyncSmtpTransport::<Tokio1Executor>::relay(host),
48+ SmtpTls::Starttls => AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(host),
49+ SmtpTls::None => Ok(AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(
50+ host,
51+ )),
52+ }
53+ .map_err(|e| format!("smtp host: {e}"))?;
54+ let mut builder = builder.port(smtp.port).timeout(Some(TIMEOUT));
55+ if !smtp.username.is_empty() {
56+ let password = password.ok_or("no password for the smtp login")?;
57+ builder = builder.credentials(Credentials::new(smtp.username.clone(), password));
58+ }
59+ Ok(builder.build())
60+}
crates/im-web/src/mail/worker.rsadded+192 -0
@@ -0,0 +1,192 @@
1+//! The mail worker (architecture section 8): sends the outbox, with retries.
2+//!
3+//! A row is tried when it is due. A failed try is retried after 1, 5, 15 and 60 minutes; the fifth
4+//! failure abandons the row. A sent or abandoned row loses its sealed body in the same write. With no
5+//! sender configured the rows wait untouched, and a sender that cannot be built (for example an unreadable
6+//! password file) also spends no attempt.
7+
8+use std::sync::Arc;
9+use std::time::Duration;
10+
11+use im_core::config::SmtpConfig;
12+use im_core::secret;
13+use im_core::store::Store;
14+use im_core::store::mail::{MailAttempt, MailJob};
15+use im_core::time::{now_stamp, stamp_after};
16+use serde::Deserialize;
17+use tokio::sync::watch;
18+
19+use super::message::{Recipient, Sender, build};
20+use super::transport;
21+
22+/// Attempts before a row is abandoned.
23+pub const MAX_ATTEMPTS: i64 = 5;
24+
25+/// How often the worker looks for due rows.
26+const TICK: Duration = Duration::from_secs(5);
27+
28+/// The most rows one pass tries.
29+const BATCH: i64 = 10;
30+
31+/// How long to wait before the next try, after `attempts` failed tries (1 to 4).
32+pub fn retry_delay(attempts: i64) -> Duration {
33+ match attempts {
34+ 1 => Duration::from_secs(60),
35+ 2 => Duration::from_secs(5 * 60),
36+ 3 => Duration::from_secs(15 * 60),
37+ _ => Duration::from_secs(60 * 60),
38+ }
39+}
40+
41+/// The body as stored (after opening): the name, when known, and the two alternatives.
42+#[derive(Deserialize)]
43+struct Body {
44+ to_name: Option<String>,
45+ text: String,
46+ html: String,
47+}
48+
49+/// Starts the worker. It runs until `stop` is set.
50+pub fn spawn(
51+ store: Store,
52+ key: Arc<[u8; 32]>,
53+ smtp: SmtpConfig,
54+ mut stop: watch::Receiver<bool>,
55+) -> tokio::task::JoinHandle<()> {
56+ tokio::spawn(async move {
57+ if !smtp.enabled() {
58+ tracing::info!("mail worker: no sender configured; mail waits in the outbox");
59+ let _ = stop.wait_for(|stopped| *stopped).await;
60+ return;
61+ }
62+ let sender = match Sender::from_config(&smtp) {
63+ Ok(sender) => sender,
64+ Err(error) => {
65+ tracing::error!(error, "mail worker: the sender is not valid; mail waits");
66+ let _ = stop.wait_for(|stopped| *stopped).await;
67+ return;
68+ }
69+ };
70+ loop {
71+ run_once(&store, &key, &smtp, &sender).await;
72+ tokio::select! {
73+ () = tokio::time::sleep(TICK) => {}
74+ _ = stop.wait_for(|stopped| *stopped) => break,
75+ }
76+ }
77+ })
78+}
79+
80+/// One pass: builds the transport (spending no attempt if that fails) and sends what is due.
81+async fn run_once(store: &Store, key: &[u8; 32], smtp: &SmtpConfig, sender: &Sender) {
82+ let password = if smtp.username.is_empty() {
83+ None
84+ } else {
85+ match transport::read_password(&smtp.password_file) {
86+ Ok(password) => Some(password),
87+ Err(error) => {
88+ tracing::error!(error, "mail worker: waiting, the sender is not ready");
89+ return;
90+ }
91+ }
92+ };
93+ let transport = match transport::build(smtp, password) {
94+ Ok(transport) => transport,
95+ Err(error) => {
96+ tracing::error!(error, "mail worker: waiting, the sender is not ready");
97+ return;
98+ }
99+ };
100+ if let Err(error) = deliver_due(store, key, sender, &transport, &now_stamp()).await {
101+ tracing::error!(error = %error, "mail worker: outbox could not be read");
102+ }
103+}
104+
105+/// Sends the due rows through `transport` and records each outcome. Generic over the transport so the
106+/// tests can use lettre's stub.
107+pub async fn deliver_due<T>(
108+ store: &Store,
109+ key: &[u8; 32],
110+ sender: &Sender,
111+ transport: &T,
112+ now: &str,
113+) -> im_core::Result<usize>
114+where
115+ T: lettre::AsyncTransport + Sync,
116+ T::Error: std::fmt::Debug,
117+{
118+ let due = store.due_mail(now, BATCH).await?;
119+ let count = due.len();
120+ for job in &due {
121+ let attempt = attempt_once(sender, transport, key, job).await;
122+ if let Err(error) = store.record_mail_attempt(&job.id, &attempt).await {
123+ tracing::error!(error = %error, mail = %job.id, "mail outcome not recorded");
124+ }
125+ }
126+ Ok(count)
127+}
128+
129+/// Tries one row and says what happened to it.
130+async fn attempt_once<T>(
131+ sender: &Sender,
132+ transport: &T,
133+ key: &[u8; 32],
134+ job: &MailJob,
135+) -> MailAttempt
136+where
137+ T: lettre::AsyncTransport + Sync,
138+ T::Error: std::fmt::Debug,
139+{
140+ // A body that cannot be opened or no longer checks out is not going to get better: give up now.
141+ let message = match open_message(sender, key, job) {
142+ Ok(message) => message,
143+ Err(error) => {
144+ tracing::error!(mail = %job.id, kind = %job.kind, error, "mail abandoned");
145+ return MailAttempt::Abandon {
146+ error: error.to_owned(),
147+ };
148+ }
149+ };
150+ match transport.send(message).await {
151+ Ok(_) => {
152+ tracing::info!(mail = %job.id, kind = %job.kind, "mail sent");
153+ MailAttempt::Sent
154+ }
155+ Err(error) => {
156+ let attempts = job.attempts + 1;
157+ // The transport error describes the SMTP reply. The body is never part of it.
158+ let reason = truncate(&format!("{error:?}"), 200);
159+ if attempts >= MAX_ATTEMPTS {
160+ tracing::error!(mail = %job.id, kind = %job.kind, attempts, "mail abandoned");
161+ MailAttempt::Abandon { error: reason }
162+ } else {
163+ let delay = retry_delay(attempts);
164+ tracing::warn!(mail = %job.id, kind = %job.kind, attempts, "mail attempt failed; retry scheduled");
165+ MailAttempt::Retry {
166+ next_at: stamp_after(delay),
167+ error: reason,
168+ }
169+ }
170+ }
171+ }
172+}
173+
174+/// Opens the sealed body and builds the message. Every failure is a fixed text.
175+fn open_message(
176+ sender: &Sender,
177+ key: &[u8; 32],
178+ job: &MailJob,
179+) -> Result<lettre::Message, &'static str> {
180+ if job.sealed_body.is_empty() {
181+ return Err("mail body is missing");
182+ }
183+ let plain = secret::open(key, &job.sealed_body).map_err(|_| "mail body cannot be opened")?;
184+ let body: Body = serde_json::from_slice(&plain).map_err(|_| "mail body is not valid")?;
185+ let to = Recipient::new(body.to_name.as_deref(), &job.to_addr)?;
186+ build(sender, &to, &job.subject, body.text, body.html)
187+}
188+
189+/// Cuts `text` to at most `max` characters, on a character boundary.
190+fn truncate(text: &str, max: usize) -> String {
191+ text.chars().take(max).collect()
192+}
crates/im-web/src/main.rsmodified+1 -0
@@ -15,6 +15,7 @@ mod client_ip;
15 mod health;15 mod health;
16 mod i18n;16 mod i18n;
17 mod live;17 mod live;
18+mod mail;
18 mod oidc;19 mod oidc;
19 mod pages;20 mod pages;
20 mod security;21 mod security;
crates/im-web/src/pages/email.rsadded+382 -0
@@ -0,0 +1,382 @@
1+//! Email change, two-sided: `GET/POST /account/email` asks for it, `GET/POST /email/{token}` confirms one
2+//! half of it.
3+//!
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,
6+//! and the store checks the new address is still free at that moment. A link is never used by a GET: the
7+//! confirm and cancel buttons are POSTs with the pre-session token.
8+
9+use std::time::Duration;
10+
11+use im_core::model::AuditAction;
12+use im_core::names::parse_email;
13+use im_core::store::links::EmailConfirm;
14+use im_core::time::stamp_after;
15+use im_core::token::{generate_token, hash_token};
16+use serde::Deserialize;
17+use serde_json::json;
18+use topcoat::Result;
19+use topcoat::context::{Cx, app_context};
20+use topcoat::router::content::Form;
21+use topcoat::router::error::{forbidden, not_found, see_other};
22+use topcoat::router::page;
23+use topcoat::view::{View, view};
24+
25+use crate::audit::{Actor, record};
26+use crate::auth::{check_pre_csrf, pre_csrf_token, require_csrf, require_user};
27+use crate::i18n::Lang;
28+use crate::i18n::account::{Txt, text};
29+use crate::i18n::flows::{Flow, email_link_summary, text as flow_text};
30+use crate::live::Topic;
31+use crate::mail::{self, Mail, Recipient};
32+use crate::pages::path_param;
33+use crate::pages::security::{password_locked, password_matches};
34+use crate::state::AppState;
35+use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell};
36+
37+/// The request form: the new address and the current password.
38+#[derive(Deserialize, Default)]
39+struct EmailRequestForm {
40+ #[serde(default)]
41+ csrf: String,
42+ #[serde(default)]
43+ new_email: String,
44+ #[serde(default)]
45+ current_password: String,
46+}
47+
48+/// The query of `GET /account/email`.
49+#[derive(Deserialize, Default)]
50+struct NoticeQuery {
51+ #[serde(default)]
52+ notice: String,
53+}
54+
55+/// The form of an email-change link: `action` is `confirm` or `cancel`.
56+#[derive(Deserialize, Default)]
57+struct LinkForm {
58+ #[serde(default)]
59+ precsrf: String,
60+ #[serde(default)]
61+ action: String,
62+}
63+
64+/// `GET /account/email`.
65+#[page("/account/email")]
66+async fn email_request_form(cx: &Cx, Form(query): Form<NoticeQuery>) -> Result<impl View> {
67+ let viewer = require_user(cx).await?;
68+ let lang = page_lang(cx, Some(&viewer));
69+ Ok(request_view(
70+ cx,
71+ lang,
72+ ViewerInfo::of(&viewer),
73+ viewer.session.csrf_token.clone(),
74+ viewer.user.email.clone(),
75+ query.notice == "sent",
76+ None,
77+ ))
78+}
79+
80+/// `POST /account/email`: checks the password and the new address, then queues both links.
81+#[page(POST "/account/email")]
82+async fn email_request_submit(cx: &Cx, Form(form): Form<EmailRequestForm>) -> Result<impl View> {
83+ let viewer = require_csrf(cx, &form.csrf).await?;
84+ let state = app_context::<AppState>(cx);
85+ let lang = page_lang(cx, Some(&viewer));
86+ let csrf = viewer.session.csrf_token.clone();
87+ let current = viewer.user.email.clone();
88+ let refuse = |problem: Txt| {
89+ request_view(
90+ cx,
91+ lang,
92+ ViewerInfo::of(&viewer),
93+ csrf.clone(),
94+ current.clone(),
95+ false,
96+ Some(text(lang, problem).to_owned()),
97+ )
98+ };
99+
100+ if password_locked(state, &viewer) {
101+ return Ok(refuse(Txt::ErrThrottled));
102+ }
103+ if !password_matches(state, &viewer, &form.current_password).await? {
104+ return Ok(refuse(Txt::ErrWrongPassword));
105+ }
106+ let new_email = match parse_email(&form.new_email) {
107+ Ok(email) => email,
108+ Err(_) => return Ok(refuse(Txt::ErrEmailInvalid)),
109+ };
110+ if new_email == viewer.user.email {
111+ let problem = flow_text(lang, Flow::EmailChangeSame).to_owned();
112+ return Ok(request_view(
113+ cx,
114+ lang,
115+ ViewerInfo::of(&viewer),
116+ csrf,
117+ current,
118+ false,
119+ Some(problem),
120+ ));
121+ }
122+ if state
123+ .store
124+ .user_by_email_folded(&new_email)
125+ .await?
126+ .is_some()
127+ {
128+ let problem = flow_text(lang, Flow::EmailChangeUnavailable).to_owned();
129+ return Ok(request_view(
130+ cx,
131+ lang,
132+ ViewerInfo::of(&viewer),
133+ csrf,
134+ current,
135+ false,
136+ Some(problem),
137+ ));
138+ }
139+
140+ let hours = state.config.policy.email_change_hours;
141+ let old_token = generate_token();
142+ let new_token = generate_token();
143+ let expires = stamp_after(Duration::from_secs(u64::from(hours) * 60 * 60));
144+ match state
145+ .store
146+ .start_email_change(
147+ &viewer.user.id,
148+ &new_email,
149+ &hash_token(&old_token),
150+ &hash_token(&new_token),
151+ &expires,
152+ )
153+ .await
154+ {
155+ Ok(()) => {}
156+ Err(im_core::Error::Conflict(_)) => return Ok(refuse(Txt::ErrEmailInvalid)),
157+ Err(error) => return Err(error.into()),
158+ }
159+
160+ let old_link = format!("{}/email/{old_token}", state.config.base_url);
161+ let new_link = format!("{}/email/{new_token}", state.config.base_url);
162+ let user_lang = mail::lang_for(&viewer.user, lang);
163+ if let Ok(to) = Recipient::new(Some(&viewer.user.name), &viewer.user.email) {
164+ let mail = Mail::EmailOld {
165+ link: &old_link,
166+ new_email: &new_email,
167+ hours,
168+ };
169+ if let Err(error) = mail::queue(&state.store, &state.key, &to, user_lang, &mail).await {
170+ tracing::error!(error = %error, "email change mail to the old address not queued");
171+ }
172+ }
173+ match Recipient::new(None, &new_email) {
174+ Ok(to) => {
175+ let mail = Mail::EmailNew {
176+ link: &new_link,
177+ hours,
178+ };
179+ if let Err(error) = mail::queue(&state.store, &state.key, &to, user_lang, &mail).await {
180+ tracing::error!(error = %error, "email change mail to the new address not queued");
181+ }
182+ }
183+ Err(error) => tracing::error!(error, "email change mail to the new address not queued"),
184+ }
185+ record(
186+ cx,
187+ Actor::User(&viewer.user.id),
188+ AuditAction::EmailChangeRequested,
189+ Some(("user", &viewer.user.id)),
190+ json!({}),
191+ )
192+ .await;
193+ Err(see_other("/account/email?notice=sent").into())
194+}
195+
196+/// `GET /email/{token}`: shows what the link would change. It does not change anything.
197+#[page("/email/{token}")]
198+async fn email_link_form(cx: &Cx) -> Result<impl View> {
199+ let state = app_context::<AppState>(cx);
200+ let Some(token) = path_param(cx, "token") else {
201+ return Err(not_found().into());
202+ };
203+ let Some(link) = state.store.live_email_link(&hash_token(&token)).await? else {
204+ return Err(not_found().into());
205+ };
206+ let Some(user) = state.store.user_by_id(&link.user_id).await? else {
207+ return Err(not_found().into());
208+ };
209+ let lang = mail::lang_for(&user, page_lang(cx, None));
210+ let summary = email_link_summary(
211+ lang,
212+ &user.email,
213+ link.new_email.as_deref().unwrap_or_default(),
214+ );
215+ let csrf = pre_csrf_token(cx);
216+ Ok(link_view(cx, lang, token, csrf, summary, None))
217+}
218+
219+/// `POST /email/{token}`: confirms this half, or cancels the whole change.
220+#[page(POST "/email/{token}")]
221+async fn email_link_submit(cx: &Cx, Form(form): Form<LinkForm>) -> Result<impl View> {
222+ if !check_pre_csrf(cx, &form.precsrf) {
223+ return Err(forbidden().into());
224+ }
225+ let state = app_context::<AppState>(cx);
226+ let Some(token) = path_param(cx, "token") else {
227+ return Err(not_found().into());
228+ };
229+ let token_hash = hash_token(&token);
230+ let Some(link) = state.store.live_email_link(&token_hash).await? else {
231+ return Err(not_found().into());
232+ };
233+ let Some(user) = state.store.user_by_id(&link.user_id).await? else {
234+ return Err(not_found().into());
235+ };
236+ let lang = mail::lang_for(&user, page_lang(cx, None));
237+
238+ if form.action == "cancel" {
239+ match state.store.cancel_email_change(&token_hash).await? {
240+ Some(user_id) => {
241+ record(
242+ cx,
243+ Actor::Anonymous,
244+ AuditAction::EmailChangeCancelled,
245+ Some(("user", &user_id)),
246+ json!({}),
247+ )
248+ .await;
249+ return Ok(done_view(
250+ cx,
251+ lang,
252+ flow_text(lang, Flow::EmailLinkCancelled),
253+ ));
254+ }
255+ None => return Err(not_found().into()),
256+ }
257+ }
258+
259+ match state.store.confirm_email_link(&token_hash).await? {
260+ EmailConfirm::Waiting => {
261+ record(
262+ cx,
263+ Actor::Anonymous,
264+ AuditAction::EmailChangeConfirmed,
265+ Some(("user", &user.id)),
266+ json!({ "kind": link.kind }),
267+ )
268+ .await;
269+ Ok(done_view(cx, lang, flow_text(lang, Flow::EmailLinkWaiting)))
270+ }
271+ EmailConfirm::Applied {
272+ user_id,
273+ old_email,
274+ new_email,
275+ } => {
276+ state.live.bump(&Topic::Account(user_id.clone()));
277+ record(
278+ cx,
279+ Actor::Anonymous,
280+ AuditAction::EmailChanged,
281+ Some(("user", &user_id)),
282+ json!({}),
283+ )
284+ .await;
285+ notify_both(state, lang, &old_email, &new_email).await;
286+ Ok(done_view(cx, lang, flow_text(lang, Flow::EmailLinkDone)))
287+ }
288+ EmailConfirm::Refused => Ok(done_view(cx, lang, flow_text(lang, Flow::EmailLinkRefused))),
289+ }
290+}
291+
292+/// Tells both the old and the new address that the change happened.
293+async fn notify_both(state: &AppState, lang: Lang, old_email: &str, new_email: &str) {
294+ for address in [old_email, new_email] {
295+ match Recipient::new(None, address) {
296+ Ok(to) => {
297+ let mail = Mail::EmailDone { new_email };
298+ if let Err(error) = mail::queue(&state.store, &state.key, &to, lang, &mail).await {
299+ tracing::error!(error = %error, "email change notice not queued");
300+ }
301+ }
302+ Err(error) => tracing::error!(error, "email change notice not queued"),
303+ }
304+ }
305+}
306+
307+/// The request page: the current address, the new address and the password.
308+fn request_view(
309+ cx: &Cx,
310+ lang: Lang,
311+ info: ViewerInfo,
312+ csrf: String,
313+ current: String,
314+ sent: bool,
315+ problem: Option<String>,
316+) -> impl View {
317+ view! { cx =>
318+ shell(title: flow_text(lang, Flow::EmailChangeTitle), lang: lang, viewer: Some(info),
319+ <section class="card narrow stack">
320+ <h1>(flow_text(lang, Flow::EmailChangeTitle))</h1>
321+ <p class="muted">(flow_text(lang, Flow::EmailChangeIntro))</p>
322+ if sent {
323+ notice(message: flow_text(lang, Flow::EmailChangeQueued).to_owned())
324+ }
325+ if let Some(problem) = problem {
326+ alert(message: problem)
327+ }
328+ <form method="post" action="/account/email" class="stack">
329+ <input type="hidden" name="csrf" value=(csrf)>
330+ <label class="field">
331+ <span class="field-label">(flow_text(lang, Flow::CurrentAddress))</span>
332+ <input type="email" value=(current) readonly="" autocomplete="off">
333+ </label>
334+ field(label: flow_text(lang, Flow::NewAddress), name: "new_email", kind: "email", autocomplete: "email", value: String::new())
335+ field(label: text(lang, Txt::CurrentPassword), name: "current_password", kind: "password", autocomplete: "current-password", value: String::new())
336+ <button type="submit" class="button primary">(flow_text(lang, Flow::EmailChangeSubmit))</button>
337+ </form>
338+ </section>
339+ )
340+ }
341+}
342+
343+/// The page behind a link: the summary, and the confirm and cancel buttons.
344+fn link_view(
345+ cx: &Cx,
346+ lang: Lang,
347+ token: String,
348+ csrf: String,
349+ summary: String,
350+ problem: Option<String>,
351+) -> impl View {
352+ let action = format!("/email/{token}");
353+ view! { cx =>
354+ shell(title: flow_text(lang, Flow::EmailLinkTitle), lang: lang, viewer: None,
355+ <section class="card narrow stack">
356+ <h1>(flow_text(lang, Flow::EmailLinkTitle))</h1>
357+ <p>(summary)</p>
358+ if let Some(problem) = problem {
359+ alert(message: problem)
360+ }
361+ <form method="post" action=(action) class="stack">
362+ <input type="hidden" name="precsrf" value=(csrf)>
363+ <button type="submit" name="action" value="confirm" class="button primary">(flow_text(lang, Flow::EmailLinkConfirm))</button>
364+ <button type="submit" name="action" value="cancel" class="button danger">(flow_text(lang, Flow::EmailLinkCancel))</button>
365+ </form>
366+ <p class="muted">(flow_text(lang, Flow::EmailLinkNote))</p>
367+ </section>
368+ )
369+ }
370+}
371+
372+/// A plain result page after a link was used.
373+fn done_view(cx: &Cx, lang: Lang, message: &'static str) -> impl View {
374+ view! { cx =>
375+ shell(title: flow_text(lang, Flow::EmailLinkTitle), lang: lang, viewer: None,
376+ <section class="card narrow stack">
377+ <h1>(flow_text(lang, Flow::EmailLinkTitle))</h1>
378+ notice(message: message.to_owned())
379+ </section>
380+ )
381+ }
382+}
crates/im-web/src/pages/invite.rsadded+302 -0
@@ -0,0 +1,302 @@
1+//! Invitations: an administrator sends one by mail, and the invited person chooses a name and a password.
2+//!
3+//! `GET/POST /invite/{token}` is open to anyone who holds a live token. A used, expired or unknown token
4+//! gets the styled not-found page, and so does an acceptance that the store refuses (the link was spent
5+//! meanwhile, or the address got an account). The acceptance itself is one conditional update in the
6+//! store, so parallel submissions create one account. `/admin/invites` is the minimal admin form that
7+//! creates invitations; it answers 404 to anyone who is not an administrator.
8+
9+use im_core::model::{AuditAction, amr};
10+use im_core::names::{parse_display_name, parse_email};
11+use im_core::password::{check_policy, hash_password_async};
12+use im_core::store::invites::{AcceptOutcome, invite_lifetime};
13+use im_core::time::stamp_after;
14+use im_core::token::{generate_token, hash_token};
15+use serde::Deserialize;
16+use serde_json::json;
17+use topcoat::Result;
18+use topcoat::context::{Cx, app_context};
19+use topcoat::router::content::Form;
20+use topcoat::router::error::{forbidden, not_found, see_other};
21+use topcoat::router::page;
22+use topcoat::view::{View, view};
23+
24+use crate::audit::{Actor, record};
25+use crate::auth::{
26+ after_sign_in, check_csrf, check_pre_csrf, clear_pre_csrf, pre_csrf_token, require_admin,
27+ start_session,
28+};
29+use crate::i18n::Lang;
30+use crate::i18n::account::{Txt, policy_problem, text};
31+use crate::i18n::flows::{Flow, text as flow_text};
32+use crate::mail::{self, Mail, Recipient};
33+use crate::pages::path_param;
34+use crate::state::AppState;
35+use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell};
36+
37+/// The invitation form.
38+#[derive(Deserialize, Default)]
39+struct InviteForm {
40+ #[serde(default)]
41+ precsrf: String,
42+ #[serde(default)]
43+ name: String,
44+ #[serde(default)]
45+ password: String,
46+ #[serde(default)]
47+ password_again: String,
48+}
49+
50+/// The administrator's invitation form. The checkbox sends `on` when ticked.
51+#[derive(Deserialize, Default)]
52+struct AdminInviteForm {
53+ #[serde(default)]
54+ csrf: String,
55+ #[serde(default)]
56+ email: String,
57+ #[serde(default)]
58+ admin: String,
59+}
60+
61+/// The query of `GET /admin/invites`.
62+#[derive(Deserialize, Default)]
63+struct NoticeQuery {
64+ #[serde(default)]
65+ notice: String,
66+}
67+
68+/// `GET /invite/{token}`.
69+#[page("/invite/{token}")]
70+async fn invite_form(cx: &Cx) -> Result<impl View> {
71+ let state = app_context::<AppState>(cx);
72+ let Some(token) = path_param(cx, "token") else {
73+ return Err(not_found().into());
74+ };
75+ let Some(invite) = state.store.live_invite(&hash_token(&token)).await? else {
76+ return Err(not_found().into());
77+ };
78+ let csrf = pre_csrf_token(cx);
79+ let lang = page_lang(cx, None);
80+ Ok(invite_view(
81+ cx,
82+ lang,
83+ csrf,
84+ token,
85+ invite.email_folded,
86+ None,
87+ ))
88+}
89+
90+/// `POST /invite/{token}`: creates the account and signs the person in.
91+#[page(POST "/invite/{token}")]
92+async fn invite_submit(cx: &Cx, Form(form): Form<InviteForm>) -> Result<impl View> {
93+ if !check_pre_csrf(cx, &form.precsrf) {
94+ return Err(forbidden().into());
95+ }
96+ let state = app_context::<AppState>(cx);
97+ let Some(token) = path_param(cx, "token") else {
98+ return Err(not_found().into());
99+ };
100+ let token_hash = hash_token(&token);
101+ let Some(invite) = state.store.live_invite(&token_hash).await? else {
102+ return Err(not_found().into());
103+ };
104+ let lang = page_lang(cx, None);
105+ let csrf = pre_csrf_token(cx);
106+ let email = invite.email_folded.clone();
107+
108+ // A refused name is not shown back: it may hold control characters.
109+ let name = match parse_display_name(&form.name) {
110+ Ok(name) => name,
111+ Err(_) => {
112+ let problem = text(lang, Txt::ErrNameInvalid).to_owned();
113+ return Ok(invite_view(cx, lang, csrf, token, email, Some(problem)));
114+ }
115+ };
116+ if let Err(violation) = check_policy(&form.password, &email, &name) {
117+ let problem = policy_problem(lang, violation);
118+ return Ok(invite_view(cx, lang, csrf, token, email, Some(problem)));
119+ }
120+ if form.password != form.password_again {
121+ let problem = text(lang, Txt::ErrPasswordsDiffer).to_owned();
122+ return Ok(invite_view(cx, lang, csrf, token, email, Some(problem)));
123+ }
124+
125+ let hash = hash_password_async(form.password.clone()).await?;
126+ let user = match state.store.accept_invite(&token_hash, &name, &hash).await? {
127+ AcceptOutcome::Accepted(user) => *user,
128+ AcceptOutcome::Refused => return Err(not_found().into()),
129+ };
130+ start_session(cx, &user, amr::PASSWORD).await?;
131+ clear_pre_csrf(cx);
132+ record(
133+ cx,
134+ Actor::User(&user.id),
135+ AuditAction::InviteAccepted,
136+ Some(("user", &user.id)),
137+ json!({ "admin": user.is_admin }),
138+ )
139+ .await;
140+ Err(see_other(after_sign_in(state, &user, "/")).into())
141+}
142+
143+/// `GET /admin/invites`. Non-administrators get 404.
144+#[page("/admin/invites")]
145+async fn admin_invites_form(cx: &Cx, Form(query): Form<NoticeQuery>) -> Result<impl View> {
146+ let viewer = require_admin(cx).await?;
147+ let lang = page_lang(cx, Some(&viewer));
148+ Ok(admin_invites_view(
149+ cx,
150+ lang,
151+ ViewerInfo::of(&viewer),
152+ viewer.session.csrf_token.clone(),
153+ query.notice == "sent",
154+ None,
155+ ))
156+}
157+
158+/// `POST /admin/invites`: creates the invitation and queues its mail.
159+#[page(POST "/admin/invites")]
160+async fn admin_invites_submit(cx: &Cx, Form(form): Form<AdminInviteForm>) -> Result<impl View> {
161+ let viewer = require_admin(cx).await?;
162+ if !check_csrf(&viewer.session, &form.csrf) {
163+ return Err(forbidden().into());
164+ }
165+ let state = app_context::<AppState>(cx);
166+ let lang = page_lang(cx, Some(&viewer));
167+ let csrf = viewer.session.csrf_token.clone();
168+ let info = ViewerInfo::of(&viewer);
169+
170+ let email = match parse_email(&form.email) {
171+ Ok(email) => email,
172+ Err(_) => {
173+ let problem = text(lang, Txt::ErrEmailInvalid).to_owned();
174+ return Ok(admin_invites_view(
175+ cx,
176+ lang,
177+ info,
178+ csrf,
179+ false,
180+ Some(problem),
181+ ));
182+ }
183+ };
184+ let is_admin = form.admin == "on";
185+ let days = state.config.policy.invite_days;
186+ let token = generate_token();
187+ let expires = stamp_after(invite_lifetime(days));
188+ match state
189+ .store
190+ .create_invite(
191+ &hash_token(&token),
192+ &email,
193+ is_admin,
194+ &viewer.user.id,
195+ &expires,
196+ )
197+ .await
198+ {
199+ Ok(()) => {}
200+ Err(im_core::Error::Conflict(_)) => {
201+ let problem = flow_text(lang, Flow::InviteAddressTaken).to_owned();
202+ return Ok(admin_invites_view(
203+ cx,
204+ lang,
205+ info,
206+ csrf,
207+ false,
208+ Some(problem),
209+ ));
210+ }
211+ Err(error) => return Err(error.into()),
212+ }
213+
214+ let link = format!("{}/invite/{token}", state.config.base_url);
215+ match Recipient::new(None, &email) {
216+ Ok(to) => {
217+ let mail = Mail::Invite { link: &link, days };
218+ if let Err(error) = mail::queue(&state.store, &state.key, &to, lang, &mail).await {
219+ tracing::error!(error = %error, "invitation mail not queued");
220+ }
221+ }
222+ Err(error) => tracing::error!(error, "invitation mail not queued"),
223+ }
224+ record(
225+ cx,
226+ Actor::User(&viewer.user.id),
227+ AuditAction::InviteCreated,
228+ None,
229+ json!({ "admin": is_admin }),
230+ )
231+ .await;
232+ Err(see_other("/admin/invites?notice=sent").into())
233+}
234+
235+/// The invitation page: the address (read only), the name and the new password.
236+fn invite_view(
237+ cx: &Cx,
238+ lang: Lang,
239+ csrf: String,
240+ token: String,
241+ email: String,
242+ problem: Option<String>,
243+) -> impl View {
244+ let action = format!("/invite/{token}");
245+ view! { cx =>
246+ shell(title: flow_text(lang, Flow::InviteTitle), lang: lang, viewer: None,
247+ <section class="card narrow stack">
248+ <h1>(flow_text(lang, Flow::InviteTitle))</h1>
249+ <p class="muted">(flow_text(lang, Flow::InviteIntro))</p>
250+ if let Some(problem) = problem {
251+ alert(message: problem)
252+ }
253+ <form method="post" action=(action) class="stack">
254+ <input type="hidden" name="precsrf" value=(csrf)>
255+ <label class="field">
256+ <span class="field-label">(text(lang, Txt::Email))</span>
257+ <input type="email" value=(email) readonly="" autocomplete="username">
258+ </label>
259+ field(label: text(lang, Txt::Name), name: "name", kind: "text", autocomplete: "name", value: String::new())
260+ field(label: text(lang, Txt::Password), name: "password", kind: "password", autocomplete: "new-password", value: String::new())
261+ field(label: text(lang, Txt::NewPasswordAgain), name: "password_again", kind: "password", autocomplete: "new-password", value: String::new())
262+ <p class="hint">(text(lang, Txt::PasswordHint))</p>
263+ <button type="submit" class="button primary">(flow_text(lang, Flow::InviteSubmit))</button>
264+ </form>
265+ </section>
266+ )
267+ }
268+}
269+
270+/// The administrator's invitation form, with the result of the last submission above it.
271+fn admin_invites_view(
272+ cx: &Cx,
273+ lang: Lang,
274+ info: ViewerInfo,
275+ csrf: String,
276+ sent: bool,
277+ problem: Option<String>,
278+) -> impl View {
279+ view! { cx =>
280+ shell(title: flow_text(lang, Flow::AdminInvitesTitle), lang: lang, viewer: Some(info),
281+ <section class="card narrow stack">
282+ <h1>(flow_text(lang, Flow::AdminInvitesTitle))</h1>
283+ <p class="muted">(flow_text(lang, Flow::AdminInvitesIntro))</p>
284+ if sent {
285+ notice(message: flow_text(lang, Flow::InviteQueued).to_owned())
286+ }
287+ if let Some(problem) = problem {
288+ alert(message: problem)
289+ }
290+ <form method="post" action="/admin/invites" class="stack">
291+ <input type="hidden" name="csrf" value=(csrf)>
292+ field(label: text(lang, Txt::Email), name: "email", kind: "email", autocomplete: "off", value: String::new())
293+ <label class="check">
294+ <input type="checkbox" name="admin">
295+ <span>(flow_text(lang, Flow::InviteAsAdmin))</span>
296+ </label>
297+ <button type="submit" class="button primary">(flow_text(lang, Flow::InviteSend))</button>
298+ </form>
299+ </section>
300+ )
301+ }
302+}
crates/im-web/src/pages/mod.rsmodified+13 -0
@@ -1,15 +1,28 @@
1 //! The pages and the page-level layers. One file per page.1 //! The pages and the page-level layers. One file per page.
2 2
3+pub mod email;
3 pub mod home;4 pub mod home;
5+pub mod invite;
4 pub mod login;6 pub mod login;
5 pub mod not_found;7 pub mod not_found;
6 pub mod people;8 pub mod people;
7 pub mod photo;9 pub mod photo;
8 pub mod preferences;10 pub mod preferences;
9 pub mod profile;11 pub mod profile;
12+pub mod reset;
10 pub mod security;13 pub mod security;
11 pub mod sessions;14 pub mod sessions;
12 pub mod setup;15 pub mod setup;
13 16
17+use topcoat::context::Cx;
18+use topcoat::router::raw_path_params;
19+
20+/// The value of the route parameter `name` of the matched route, or `None` when there is none.
21+pub fn path_param(cx: &Cx, name: &str) -> Option<String> {
22+ raw_path_params(cx)
23+ .find(|(param, _)| *param == name)
24+ .map(|(_, value)| value.as_str().to_owned())
25+}
26+
14 #[cfg(test)]27 #[cfg(test)]
15 mod tests;28 mod tests;
crates/im-web/src/pages/profile.rsmodified+4 -2
@@ -1,7 +1,7 @@
1 //! The profile of the signed-in person: the display name, the profile photo, and the email address.1 //! The profile of the signed-in person: the display name, the profile photo, and the email address.
2 //!2 //!
3-//! The email address is shown read-only until the mail step exists; changing it needs the3+//! The email address is shown here; changing it goes through `pages/email.rs`, which needs a confirmation
4-//! confirmation links that mail carries. The photo is the only upload in `im` so far. Its bytes are4+//! link at both addresses. The photo is the only upload in `im` so far. Its bytes are
5 //! read as a stream with a hard limit, and the CSRF field has to arrive before the first byte of the5 //! read as a stream with a hard limit, and the CSRF field has to arrive before the first byte of the
6 //! picture, so an upload from another site is refused before it is read at all. What is read is6 //! picture, so an upload from another site is refused before it is read at all. What is read is
7 //! decoded and re-encoded by `im_core::photo` before anything is written.7 //! decoded and re-encoded by `im_core::photo` before anything is written.
@@ -23,6 +23,7 @@ use crate::audit::{Actor, record};
23 use crate::auth::{Viewer, require_csrf, require_user};23 use crate::auth::{Viewer, require_csrf, require_user};
24 use crate::i18n::Lang;24 use crate::i18n::Lang;
25 use crate::i18n::account::{Txt, text};25 use crate::i18n::account::{Txt, text};
26+use crate::i18n::flows::{Flow, text as flow_text};
26 use crate::live::Topic;27 use crate::live::Topic;
27 use crate::pages::login::CsrfForm;28 use crate::pages::login::CsrfForm;
28 use crate::state::AppState;29 use crate::state::AppState;
@@ -305,6 +306,7 @@ fn profile_view(cx: &Cx, lang: Lang, info: ViewerInfo, data: ProfileData) -> imp
305 <h2>(text(lang, Txt::Email))</h2>306 <h2>(text(lang, Txt::Email))</h2>
306 <p>(email)</p>307 <p>(email)</p>
307 <p class="muted">(text(lang, Txt::EmailLaterNote))</p>308 <p class="muted">(text(lang, Txt::EmailLaterNote))</p>
309+ <p><a href="/account/email">(flow_text(lang, Flow::ChangeEmailLink))</a></p>
308 </section>310 </section>
309 </section>311 </section>
310 )312 )
crates/im-web/src/pages/reset.rsadded+304 -0
@@ -0,0 +1,304 @@
1+//! Password reset by mail: `GET/POST /forgot` asks for a link, `GET/POST /reset/{token}` spends it.
2+//!
3+//! The forgot answer is the same for every address. It is a redirect to the same place, and the work
4+//! behind it is the same lookup either way. For a known, enabled address the link is created and mailed
5+//! in a background task, so the response does not wait for the mail queue. Requests are counted per
6+//! address and per client, and a counted-out request gets the same redirect with no work at all.
7+//!
8+//! The reset link is single use and lasts `policy.reset_minutes`. Spending it sets the password, ends
9+//! every session of the person with its back-channel logouts, and signs the browser in again. An account
10+//! with two-factor sign-in is sent to the sign-in page instead, so the second factor is still asked.
11+
12+use std::sync::Arc;
13+use std::time::{Duration, Instant};
14+
15+use im_core::model::{AuditAction, User, amr};
16+use im_core::names::{normalize_email, parse_email};
17+use im_core::password::{check_policy, hash_password_async, verify_password_async};
18+use im_core::store::Store;
19+use im_core::store::audit::NewAudit;
20+use im_core::time::stamp_after;
21+use im_core::token::{generate_token, hash_token};
22+use serde::Deserialize;
23+use serde_json::json;
24+use topcoat::Result;
25+use topcoat::context::{Cx, app_context};
26+use topcoat::router::content::Form;
27+use topcoat::router::error::{forbidden, not_found, see_other};
28+use topcoat::router::page;
29+use topcoat::view::{View, view};
30+
31+use crate::audit::{Actor, record};
32+use crate::auth::{after_sign_in, check_pre_csrf, clear_pre_csrf, pre_csrf_token, start_session};
33+use crate::client_ip::client_ip;
34+use crate::i18n::Lang;
35+use crate::i18n::account::{Txt, policy_problem, text};
36+use crate::i18n::flows::{Flow, text as flow_text};
37+use crate::live::Topic;
38+use crate::mail::{self, Mail, Notice, Recipient};
39+use crate::pages::path_param;
40+use crate::state::AppState;
41+use crate::throttle::{FORGOT_EMAIL_LIMIT, FORGOT_IP_LIMIT, forgot_email_key, ip_key};
42+use crate::views::{alert, field, notice, page_lang, shell};
43+
44+/// The forgot-password form.
45+#[derive(Deserialize, Default)]
46+struct ForgotForm {
47+ #[serde(default)]
48+ precsrf: String,
49+ #[serde(default)]
50+ email: String,
51+}
52+
53+/// The query of `GET /forgot`: `sent=1` after a request.
54+#[derive(Deserialize, Default)]
55+struct ForgotQuery {
56+ #[serde(default)]
57+ sent: String,
58+}
59+
60+/// The new-password form.
61+#[derive(Deserialize, Default)]
62+struct ResetForm {
63+ #[serde(default)]
64+ precsrf: String,
65+ #[serde(default)]
66+ password: String,
67+ #[serde(default)]
68+ password_again: String,
69+}
70+
71+/// `GET /forgot`.
72+#[page("/forgot")]
73+async fn forgot_form(cx: &Cx, Form(query): Form<ForgotQuery>) -> Result<impl View> {
74+ let csrf = pre_csrf_token(cx);
75+ let lang = page_lang(cx, None);
76+ Ok(forgot_view(cx, lang, csrf, query.sent == "1"))
77+}
78+
79+/// `POST /forgot`. The same redirect whatever the address is.
80+#[page(POST "/forgot")]
81+async fn forgot_submit(cx: &Cx, Form(form): Form<ForgotForm>) -> Result<impl View> {
82+ if !check_pre_csrf(cx, &form.precsrf) {
83+ return Err(forbidden().into());
84+ }
85+ let state = app_context::<AppState>(cx);
86+ let lang = page_lang(cx, None);
87+ let now = Instant::now();
88+ let email = normalize_email(&form.email);
89+ let client = client_ip(cx);
90+ let email_limit = forgot_email_key(&email);
91+ let client_limit = ip_key("forgot-ip", client);
92+ let limited = state
93+ .throttle
94+ .check(&email_limit, FORGOT_EMAIL_LIMIT, now)
95+ .is_some()
96+ || state
97+ .throttle
98+ .check(&client_limit, FORGOT_IP_LIMIT, now)
99+ .is_some();
100+ state.throttle.record_failure(&email_limit, now);
101+ state.throttle.record_failure(&client_limit, now);
102+
103+ // The same lookup for a known and an unknown address; only a known, enabled one gets a link.
104+ if !limited
105+ && let Ok(address) = parse_email(&email)
106+ && let Some(user) = state.store.user_by_email_folded(&address).await?
107+ && !user.is_disabled()
108+ {
109+ spawn_reset(
110+ state.store.clone(),
111+ state.key.clone(),
112+ state.config.base_url.clone(),
113+ state.config.policy.reset_minutes,
114+ user,
115+ lang,
116+ client.to_string(),
117+ );
118+ }
119+ Ok(forgot_view(cx, lang, pre_csrf_token(cx), true))
120+}
121+
122+/// Creates a reset link for `user` and queues its mail, in the background. Failures are logged; the
123+/// person who asked sees the same answer either way.
124+fn spawn_reset(
125+ store: Store,
126+ key: Arc<[u8; 32]>,
127+ base_url: String,
128+ minutes: u32,
129+ user: User,
130+ lang: Lang,
131+ ip: String,
132+) {
133+ tokio::spawn(async move {
134+ let token = generate_token();
135+ let expires = stamp_after(Duration::from_secs(u64::from(minutes) * 60));
136+ if let Err(error) = store
137+ .create_reset_link(&user.id, &hash_token(&token), &expires)
138+ .await
139+ {
140+ tracing::error!(error = %error, "reset link not created");
141+ return;
142+ }
143+ let link = format!("{base_url}/reset/{token}");
144+ let lang = mail::lang_for(&user, lang);
145+ match Recipient::new(Some(&user.name), &user.email) {
146+ Ok(to) => {
147+ let mail = Mail::Reset {
148+ link: &link,
149+ minutes,
150+ };
151+ if let Err(error) = mail::queue(&store, &key, &to, lang, &mail).await {
152+ tracing::error!(error = %error, "reset mail not queued");
153+ }
154+ }
155+ Err(error) => tracing::error!(error, "reset mail not queued"),
156+ }
157+ let entry = NewAudit {
158+ actor_id: None,
159+ actor_kind: "anonymous",
160+ action: AuditAction::ResetRequested.as_str(),
161+ target_kind: Some("user"),
162+ target_id: Some(&user.id),
163+ ip: Some(ip.as_str()),
164+ data: None,
165+ };
166+ if let Err(error) = store.record_audit(&entry).await {
167+ tracing::error!(error = %error, "audit entry was not written");
168+ }
169+ });
170+}
171+
172+/// `GET /reset/{token}`. Only a live reset link opens the form; anything else is not found.
173+#[page("/reset/{token}")]
174+async fn reset_form(cx: &Cx) -> Result<impl View> {
175+ let state = app_context::<AppState>(cx);
176+ let Some(token) = path_param(cx, "token") else {
177+ return Err(not_found().into());
178+ };
179+ if state
180+ .store
181+ .live_reset_link(&hash_token(&token))
182+ .await?
183+ .is_none()
184+ {
185+ return Err(not_found().into());
186+ }
187+ let csrf = pre_csrf_token(cx);
188+ let lang = page_lang(cx, None);
189+ Ok(reset_view(cx, lang, csrf, token, None))
190+}
191+
192+/// `POST /reset/{token}`: sets the password and ends every session of the person.
193+#[page(POST "/reset/{token}")]
194+async fn reset_submit(cx: &Cx, Form(form): Form<ResetForm>) -> Result<impl View> {
195+ if !check_pre_csrf(cx, &form.precsrf) {
196+ return Err(forbidden().into());
197+ }
198+ let state = app_context::<AppState>(cx);
199+ let Some(token) = path_param(cx, "token") else {
200+ return Err(not_found().into());
201+ };
202+ let token_hash = hash_token(&token);
203+ let Some(link) = state.store.live_reset_link(&token_hash).await? else {
204+ return Err(not_found().into());
205+ };
206+ let Some(user) = state
207+ .store
208+ .user_by_id(&link.user_id)
209+ .await?
210+ .filter(|user| !user.is_disabled())
211+ else {
212+ return Err(not_found().into());
213+ };
214+ let lang = mail::lang_for(&user, page_lang(cx, None));
215+ let csrf = pre_csrf_token(cx);
216+
217+ if form.password != form.password_again {
218+ let problem = text(lang, Txt::ErrPasswordsDiffer).to_owned();
219+ return Ok(reset_view(cx, lang, csrf, token, Some(problem)));
220+ }
221+ if let Err(violation) = check_policy(&form.password, &user.email, &user.name) {
222+ let problem = policy_problem(lang, violation);
223+ return Ok(reset_view(cx, lang, csrf, token, Some(problem)));
224+ }
225+ if verify_password_async(form.password.clone(), user.password_hash.clone()).await? {
226+ let problem = text(lang, Txt::ErrPasswordSame).to_owned();
227+ return Ok(reset_view(cx, lang, csrf, token, Some(problem)));
228+ }
229+
230+ let hash = hash_password_async(form.password.clone()).await?;
231+ // The conditional spend and the password change are one transaction: a second request with the same
232+ // link gets None here, even if both passed the checks above.
233+ let Some(user_id) = state.store.redeem_reset_link(&token_hash, &hash).await? else {
234+ return Err(not_found().into());
235+ };
236+ state.live.bump(&Topic::Account(user_id.clone()));
237+ record(
238+ cx,
239+ Actor::Anonymous,
240+ AuditAction::PasswordReset,
241+ Some(("user", &user_id)),
242+ json!({}),
243+ )
244+ .await;
245+ mail::notify(&state.store, &state.key, &user, lang, Notice::PasswordReset).await;
246+
247+ if user.totp_enabled() {
248+ clear_pre_csrf(cx);
249+ return Err(see_other("/login").into());
250+ }
251+ start_session(cx, &user, amr::PASSWORD).await?;
252+ clear_pre_csrf(cx);
253+ Err(see_other(after_sign_in(state, &user, "/")).into())
254+}
255+
256+/// The forgot-password page.
257+fn forgot_view(cx: &Cx, lang: Lang, csrf: String, sent: bool) -> impl View {
258+ view! { cx =>
259+ shell(title: flow_text(lang, Flow::ForgotTitle), lang: lang, viewer: None,
260+ <section class="card narrow stack">
261+ <h1>(flow_text(lang, Flow::ForgotTitle))</h1>
262+ if sent {
263+ notice(message: flow_text(lang, Flow::ForgotSent).to_owned())
264+ }
265+ <p class="muted">(flow_text(lang, Flow::ForgotIntro))</p>
266+ <form method="post" action="/forgot" class="stack">
267+ <input type="hidden" name="precsrf" value=(csrf)>
268+ field(label: text(lang, Txt::Email), name: "email", kind: "email", autocomplete: "username", value: String::new())
269+ <button type="submit" class="button primary">(flow_text(lang, Flow::ForgotSubmit))</button>
270+ </form>
271+ <p><a href="/login">(flow_text(lang, Flow::BackToSignIn))</a></p>
272+ </section>
273+ )
274+ }
275+}
276+
277+/// The new-password page for `token`. The form posts back to the same path.
278+fn reset_view(
279+ cx: &Cx,
280+ lang: Lang,
281+ csrf: String,
282+ token: String,
283+ problem: Option<String>,
284+) -> impl View {
285+ let action = format!("/reset/{token}");
286+ view! { cx =>
287+ shell(title: flow_text(lang, Flow::ResetTitle), lang: lang, viewer: None,
288+ <section class="card narrow stack">
289+ <h1>(flow_text(lang, Flow::ResetTitle))</h1>
290+ <p class="muted">(flow_text(lang, Flow::ResetIntro))</p>
291+ if let Some(problem) = problem {
292+ alert(message: problem)
293+ }
294+ <form method="post" action=(action) class="stack">
295+ <input type="hidden" name="precsrf" value=(csrf)>
296+ field(label: text(lang, Txt::NewPassword), name: "password", kind: "password", autocomplete: "new-password", value: String::new())
297+ field(label: text(lang, Txt::NewPasswordAgain), name: "password_again", kind: "password", autocomplete: "new-password", value: String::new())
298+ <p class="hint">(text(lang, Txt::PasswordHint))</p>
299+ <button type="submit" class="button primary">(flow_text(lang, Flow::ResetSubmit))</button>
300+ </form>
301+ </section>
302+ )
303+ }
304+}
crates/im-web/src/pages/security.rsmodified+35 -2
@@ -25,6 +25,7 @@ use crate::auth::{Viewer, check_second_factor, require_csrf, require_user, unix_
25 use crate::i18n::Lang;25 use crate::i18n::Lang;
26 use crate::i18n::account::{Txt, policy_problem, recovery_left, text};26 use crate::i18n::account::{Txt, policy_problem, recovery_left, text};
27 use crate::live::Topic;27 use crate::live::Topic;
28+use crate::mail::{self, Notice};
28 use crate::state::AppState;29 use crate::state::AppState;
29 use crate::throttle::{LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT, two_factor_key, user_key};30 use crate::throttle::{LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT, two_factor_key, user_key};
30 use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell};31 use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell};
@@ -191,6 +192,14 @@ async fn change_password(cx: &Cx, Form(form): Form<PasswordForm>) -> Result<impl
191 json!({ "sessions_ended": ended.len() }),192 json!({ "sessions_ended": ended.len() }),
192 )193 )
193 .await;194 .await;
195+ mail::notify(
196+ &state.store,
197+ &state.key,
198+ &viewer.user,
199+ lang,
200+ Notice::PasswordChanged,
201+ )
202+ .await;
194 Err(see_other("/account/security?notice=saved-password").into())203 Err(see_other("/account/security?notice=saved-password").into())
195 }204 }
196 205
@@ -294,6 +303,14 @@ async fn confirm_enrolment(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl V
294 json!({ "recovery_codes": codes.len() }),303 json!({ "recovery_codes": codes.len() }),
295 )304 )
296 .await;305 .await;
306+ mail::notify(
307+ &state.store,
308+ &state.key,
309+ &viewer.user,
310+ lang,
311+ Notice::TwoFactorOn,
312+ )
313+ .await;
297 // Reload the person, so the page shows two-factor sign-in as on.314 // Reload the person, so the page shows two-factor sign-in as on.
298 let user = state315 let user = state
299 .store316 .store
@@ -380,6 +397,14 @@ async fn disable_two_factor(cx: &Cx, Form(form): Form<DisableForm>) -> Result<im
380 json!({}),397 json!({}),
381 )398 )
382 .await;399 .await;
400+ mail::notify(
401+ &state.store,
402+ &state.key,
403+ &viewer.user,
404+ lang,
405+ Notice::TwoFactorOff,
406+ )
407+ .await;
383 Err(see_other("/account/security?notice=saved-2fa-off").into())408 Err(see_other("/account/security?notice=saved-2fa-off").into())
384 }409 }
385 410
@@ -426,6 +451,14 @@ async fn regenerate_recovery(cx: &Cx, Form(form): Form<RecoveryForm>) -> Result<
426 json!({ "count": codes.len() }),451 json!({ "count": codes.len() }),
427 )452 )
428 .await;453 .await;
454+ mail::notify(
455+ &state.store,
456+ &state.key,
457+ &viewer.user,
458+ lang,
459+ Notice::RecoveryCodes,
460+ )
461+ .await;
429 let flash = Flash {462 let flash = Flash {
430 codes,463 codes,
431 ..Flash::default()464 ..Flash::default()
@@ -442,7 +475,7 @@ fn issue_codes() -> Vec<String> {
442 475
443 /// True while the password counters hold the account. Wrong passwords on this page count toward476 /// True while the password counters hold the account. Wrong passwords on this page count toward
444 /// the same limit as sign-in.477 /// the same limit as sign-in.
445-fn password_locked(state: &AppState, viewer: &Viewer) -> bool {478+pub fn password_locked(state: &AppState, viewer: &Viewer) -> bool {
446 state479 state
447 .throttle480 .throttle
448 .check(481 .check(
@@ -454,7 +487,7 @@ fn password_locked(state: &AppState, viewer: &Viewer) -> bool {
454 }487 }
455 488
456 /// Checks the password of the signed-in person and records the outcome in the throttle.489 /// Checks the password of the signed-in person and records the outcome in the throttle.
457-async fn password_matches(state: &AppState, viewer: &Viewer, given: &str) -> Result<bool> {490+pub async fn password_matches(state: &AppState, viewer: &Viewer, given: &str) -> Result<bool> {
458 let ok = verify_password_async(given.to_owned(), viewer.user.password_hash.clone()).await?;491 let ok = verify_password_async(given.to_owned(), viewer.user.password_hash.clone()).await?;
459 let limit = user_key(&viewer.user.email);492 let limit = user_key(&viewer.user.email);
460 if ok {493 if ok {
crates/im-web/src/pages/tests.rsmodified+25 -0
@@ -104,3 +104,28 @@ async fn setup_is_not_found_once_a_user_exists() {
104 let (status, _) = post_form(state, "/setup", None, "precsrf=x").await;104 let (status, _) = post_form(state, "/setup", None, "precsrf=x").await;
105 assert_eq!(status, 404);105 assert_eq!(status, 404);
106 }106 }
107+
108+/// Sends `POST /forgot` with the pre-session token and returns the status and body.
109+async fn forgot_post(state: AppState, email: &str) -> (u16, String) {
110+ let request = http::Request::post("/forgot")
111+ .header(CONTENT_TYPE, "application/x-www-form-urlencoded")
112+ .header(COOKIE, "__Host-im_precsrf=pre-token")
113+ .body(Body::from(format!("precsrf=pre-token&email={email}")))
114+ .expect("request");
115+ let response = router(state).handle(request).await;
116+ let status = response.status().as_u16();
117+ let bytes = to_bytes(response.into_body(), 1024 * 1024)
118+ .await
119+ .expect("body");
120+ (status, String::from_utf8_lossy(&bytes).into_owned())
121+}
122+
123+#[tokio::test]
124+async fn forgot_answers_the_same_for_a_known_and_an_unknown_address() {
125+ let (_dir, state) = test_state().await;
126+ signed_in(&state).await;
127+ let known = forgot_post(state.clone(), "ada%40example.com").await;
128+ let unknown = forgot_post(state.clone(), "nobody%40example.com").await;
129+ assert_eq!(known, unknown);
130+ assert_eq!(known.0, 200);
131+}
crates/im-web/src/security.rsmodified+29 -0
@@ -26,6 +26,19 @@ const HSTS: &str = "max-age=31536000";
26 /// The cache policy of every page: nothing is stored, not even for going back in the history.26 /// The cache policy of every page: nothing is stored, not even for going back in the history.
27 const NO_STORE: &str = "no-store";27 const NO_STORE: &str = "no-store";
28 28
29+/// The referrer policy of the pages that carry a single-use token in their path. The token must never leave
30+/// the site in a `Referer` header, so these pages send none at all.
31+const NO_REFERRER: &str = "no-referrer";
32+
33+/// True for the pages whose path holds a token or starts an account link: the reset request and every
34+/// `/reset/`, `/invite/` and `/email/` page.
35+pub fn token_path(path: &str) -> bool {
36+ path == "/forgot"
37+ || path.starts_with("/reset/")
38+ || path.starts_with("/invite/")
39+ || path.starts_with("/email/")
40+}
41+
29 /// The headers that every response carries, for an instance at `base_url`.42 /// The headers that every response carries, for an instance at `base_url`.
30 pub fn headers_for(base_url: &str) -> HeaderMap {43 pub fn headers_for(base_url: &str) -> HeaderMap {
31 let mut headers = HeaderMap::new();44 let mut headers = HeaderMap::new();
@@ -114,6 +127,12 @@ impl Layer for SecurityHeaders {
114 };127 };
115 if answer == Answer::Page {128 if answer == Answer::Page {
116 headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(NO_STORE));129 headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(NO_STORE));
130+ if token_path(uri(cx).path()) {
131+ headers.insert(
132+ header::REFERRER_POLICY,
133+ HeaderValue::from_static(NO_REFERRER),
134+ );
135+ }
117 }136 }
118 match next.run(cx, body).await {137 match next.run(cx, body).await {
119 // A header the route set itself wins: a token answer that is already `no-store`, or a138 // A header the route set itself wins: a token answer that is already `no-store`, or a
@@ -182,6 +201,16 @@ mod tests {
182 }201 }
183 }202 }
184 203
204+ #[test]
205+ fn token_pages_are_recognised() {
206+ assert!(token_path("/reset/abc"));
207+ assert!(token_path("/invite/abc"));
208+ assert!(token_path("/email/abc"));
209+ assert!(token_path("/forgot"));
210+ assert!(!token_path("/login"));
211+ assert!(!token_path("/resetting"));
212+ }
213+
185 #[test]214 #[test]
186 fn hsts_only_for_https_origins() {215 fn hsts_only_for_https_origins() {
187 assert!(216 assert!(
crates/im-web/src/sweeper.rsmodified+21 -1
@@ -4,7 +4,9 @@
4 //! - authorization codes that expired more than a day ago (a day is kept so that a reused code is still4 //! - authorization codes that expired more than a day ago (a day is kept so that a reused code is still
5 //! recognised as reuse, which revokes the tokens it issued);5 //! recognised as reuse, which revokes the tokens it issued);
6 //! - refresh tokens past their expiry;6 //! - refresh tokens past their expiry;
7-//! - directory change rows older than 30 days (a cursor older than the oldest row gets `resync`).7+//! - directory change rows older than 30 days (a cursor older than the oldest row gets `resync`);
8+//! - account links and invitations past their expiry;
9+//! - sent mail older than 30 days (its body was blanked when it was sent).
8 //!10 //!
9 //! Each step runs on its own: one failing step is logged and does not stop the others.11 //! Each step runs on its own: one failing step is logged and does not stop the others.
10 12
@@ -23,6 +25,9 @@ const DIRECTORY_KEEP: Duration = Duration::from_secs(30 * 24 * 60 * 60);
23 /// How long an expired authorization code is kept, so a reuse is still seen as reuse.25 /// How long an expired authorization code is kept, so a reuse is still seen as reuse.
24 const CODE_KEEP: Duration = Duration::from_secs(24 * 60 * 60);26 const CODE_KEEP: Duration = Duration::from_secs(24 * 60 * 60);
25 27
28+/// How long a sent mail is kept in the outbox before it is deleted (architecture section 8).
29+const MAIL_KEEP: Duration = Duration::from_secs(30 * 24 * 60 * 60);
30+
26 /// Starts the sweeper. It runs until `stop` is set.31 /// Starts the sweeper. It runs until `stop` is set.
27 pub fn spawn(store: Store, mut stop: watch::Receiver<bool>) -> tokio::task::JoinHandle<()> {32 pub fn spawn(store: Store, mut stop: watch::Receiver<bool>) -> tokio::task::JoinHandle<()> {
28 tokio::spawn(async move {33 tokio::spawn(async move {
@@ -63,4 +68,19 @@ pub async fn sweep_once(store: &Store) {
63 Ok(count) => tracing::info!(count, "sweeper: old directory changes removed"),68 Ok(count) => tracing::info!(count, "sweeper: old directory changes removed"),
64 Err(error) => tracing::error!(error = %error, "sweeper: directory changes"),69 Err(error) => tracing::error!(error = %error, "sweeper: directory changes"),
65 }70 }
71+ match store.sweep_links(&now).await {
72+ Ok(0) => {}
73+ Ok(count) => tracing::info!(count, "sweeper: expired account links removed"),
74+ Err(error) => tracing::error!(error = %error, "sweeper: account links"),
75+ }
76+ match store.sweep_invites(&now).await {
77+ Ok(0) => {}
78+ Ok(count) => tracing::info!(count, "sweeper: expired invitations removed"),
79+ Err(error) => tracing::error!(error = %error, "sweeper: invitations"),
80+ }
81+ match store.prune_sent_mail(&stamp_before(MAIL_KEEP)).await {
82+ Ok(0) => {}
83+ Ok(count) => tracing::info!(count, "sweeper: sent mail removed"),
84+ Err(error) => tracing::error!(error = %error, "sweeper: sent mail"),
85+ }
66 }86 }
crates/im-web/src/throttle.rsmodified+12 -0
@@ -26,6 +26,13 @@ pub const LOGIN_IP_LIMIT: usize = 30;
26 /// Failed second-factor checks allowed per user inside [`WINDOW`].26 /// Failed second-factor checks allowed per user inside [`WINDOW`].
27 pub const TWO_FACTOR_USER_LIMIT: usize = 10;27 pub const TWO_FACTOR_USER_LIMIT: usize = 10;
28 28
29+/// Reset-link requests allowed per normalised email address inside [`WINDOW`]. Every request counts, known
30+/// address or not, so the limit leaks nothing about the account.
31+pub const FORGOT_EMAIL_LIMIT: usize = 3;
32+
33+/// Reset-link requests allowed per client address inside [`WINDOW`].
34+pub const FORGOT_IP_LIMIT: usize = 20;
35+
29 /// Maximum number of distinct keys tracked at once. A flood of random keys cannot grow memory past36 /// Maximum number of distinct keys tracked at once. A flood of random keys cannot grow memory past
30 /// this.37 /// this.
31 const MAX_KEYS: usize = 100_000;38 const MAX_KEYS: usize = 100_000;
@@ -139,6 +146,11 @@ pub fn user_key(email: &str) -> String {
139 format!("user:{email}")146 format!("user:{email}")
140 }147 }
141 148
149+/// Throttle key for the reset-link requests of one normalised address.
150+pub fn forgot_email_key(email: &str) -> String {
151+ format!("forgot:{email}")
152+}
153+
142 /// Throttle key for the second factor of one user, by user id.154 /// Throttle key for the second factor of one user, by user id.
143 pub fn two_factor_key(user_id: &str) -> String {155 pub fn two_factor_key(user_id: &str) -> String {
144 format!("2fa:{user_id}")156 format!("2fa:{user_id}")