forge
Explore
Log in

Don't you dare go Hollow

The SMTP sender is typed into Settings, not the environment

Browse files at this commit

fd45c3dcea060bf830b25bf7404f4911785e4aafAhmet Kaan GümüşParent: 3e26a9a
  • feat
    • the SMTP sender is typed into Settings, not the environment
Show full message
🔒️ feat(settings): the SMTP sender is typed into Settings, not the environment

The sender panel becomes editable. An admin fills in host, port, username,
password, from-name and from-address, and the workspace can send mail without
anybody touching a shell — which is the point, since nobody on this team has
one.

The password is stored in the workspace row as typed, in the same database
file as everything else. It is a credential the server has to replay to the
mail host on every send, so hashing it is not an option; encrypting it under a
key sitting on the same disk moves the secret rather than shrinking it. What
does apply is applied: the password has no field on `Workspace` at all, so no
query can carry it outward by accident, and `WORKSPACE_COLUMNS` selects only
whether one is set. The panel's field is write-only — an empty field on an
edit means "keep the stored one" (`COALESCE`), so correcting a port cannot
blank the credential.

Both writes and reads are guarded in the handler. A Member or a signed-out
browser asking for the settings gets `"sender":null` rather than a hidden
panel, and posting `save_sender` directly is refused with nothing written.

Mail gained a third outcome. A send with no sender configured is *unsent*, not
failed: it is held for a minute without spending one of the five attempts, so
what a workspace owes still goes out once somebody fills the panel in, instead
of being abandoned two hours later.

The transport is rebuilt only when the settings actually change, keyed on the
sender itself, so editing an unrelated setting does not throw away the
connection pool.
crates/dizey-core/src/config.rsmodified+19 -217
@@ -14,34 +14,17 @@
14 //!14 //!
15 //! Whatever is finally resolved is printed once at startup — the database path15 //! Whatever is finally resolved is printed once at startup — the database path
16 //! absolute, the base URL as it will appear in mail — so "which file are we16 //! absolute, the base URL as it will appear in mail — so "which file are we
17-//! on" is answered by the log rather than by someone's memory. Passwords are17+//! on" is answered by the log rather than by someone's memory.
18-//! never among the things printed.18+//!
19+//! The sender is not here. Host, port, username, password and from-address are
20+//! workspace settings an admin writes on the Settings screen, so that changing
21+//! where mail goes out through does not need a shell on the box and a restart.
19 22
20 use std::fmt;23 use std::fmt;
21 use std::path::{Path, PathBuf};24 use std::path::{Path, PathBuf};
22 25
23 /// Every variable the app reads, in the order the report prints them.26 /// Every variable the app reads, in the order the report prints them.
24-pub const VARIABLES: &[&str] = &[27+pub const VARIABLES: &[&str] = &["DIZEY_DEV", "DIZEY_DATABASE", "DIZEY_BASE_URL"];
25- "DIZEY_DEV",
26- "DIZEY_DATABASE",
27- "DIZEY_BASE_URL",
28- "DIZEY_SMTP_HOST",
29- "DIZEY_SMTP_PORT",
30- "DIZEY_SMTP_USERNAME",
31- "DIZEY_SMTP_PASSWORD",
32- "DIZEY_MAIL_FROM",
33-];
34-
35-/// The five variables that carry a sender. They are all-or-nothing: a host
36-/// without a from-address is not a half-configured sender, it is a mistake
37-/// that would be discovered by a mail that never arrives.
38-const MAIL_VARIABLES: &[&str] = &[
39- "DIZEY_SMTP_HOST",
40- "DIZEY_SMTP_PORT",
41- "DIZEY_SMTP_USERNAME",
42- "DIZEY_SMTP_PASSWORD",
43- "DIZEY_MAIL_FROM",
44-];
45 28
46 /// What the process needs to know before it opens a socket.29 /// What the process needs to know before it opens a socket.
47 #[derive(Clone, Debug, PartialEq, Eq)]30 #[derive(Clone, Debug, PartialEq, Eq)]
@@ -50,35 +33,10 @@ pub struct Config {
50 pub database: PathBuf,33 pub database: PathBuf,
51 /// The origin links in mail point at, with no trailing slash.34 /// The origin links in mail point at, with no trailing slash.
52 pub base_url: String,35 pub base_url: String,
53- /// The sender, if one is configured. Mail stays quiet without it.
54- pub mail: Option<MailConfig>,
55 /// Whether the development defaults were taken.36 /// Whether the development defaults were taken.
56 pub dev: bool,37 pub dev: bool,
57 }38 }
58 39
59-/// Where mail goes out through. The password is in here and stays out of every
60-/// rendering of it.
61-#[derive(Clone, PartialEq, Eq)]
62-pub struct MailConfig {
63- pub host: String,
64- pub port: u16,
65- pub username: String,
66- pub password: String,
67- pub from: String,
68-}
69-
70-impl fmt::Debug for MailConfig {
71- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72- f.debug_struct("MailConfig")
73- .field("host", &self.host)
74- .field("port", &self.port)
75- .field("username", &self.username)
76- .field("password", &"…")
77- .field("from", &self.from)
78- .finish()
79- }
80-}
81-
82 /// Why the process is not starting.40 /// Why the process is not starting.
83 #[derive(Clone, Debug, PartialEq, Eq)]41 #[derive(Clone, Debug, PartialEq, Eq)]
84 pub enum ConfigError {42 pub enum ConfigError {
@@ -86,11 +44,6 @@ pub enum ConfigError {
86 Missing(Vec<&'static str>),44 Missing(Vec<&'static str>),
87 /// A variable is set to something the app cannot use.45 /// A variable is set to something the app cannot use.
88 Invalid { variable: &'static str, why: String },46 Invalid { variable: &'static str, why: String },
89- /// Some of the sender's variables are set and some are not.
90- PartialMail {
91- set: Vec<&'static str>,
92- missing: Vec<&'static str>,
93- },
94 }47 }
95 48
96 impl fmt::Display for ConfigError {49 impl fmt::Display for ConfigError {
@@ -116,13 +69,6 @@ impl fmt::Display for ConfigError {
116 "not starting: {variable} is set to something unusable — {why}"69 "not starting: {variable} is set to something unusable — {why}"
117 )70 )
118 }71 }
119- ConfigError::PartialMail { set, missing } => write!(
120- f,
121- "not starting: a mail sender is half configured — {} set, {} missing. \
122- Set all five or none; with none, Dizey sends nothing and says so.",
123- set.join(", "),
124- missing.join(", ")
125- ),
126 }72 }
127 }73 }
128 }74 }
@@ -169,12 +115,9 @@ impl Config {
169 }115 }
170 let base_url = base_url.trim_end_matches('/').to_string();116 let base_url = base_url.trim_end_matches('/').to_string();
171 117
172- let mail = mail_from(&value)?;
173-
174 Ok(Config {118 Ok(Config {
175 database: absolute(Path::new(&database.expect("checked above"))),119 database: absolute(Path::new(&database.expect("checked above"))),
176 base_url,120 base_url,
177- mail,
178 dev,121 dev,
179 })122 })
180 }123 }
@@ -185,13 +128,7 @@ impl Config {
185 format!("database {}", self.database.display()),128 format!("database {}", self.database.display()),
186 format!("base url {}", self.base_url),129 format!("base url {}", self.base_url),
187 ];130 ];
188- lines.push(match &self.mail {131+ lines.push("mail the sender is in Settings, not here".to_string());
189- Some(mail) => format!(
190- "mail {} via {}:{} as {}",
191- mail.from, mail.host, mail.port, mail.username
192- ),
193- None => "mail no sender configured — Dizey sends nothing".to_string(),
194- });
195 if self.dev {132 if self.dev {
196 lines.push("dev DIZEY_DEV=1, development defaults taken".to_string());133 lines.push("dev DIZEY_DEV=1, development defaults taken".to_string());
197 }134 }
@@ -199,55 +136,6 @@ impl Config {
199 }136 }
200 }137 }
201 138
202-fn mail_from(value: &impl Fn(&str) -> Option<String>) -> Result<Option<MailConfig>, ConfigError> {
203- let read: Vec<(&'static str, Option<String>)> = MAIL_VARIABLES
204- .iter()
205- .map(|name| (*name, value(name)))
206- .collect();
207- let set: Vec<&'static str> = read
208- .iter()
209- .filter(|(_, held)| held.is_some())
210- .map(|(name, _)| *name)
211- .collect();
212- if set.is_empty() {
213- return Ok(None);
214- }
215- let missing: Vec<&'static str> = read
216- .iter()
217- .filter(|(_, held)| held.is_none())
218- .map(|(name, _)| *name)
219- .collect();
220- if !missing.is_empty() {
221- return Err(ConfigError::PartialMail { set, missing });
222- }
223-
224- let held = |name: &str| {
225- read.iter()
226- .find(|(candidate, _)| *candidate == name)
227- .and_then(|(_, held)| held.clone())
228- .expect("all five are set")
229- };
230- let raw_port = held("DIZEY_SMTP_PORT");
231- let port = raw_port.parse::<u16>().map_err(|_| ConfigError::Invalid {
232- variable: "DIZEY_SMTP_PORT",
233- why: format!("{raw_port:?} is not a port number"),
234- })?;
235- let from = held("DIZEY_MAIL_FROM");
236- if !from.contains('@') {
237- return Err(ConfigError::Invalid {
238- variable: "DIZEY_MAIL_FROM",
239- why: format!("{from:?} is not an address"),
240- });
241- }
242-
243- Ok(Some(MailConfig {
244- host: held("DIZEY_SMTP_HOST"),
245- port,
246- username: held("DIZEY_SMTP_USERNAME"),
247- password: held("DIZEY_SMTP_PASSWORD"),
248- from,
249- }))
250-}
251 139
252 /// An absolute path for a file that may not exist yet: the directory is140 /// An absolute path for a file that may not exist yet: the directory is
253 /// resolved, the file name is kept as written.141 /// resolved, the file name is kept as written.
@@ -309,7 +197,6 @@ mod tests {
309 assert!(config.database.is_absolute(), "{:?}", config.database);197 assert!(config.database.is_absolute(), "{:?}", config.database);
310 assert!(config.database.ends_with("dizey.db"));198 assert!(config.database.ends_with("dizey.db"));
311 assert_eq!(config.base_url, "http://127.0.0.1:3000");199 assert_eq!(config.base_url, "http://127.0.0.1:3000");
312- assert!(config.mail.is_none());
313 }200 }
314 201
315 #[test]202 #[test]
@@ -357,49 +244,13 @@ mod tests {
357 assert_eq!(config.base_url, "https://dizey.sh");244 assert_eq!(config.base_url, "https://dizey.sh");
358 }245 }
359 246
247+ /// The sender used to be five environment variables. It is workspace
248+ /// settings now, so a stale `DIZEY_SMTP_PASSWORD` left in a unit file or a
249+ /// shell must do nothing at all — not half-configure a sender, not stop the
250+ /// boot, and above all not quietly send through an account the Settings
251+ /// screen does not show.
360 #[test]252 #[test]
361- fn no_sender_is_a_configuration_not_an_error() {253+ fn leftover_sender_variables_are_ignored_entirely() {
362- let config = Config::read(env(&[
363- ("DIZEY_DATABASE", "/srv/dizey.db"),
364- ("DIZEY_BASE_URL", "https://dizey.sh"),
365- ]))
366- .unwrap();
367- assert!(config.mail.is_none());
368- assert!(
369- config
370- .report()
371- .iter()
372- .any(|line| line.contains("no sender configured")),
373- "{:?}",
374- config.report()
375- );
376- }
377-
378- #[test]
379- fn half_a_sender_stops_the_boot_and_names_both_halves() {
380- let problem = Config::read(env(&[
381- ("DIZEY_DATABASE", "/srv/dizey.db"),
382- ("DIZEY_BASE_URL", "https://dizey.sh"),
383- ("DIZEY_SMTP_HOST", "smtp.example.net"),
384- ("DIZEY_SMTP_PORT", "587"),
385- ]))
386- .unwrap_err();
387- let ConfigError::PartialMail { set, missing } = &problem else {
388- panic!("expected the half-configured sender, got {problem:?}");
389- };
390- assert_eq!(set, &["DIZEY_SMTP_HOST", "DIZEY_SMTP_PORT"]);
391- assert_eq!(
392- missing,
393- &[
394- "DIZEY_SMTP_USERNAME",
395- "DIZEY_SMTP_PASSWORD",
396- "DIZEY_MAIL_FROM"
397- ]
398- );
399- }
400-
401- #[test]
402- fn a_whole_sender_is_read_and_its_password_is_never_printed() {
403 let config = Config::read(env(&[254 let config = Config::read(env(&[
404 ("DIZEY_DATABASE", "/srv/dizey.db"),255 ("DIZEY_DATABASE", "/srv/dizey.db"),
405 ("DIZEY_BASE_URL", "https://dizey.sh"),256 ("DIZEY_BASE_URL", "https://dizey.sh"),
@@ -409,71 +260,22 @@ mod tests {
409 ("DIZEY_SMTP_PASSWORD", "hunter2-and-then-some"),260 ("DIZEY_SMTP_PASSWORD", "hunter2-and-then-some"),
410 ("DIZEY_MAIL_FROM", "board@dizey.sh"),261 ("DIZEY_MAIL_FROM", "board@dizey.sh"),
411 ]))262 ]))
412- .unwrap();263+ .expect("a stale sender in the environment is not an error");
413- let mail = config.mail.clone().expect("a sender");
414- assert_eq!(mail.port, 587);
415- assert_eq!(mail.from, "board@dizey.sh");
416 264
417 let report = config.report().join("\n");265 let report = config.report().join("\n");
418- assert!(report.contains("board@dizey.sh"), "{report}");
419- assert!(!report.contains("hunter2-and-then-some"), "{report}");
420- let debugged = format!("{mail:?}");
421- assert!(!debugged.contains("hunter2-and-then-some"), "{debugged}");
422- }
423-
424- #[test]
425- fn a_port_that_is_not_a_port_stops_the_boot() {
426- let problem = Config::read(env(&[
427- ("DIZEY_DATABASE", "/srv/dizey.db"),
428- ("DIZEY_BASE_URL", "https://dizey.sh"),
429- ("DIZEY_SMTP_HOST", "smtp.example.net"),
430- ("DIZEY_SMTP_PORT", "not-a-port"),
431- ("DIZEY_SMTP_USERNAME", "dizey"),
432- ("DIZEY_SMTP_PASSWORD", "secret"),
433- ("DIZEY_MAIL_FROM", "board@dizey.sh"),
434- ]))
435- .unwrap_err();
436 assert!(266 assert!(
437- matches!(267+ !report.contains("hunter2-and-then-some") && !report.contains("smtp.example.net"),
438- problem,268+ "the report read a variable it no longer honours: {report}"
439- ConfigError::Invalid {
440- variable: "DIZEY_SMTP_PORT",
441- ..
442- }
443- ),
444- "{problem:?}"
445 );269 );
446- }
447-
448- #[test]
449- fn a_from_address_without_an_at_sign_stops_the_boot() {
450- let problem = Config::read(env(&[
451- ("DIZEY_DATABASE", "/srv/dizey.db"),
452- ("DIZEY_BASE_URL", "https://dizey.sh"),
453- ("DIZEY_SMTP_HOST", "smtp.example.net"),
454- ("DIZEY_SMTP_PORT", "587"),
455- ("DIZEY_SMTP_USERNAME", "dizey"),
456- ("DIZEY_SMTP_PASSWORD", "secret"),
457- ("DIZEY_MAIL_FROM", "board-at-dizey"),
458- ]))
459- .unwrap_err();
460 assert!(270 assert!(
461- matches!(271+ report.contains("the sender is in Settings"),
462- problem,272+ "the report should say where the sender lives: {report}"
463- ConfigError::Invalid {
464- variable: "DIZEY_MAIL_FROM",
465- ..
466- }
467- ),
468- "{problem:?}"
469 );273 );
470 }274 }
471 275
472 #[test]276 #[test]
473 fn every_variable_the_app_reads_is_named_in_one_list() {277 fn every_variable_the_app_reads_is_named_in_one_list() {
474- for name in MAIL_VARIABLES {278+ assert_eq!(VARIABLES.len(), 3, "a variable was added without a line here");
475- assert!(VARIABLES.contains(name), "{name} is missing from VARIABLES");
476- }
477 assert!(VARIABLES.contains(&"DIZEY_DEV"));279 assert!(VARIABLES.contains(&"DIZEY_DEV"));
478 assert!(VARIABLES.contains(&"DIZEY_DATABASE"));280 assert!(VARIABLES.contains(&"DIZEY_DATABASE"));
479 assert!(VARIABLES.contains(&"DIZEY_BASE_URL"));281 assert!(VARIABLES.contains(&"DIZEY_BASE_URL"));
crates/dizey-core/src/mail.rsmodified+35 -0
@@ -34,6 +34,11 @@ pub struct MailError {
34 /// A timeout or a host that is down may work in a minute. A refused34 /// A timeout or a host that is down may work in a minute. A refused
35 /// address will not, and retrying it forever is noise nobody reads.35 /// address will not, and retrying it forever is noise nobody reads.
36 pub retryable: bool,36 pub retryable: bool,
37+ /// Whether a mail server was actually asked. `false` means the mail never
38+ /// left the building — there is no sender configured yet — and that must
39+ /// not spend one of the five attempts, or a workspace whose admin sets the
40+ /// sender up tomorrow finds that today's mail was given up on overnight.
41+ pub attempted: bool,
37 }42 }
38 43
39 impl MailError {44 impl MailError {
@@ -41,6 +46,7 @@ impl MailError {
41 Self {46 Self {
42 message: message.into(),47 message: message.into(),
43 retryable: true,48 retryable: true,
49+ attempted: true,
44 }50 }
45 }51 }
46 52
@@ -48,6 +54,18 @@ impl MailError {
48 Self {54 Self {
49 message: message.into(),55 message: message.into(),
50 retryable: false,56 retryable: false,
57+ attempted: true,
58+ }
59+ }
60+
61+ /// Nothing was sent and nothing was asked: the workspace has no sender.
62+ /// The mail stays owed, at no cost to its attempts, and goes out when a
63+ /// sender exists — which is exactly what the empty-sender panel promises.
64+ pub fn unsent(message: impl Into<String>) -> Self {
65+ Self {
66+ message: message.into(),
67+ retryable: true,
68+ attempted: false,
51 }69 }
52 }70 }
53 }71 }
@@ -71,6 +89,11 @@ pub trait Mailer: Send + Sync {
71 /// written down as abandoned.89 /// written down as abandoned.
72 pub const MAX_ATTEMPTS: u32 = 5;90 pub const MAX_ATTEMPTS: u32 = 5;
73 91
92+/// How long a mail with no sender waits before it is looked at again. Short,
93+/// because the thing it waits on is an admin finishing a form and then watching
94+/// to see whether mail starts moving.
95+pub const HOLD: Duration = Duration::minutes(1);
96+
74 /// The wait before the next attempt, doubling and capped: five minutes, ten,97 /// The wait before the next attempt, doubling and capped: five minutes, ten,
75 /// twenty, forty, an hour.98 /// twenty, forty, an hour.
76 pub fn backoff(attempts: u32) -> Duration {99 pub fn backoff(attempts: u32) -> Duration {
@@ -89,6 +112,9 @@ pub struct Report {
89 pub failed: u32,112 pub failed: u32,
90 /// Refusals that will not.113 /// Refusals that will not.
91 pub abandoned: u32,114 pub abandoned: u32,
115+ /// Mails held back because there is no sender to send them through. Owed,
116+ /// not failed: no attempt was spent and none will be until one exists.
117+ pub held: u32,
92 }118 }
93 119
94 pub struct Engine {120 pub struct Engine {
@@ -284,6 +310,15 @@ impl Engine {
284 self.store.record_send_accepted(&send.id, now).await?;310 self.store.record_send_accepted(&send.id, now).await?;
285 report.sent += 1;311 report.sent += 1;
286 }312 }
313+ Err(problem) if !problem.attempted => {
314+ // No sender. The mail keeps its place in the ledger and its
315+ // attempts, and is looked at again on the next sweep — by then
316+ // an admin may have filled the panel in.
317+ self.store
318+ .defer_send(&send.id, &problem.message, now + HOLD, now)
319+ .await?;
320+ report.held += 1;
321+ }
287 Err(problem) => {322 Err(problem) => {
288 let attempts = send.attempts + 1;323 let attempts = send.attempts + 1;
289 // The last attempt is written down as given up on rather than324 // The last attempt is written down as given up on rather than
crates/dizey-core/src/store/mod.rsmodified+12 -0
@@ -605,6 +605,18 @@ pub trait Store: BoardReads + DetailReads + 'static {
605 at: OffsetDateTime,605 at: OffsetDateTime,
606 ) -> Result<()>;606 ) -> Result<()>;
607 607
608+ /// Holds a send that was never attempted, because the workspace has no
609+ /// sender. The reason is written down like any refusal so the ledger does
610+ /// not go quiet, but `attempts` is left alone: nothing was spent, so
611+ /// nothing is charged, and the mail is still owed when a sender appears.
612+ async fn defer_send(
613+ &self,
614+ send_id: &str,
615+ reason: &str,
616+ retry_at: OffsetDateTime,
617+ at: OffsetDateTime,
618+ ) -> Result<()>;
619+
608 /// Sends owed right now: claimed but never accepted, and due.620 /// Sends owed right now: claimed but never accepted, and due.
609 async fn sends_owed(&self, now: OffsetDateTime, limit: u32) -> Result<Vec<MailSend>>;621 async fn sends_owed(&self, now: OffsetDateTime, limit: u32) -> Result<Vec<MailSend>>;
610 622
crates/dizey-core/src/store/turso_store.rsmodified+26 -0
@@ -1968,6 +1968,32 @@ impl Store for TursoStore {
1968 Ok(())1968 Ok(())
1969 }1969 }
1970 1970
1971+ async fn defer_send(
1972+ &self,
1973+ send_id: &str,
1974+ reason: &str,
1975+ retry_at: OffsetDateTime,
1976+ _at: OffsetDateTime,
1977+ ) -> Result<()> {
1978+ // `attempts` is deliberately not touched. Everything else reads like a
1979+ // refusal that will be retried, because that is what it is — the mail
1980+ // is owed, it is due again shortly, and the reason says why it waited.
1981+ let n = self
1982+ .conn
1983+ .execute(
1984+ "UPDATE mail_send \
1985+ SET state = 'failed', last_error = ?1, next_attempt_at = ?2 \
1986+ WHERE id = ?3",
1987+ params![reason, stamp(retry_at)?, send_id],
1988+ )
1989+ .await
1990+ .map_err(backend)?;
1991+ if n == 0 {
1992+ return Err(StoreError::NotFound);
1993+ }
1994+ Ok(())
1995+ }
1996+
1971 async fn sends_owed(&self, now: OffsetDateTime, limit: u32) -> Result<Vec<MailSend>> {1997 async fn sends_owed(&self, now: OffsetDateTime, limit: u32) -> Result<Vec<MailSend>> {
1972 let sql = format!(1998 let sql = format!(
1973 "SELECT {SEND_COLUMNS} FROM mail_send \1999 "SELECT {SEND_COLUMNS} FROM mail_send \
crates/dizey-web/src/auth.rsmodified+7 -0
@@ -39,6 +39,11 @@ pub enum Refusal {
39 BadLimit,39 BadLimit,
40 /// Something in the allowed-types list is not a file extension.40 /// Something in the allowed-types list is not a file extension.
41 BadFileType,41 BadFileType,
42+ /// The sender panel was saved with a field it cannot work without, or with
43+ /// one that is not what it claims to be. The message names the field: this
44+ /// is a form somebody is filling in, not an attacker probing, and "that did
45+ /// not work" would send them round the panel guessing.
46+ BadSender(String),
42 /// A comment with nothing in it.47 /// A comment with nothing in it.
43 EmptyComment,48 EmptyComment,
44 /// The date field did not hold a date.49 /// The date field did not hold a date.
@@ -78,6 +83,7 @@ impl Refusal {
78 Refusal::BadFileType => {83 Refusal::BadFileType => {
79 "File types are extensions — png, pdf, zip — separated by commas.".to_string()84 "File types are extensions — png, pdf, zip — separated by commas.".to_string()
80 }85 }
86+ Refusal::BadSender(problem) => problem.clone(),
81 Refusal::EmptyComment => "Write something first.".to_string(),87 Refusal::EmptyComment => "Write something first.".to_string(),
82 Refusal::BadDeadline => "That is not a date.".to_string(),88 Refusal::BadDeadline => "That is not a date.".to_string(),
83 Refusal::Cycle => "That link would put this task behind itself.".to_string(),89 Refusal::Cycle => "That link would put this task behind itself.".to_string(),
@@ -119,6 +125,7 @@ impl Refusal {
119 Refusal::EmptyName => "empty-name",125 Refusal::EmptyName => "empty-name",
120 Refusal::BadLimit => "bad-limit",126 Refusal::BadLimit => "bad-limit",
121 Refusal::BadFileType => "bad-file-type",127 Refusal::BadFileType => "bad-file-type",
128+ Refusal::BadSender(_) => "bad-sender",
122 Refusal::EmptyComment => "empty-comment",129 Refusal::EmptyComment => "empty-comment",
123 Refusal::BadDeadline => "bad-deadline",130 Refusal::BadDeadline => "bad-deadline",
124 Refusal::Cycle => "cycle",131 Refusal::Cycle => "cycle",
crates/dizey-web/src/main.rsmodified+12 -29
@@ -32,40 +32,23 @@ async fn main() {
32 let store: Arc<dyn dizey_core::store::Store> = Arc::new(store);32 let store: Arc<dyn dizey_core::store::Store> = Arc::new(store);
33 let accounts = Accounts::new(store.clone());33 let accounts = Accounts::new(store.clone());
34 34
35- // A workspace without a sender still works: cards move, rules can be35+ // The engine is always built, because a sender can appear at any moment:
36- // written, nothing goes out. With one, the engine is built once — it holds36+ // an admin fills the panel in and the next sweep sends what was held. It
37- // a connection pool — and two things use it: every committed crossing, and37+ // holds one connection pool, rebuilt only when the settings behind it
38- // the sweep below.38+ // change, and two things use it — every committed crossing, and the sweep.
39- let mail = match &config.mail {39+ let engine = Arc::new(dizey_core::MailEngine::new(
40- Some(sender) => {40+ store.clone(),
41- let smtp = dizey_web::smtp::Smtp::new(sender).unwrap_or_else(|problem| {41+ Arc::new(dizey_web::smtp::WorkspaceSmtp::new(store.clone())),
42- eprintln!("dizey: {problem}");42+ config.base_url.clone(),
43- std::process::exit(2);43+ ));
44- });44+ tokio::spawn(sweep(engine.clone()));
45- let engine = Arc::new(dizey_core::MailEngine::new(45+ let mail = dizey_web::server::Mail::sending(engine);
46- store.clone(),
47- Arc::new(smtp),
48- config.base_url.clone(),
49- ));
50- tokio::spawn(sweep(engine.clone()));
51- dizey_web::server::Mail::sending(engine)
52- }
53- None => dizey_web::server::Mail::silent(),
54- };
55 46
56 let conf = get_configuration(None).expect("failed to read leptos configuration");47 let conf = get_configuration(None).expect("failed to read leptos configuration");
57 let leptos_options = conf.leptos_options;48 let leptos_options = conf.leptos_options;
58 let addr = leptos_options.site_addr;49 let addr = leptos_options.site_addr;
59 50
60- // What the settings screen may show of the sender: host, port, username51+ let app = dizey_web::server::router(accounts, mail, leptos_options);
61- // and from-address, and nothing else. The password stays in `config.mail`
62- // where the mailer reads it.
63- let sender = config
64- .mail
65- .as_ref()
66- .map(dizey_web::settings::Sender::of);
67-
68- let app = dizey_web::server::router(accounts, mail, sender, leptos_options);
69 52
70 let listener = tokio::net::TcpListener::bind(&addr)53 let listener = tokio::net::TcpListener::bind(&addr)
71 .await54 .await
crates/dizey-web/src/server.rsmodified+7 -12
@@ -22,17 +22,17 @@ pub fn accounts() -> Accounts {
22 expect_context::<Accounts>()22 expect_context::<Accounts>()
23 }23 }
24 24
25-/// The mail engine, or the fact that there is nobody to send through.25+/// The mail engine, or the fact that there is nobody to hand a crossing to.
26 ///26 ///
27-/// A workspace with no sender configured is a working workspace: cards move,27+/// The running server always has an engine: the sender is workspace settings
28-/// rules can be written, and nothing is mailed. That is a configuration, not a28+/// now, so it can appear at any moment and the engine reads it per send. The
29-/// broken deployment, so it is a `None` here rather than an error at the call29+/// `None` is for tests, which drive the router without one and assert on the
30-/// site of every move.30+/// ledger rather than on a mail server.
31 #[derive(Clone)]31 #[derive(Clone)]
32 pub struct Mail(Option<std::sync::Arc<Engine>>);32 pub struct Mail(Option<std::sync::Arc<Engine>>);
33 33
34 impl Mail {34 impl Mail {
35- /// No sender. Crossings are recorded and nothing goes out.35+ /// No engine at all. Crossings are recorded and nothing is handed on.
36 pub fn silent() -> Self {36 pub fn silent() -> Self {
37 Self(None)37 Self(None)
38 }38 }
@@ -88,7 +88,7 @@ impl Mail {
88 }88 }
89 89
90 /// The engine for this request, or a silent one when the router was built90 /// The engine for this request, or a silent one when the router was built
91-/// without a sender.91+/// without an engine at all.
92 pub fn mail() -> Mail {92 pub fn mail() -> Mail {
93 use_context::<Mail>().unwrap_or_else(Mail::silent)93 use_context::<Mail>().unwrap_or_else(Mail::silent)
94 }94 }
@@ -229,7 +229,6 @@ impl From<AccountError> for Refusal {
229 pub fn router(229 pub fn router(
230 accounts: Accounts,230 accounts: Accounts,
231 mail: Mail,231 mail: Mail,
232- sender: Option<crate::settings::Sender>,
233 leptos_options: LeptosOptions,232 leptos_options: LeptosOptions,
234 ) -> axum::Router {233 ) -> axum::Router {
235 use axum::Router;234 use axum::Router;
@@ -246,13 +245,9 @@ pub fn router(
246 // `leptos_routes_with_context` registers with the same closure.245 // `leptos_routes_with_context` registers with the same closure.
247 let accounts = accounts.clone();246 let accounts = accounts.clone();
248 let mail = mail.clone();247 let mail = mail.clone();
249- let sender = sender.clone();
250 move || {248 move || {
251 provide_context(accounts.clone());249 provide_context(accounts.clone());
252 provide_context(mail.clone());250 provide_context(mail.clone());
253- // What a settings screen may say about the sender. The
254- // password is not in it and has no field to be in.
255- provide_context(sender.clone());
256 }251 }
257 },252 },
258 {253 {
crates/dizey-web/src/settings.rsmodified+264 -79
@@ -11,31 +11,47 @@ use serde::{Deserialize, Serialize};
11 11
12 use crate::auth::{Me, Refusal};12 use crate::auth::{Me, Refusal};
13 13
14-/// The sender the process was started with, as a screen may see it.14+/// The sender as the admin's screen may see it.
15 ///15 ///
16 /// The password is not a field here and there is no field it could be put in.16 /// The password is not a field here and there is no field it could be put in.
17-/// It lives in `DIZEY_SMTP_PASSWORD`, is read once at boot and is held only by17+/// The store keeps it in a column the workspace read path never selects, and
18-/// the mailer; the database has no column for it since migration 0006. A18+/// the only reader is the mailer. What the screen gets instead is
19-/// sender is all-or-nothing in configuration — five variables or none — so a19+/// `password_set`: enough to say "set" beside the field, and enough to know
20-/// sender that exists is a sender whose password is set, and that is the whole20+/// that a save which sends no password is an edit rather than a deletion.
21-/// of what this type can say about it.21+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
22-#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
23 pub struct Sender {22 pub struct Sender {
24 pub host: String,23 pub host: String,
25 pub port: u16,24 pub port: u16,
26 pub username: String,25 pub username: String,
27- pub from: String,26+ pub from_name: String,
27+ pub from_address: String,
28+ pub password_set: bool,
29+}
30+
31+impl Sender {
32+ /// Whether this is a sender at all, or an empty panel waiting to be filled
33+ /// in. Mail waits, rather than fails, until this is true.
34+ pub fn is_connected(&self) -> bool {
35+ !self.host.trim().is_empty()
36+ && !self.username.trim().is_empty()
37+ && !self.from_address.trim().is_empty()
38+ && self.password_set
39+ }
28 }40 }
29 41
30 #[cfg(feature = "ssr")]42 #[cfg(feature = "ssr")]
31 impl Sender {43 impl Sender {
32- /// What the screen may see of the sender the process is running with.44+ /// What the screen may see of the workspace's sender.
33- pub fn of(config: &dizey_core::config::MailConfig) -> Self {45+ pub fn of(workspace: &dizey_core::store::Workspace) -> Self {
34 Self {46 Self {
35- host: config.host.clone(),47+ host: workspace.smtp_host.clone().unwrap_or_default(),
36- port: config.port,48+ // 587 is submission with STARTTLS, which is what a new panel should
37- username: config.username.clone(),49+ // suggest rather than making somebody look it up.
38- from: config.from.clone(),50+ port: workspace.smtp_port.and_then(|p| u16::try_from(p).ok()).unwrap_or(587),
51+ username: workspace.smtp_username.clone().unwrap_or_default(),
52+ from_name: workspace.smtp_from_name.clone().unwrap_or_default(),
53+ from_address: workspace.smtp_from_address.clone().unwrap_or_default(),
54+ password_set: workspace.smtp_password_set,
39 }55 }
40 }56 }
41 }57 }
@@ -77,10 +93,10 @@ pub struct Member {
77 pub is_owner: bool,93 pub is_owner: bool,
78 }94 }
79 95
80-/// One settings screen's worth of state. `sender` is `None` for two different96+/// One settings screen's worth of state. `sender` is `None` for exactly one
81-/// reasons — no sender configured, or not an admin asking — and neither of97+/// reason — the person asking does not administer the workspace — and a
82-/// them is a reason to send a host name to somebody who may not have it, so98+/// workspace with no sender yet carries an empty one, which is the panel an
83-/// the two are one answer here.99+/// admin fills in. Nobody else is told a host name.
84 #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]100 #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
85 pub struct SettingsSnapshot {101 pub struct SettingsSnapshot {
86 pub me: Me,102 pub me: Me,
@@ -121,14 +137,28 @@ pub async fn current_settings() -> Result<Result<SettingsSnapshot, Refusal>, Ser
121 },137 },
122 administers,138 administers,
123 // Only an admin is told anything about the sender at all.139 // Only an admin is told anything about the sender at all.
124- sender: administers140+ sender: match administers {
125- .then(|| use_context::<Option<Sender>>().flatten())141+ true => Some(sender_now().await?),
126- .flatten(),142+ false => None,
143+ },
127 limits,144 limits,
128 members,145 members,
129 }))146 }))
130 }147 }
131 148
149+#[cfg(feature = "ssr")]
150+async fn sender_now() -> Result<Sender, ServerFnError> {
151+ let store = crate::server::accounts().store().clone();
152+ let workspace = store
153+ .workspace()
154+ .await
155+ .map_err(|e| ServerFnError::new(e.to_string()))?;
156+ // A workspace that somehow is not there yet reads as an empty panel rather
157+ // than an error: there is nothing to correct and nothing to alarm anyone
158+ // with, and the fields are the same ones either way.
159+ Ok(workspace.as_ref().map(Sender::of).unwrap_or_default())
160+}
161+
132 #[cfg(feature = "ssr")]162 #[cfg(feature = "ssr")]
133 async fn members_now(asking: &dizey_core::store::User) -> Result<Vec<Member>, ServerFnError> {163 async fn members_now(asking: &dizey_core::store::User) -> Result<Vec<Member>, ServerFnError> {
134 let store = crate::server::accounts().store().clone();164 let store = crate::server::accounts().store().clone();
@@ -237,6 +267,106 @@ pub async fn save_limits(
237 }267 }
238 }268 }
239 269
270+/// Writes the workspace's sender. Admin-only, checked here.
271+///
272+/// `password` is empty when the admin did not type one, and empty means "leave
273+/// the stored one alone" rather than "delete it": the field is write-only, so
274+/// the form has nothing to send back for a password that already exists, and a
275+/// save that took the blank literally would stop the workspace sending mail as
276+/// a side effect of fixing a typo in the port.
277+///
278+/// A sender with no password at all is refused rather than stored, because a
279+/// half-filled sender is not a configuration — it is a mail nobody receives and
280+/// a ledger nobody reads.
281+#[server]
282+pub async fn save_sender(
283+ host: String,
284+ port: u32,
285+ username: String,
286+ password: String,
287+ from_name: String,
288+ from_address: String,
289+) -> Result<Option<Refusal>, ServerFnError> {
290+ use crate::server::{accounts, require_admin};
291+ use dizey_core::store::NewSender;
292+
293+ let admin = match require_admin().await {
294+ Ok(admin) => admin,
295+ Err(refusal) => return Ok(Some(refusal)),
296+ };
297+
298+ let host = host.trim().to_string();
299+ let username = username.trim().to_string();
300+ let from_name = from_name.trim().to_string();
301+ let from_address = from_address.trim().to_string();
302+ // Not typed is not the same as blanked. Nothing here can clear a stored
303+ // password; replacing it means typing a new one.
304+ let password = (!password.is_empty()).then_some(password);
305+
306+ let store = accounts().store().clone();
307+ let known = store
308+ .workspace()
309+ .await
310+ .map_err(|e| ServerFnError::new(e.to_string()))?
311+ .map(|ws| ws.smtp_password_set)
312+ .unwrap_or(false);
313+
314+ let complaint = if host.is_empty() {
315+ Some("The SMTP host is the server your mail goes out through — smtp.fastmail.com, for instance.")
316+ } else if host.contains(char::is_whitespace) || host.contains('@') || host.contains('/') {
317+ Some("The SMTP host is a host name, not an address or a URL.")
318+ } else if !(1..=65535).contains(&port) {
319+ Some("A port is a number between 1 and 65535. 587 is the usual one; 465 is the other.")
320+ } else if username.is_empty() {
321+ Some("The username is the account Dizey signs in to the mail server with.")
322+ } else if password.is_none() && !known {
323+ Some("A password is needed the first time. It is stored so Dizey can sign in on every send, and is never shown again.")
324+ } else if !is_address(&from_address) {
325+ Some("The from-address is the address people will see this mail come from.")
326+ } else {
327+ None
328+ };
329+ if let Some(problem) = complaint {
330+ return Ok(Some(Refusal::BadSender(problem.to_string())));
331+ }
332+
333+ match store
334+ .set_sender(
335+ &admin.workspace_id,
336+ NewSender {
337+ host,
338+ port,
339+ username,
340+ password,
341+ from_name,
342+ from_address,
343+ },
344+ )
345+ .await
346+ {
347+ Ok(()) => Ok(None),
348+ Err(problem) => {
349+ eprintln!("store error: {problem}");
350+ Ok(Some(Refusal::Unavailable))
351+ }
352+ }
353+}
354+
355+/// The shallowest check that catches a typo without rejecting a real address.
356+/// Nothing here is trying to decide what RFC 5322 permits — the mail server
357+/// settles that, and a refusal from it lands in the ledger with its own words.
358+pub fn is_address(raw: &str) -> bool {
359+ let mut halves = raw.split('@');
360+ let (Some(local), Some(domain), None) = (halves.next(), halves.next(), halves.next()) else {
361+ return false;
362+ };
363+ !local.is_empty()
364+ && domain.contains('.')
365+ && !domain.starts_with('.')
366+ && !domain.ends_with('.')
367+ && !raw.contains(char::is_whitespace)
368+}
369+
240 /// The typed list as extensions, or `None` if one of them is not an extension.370 /// The typed list as extensions, or `None` if one of them is not an extension.
241 ///371 ///
242 /// Lowercased, dots dropped, duplicates dropped, and nothing but letters and372 /// Lowercased, dots dropped, duplicates dropped, and nothing but letters and
@@ -347,7 +477,6 @@ fn SettingsScreen(
347 link_refusal: RwSignal<Option<String>>,477 link_refusal: RwSignal<Option<String>>,
348 ) -> impl IntoView {478 ) -> impl IntoView {
349 let me = snapshot.me.clone();479 let me = snapshot.me.clone();
350- let has_sender = snapshot.sender.is_some();
351 // Three roles, three true sentences. A Viewer is never mailed by a rule, so480 // Three roles, three true sentences. A Viewer is never mailed by a rule, so
352 // the member's line is not merely vague for them, it is wrong.481 // the member's line is not merely vague for them, it is wrong.
353 let role_note = match me.role {482 let role_note = match me.role {
@@ -396,9 +525,7 @@ fn SettingsScreen(
396 <ProfilePanel me=me.clone()/>525 <ProfilePanel me=me.clone()/>
397 {snapshot526 {snapshot
398 .sender527 .sender
399- .map(|sender| view! { <SenderPanel sender=sender/> })}528+ .map(|sender| view! { <SenderPanel sender=sender on_change=on_change/> })}
400- {(snapshot.administers && !has_sender)
401- .then(|| view! { <NoSenderPanel/> })}
402 {snapshot.limits.map(|limits| view! { <LimitsPanel limits=limits/> })}529 {snapshot.limits.map(|limits| view! { <LimitsPanel limits=limits/> })}
403 {snapshot530 {snapshot
404 .members531 .members
@@ -469,77 +596,135 @@ fn ProfilePanel(me: Me) -> impl IntoView {
469 }596 }
470 }597 }
471 598
472-/// The sender, as the process is running it. Every control is disabled and599+/// The sender the whole workspace mails through, as an admin edits it.
473-/// says why: none of this is workspace content, so there is nothing here a600+///
474-/// save could write.601+/// The password field is write-only in both directions: it is never filled in,
602+/// because the server does not send it, and leaving it empty on a save means
603+/// "keep the one you have". The row underneath says which of those is true, so
604+/// an empty box is never ambiguous.
475 #[component]605 #[component]
476-fn SenderPanel(sender: Sender) -> impl IntoView {606+fn SenderPanel(sender: Sender, on_change: Callback<()>) -> impl IntoView {
607+ let action = ServerAction::<SaveSender>::new();
608+ let value = action.value();
609+ let saved = move || matches!(value.get(), Some(Ok(None)));
610+ let refusal = move || match value.get() {
611+ Some(Ok(Some(refusal))) => Some(refusal.message()),
612+ Some(Err(_)) => Some(Refusal::Unavailable.message()),
613+ _ => None,
614+ };
615+ // A saved sender changes the chip, the password row and whether mail moves
616+ // at all, so the snapshot behind this panel is refetched rather than left
617+ // saying what was true before the save.
618+ Effect::new(move |_| {
619+ if matches!(value.get(), Some(Ok(None))) {
620+ on_change.run(());
621+ }
622+ });
623+
624+ let connected = sender.is_connected();
625+ let password_set = sender.password_set;
626+
477 view! {627 view! {
478 <section class="panel">628 <section class="panel">
479 <div class="panel-head">629 <div class="panel-head">
480 <h2 class="panel-title">"Outgoing mail"</h2>630 <h2 class="panel-title">"Outgoing mail"</h2>
481 <span class="chip chip-admin">"Admin only"</span>631 <span class="chip chip-admin">"Admin only"</span>
482- <span class="chip chip-connected">"Connected"</span>632+ {match connected {
633+ true => view! { <span class="chip chip-connected">"Connected"</span> }.into_any(),
634+ false => view! { <span class="chip chip-off">"Not configured"</span> }.into_any(),
635+ }}
483 </div>636 </div>
484 <div class="panel-body">637 <div class="panel-body">
485 <p class="panel-lede">638 <p class="panel-lede">
486 "One sender for the whole workspace. Every mail rule, for every member, sends through this account — nobody sets their own."639 "One sender for the whole workspace. Every mail rule, for every member, sends through this account — nobody sets their own."
487 </p>640 </p>
488- <div class="field-row">641+ {(!connected)
642+ .then(|| {
643+ view! {
644+ <p class="panel-lede">
645+ "Nothing is sent until this is filled in. Cards still move and rules still fire — what they owe is kept, and goes out on the next sweep after you save."
646+ </p>
647+ }
648+ })}
649+ <ActionForm action=action>
650+ <div class="field-row">
651+ <label class="field">
652+ <span class="field-label">"SMTP HOST"</span>
653+ <input
654+ class="field-input"
655+ type="text"
656+ name="host"
657+ value=sender.host
658+ placeholder="smtp.fastmail.com"
659+ />
660+ </label>
661+ <label class="field field-narrow">
662+ <span class="field-label">"PORT"</span>
663+ <input
664+ class="field-input"
665+ type="number"
666+ name="port"
667+ min="1"
668+ max="65535"
669+ value=sender.port.to_string()
670+ />
671+ </label>
672+ </div>
489 <label class="field">673 <label class="field">
490- <span class="field-label">"SMTP HOST"</span>674+ <span class="field-label">"USERNAME"</span>
491- <input class="field-input" type="text" value=sender.host disabled/>675+ <input class="field-input" type="text" name="username" value=sender.username/>
492 </label>676 </label>
493- <label class="field field-narrow">677+ <label class="field">
494- <span class="field-label">"PORT"</span>678+ <span class="field-label">"PASSWORD"</span>
495 <input679 <input
496 class="field-input"680 class="field-input"
497- type="text"681+ type="password"
498- value=sender.port.to_string()682+ name="password"
499- disabled683+ autocomplete="off"
684+ placeholder=match password_set {
685+ true => "Set — type a new one to replace it",
686+ false => "Needed before anything can be sent",
687+ }
500 />688 />
689+ <span class="field-note">
690+ {match password_set {
691+ true => "A password is stored. It is never shown again — not here, not in any answer this page receives. Leave this empty and the stored one is kept.",
692+ false => "No password is stored yet. It is kept so Dizey can sign in to the mail server on every send, and is never shown again once saved.",
693+ }}
694+ </span>
501 </label>695 </label>
502- </div>696+ <div class="field-row">
503- <label class="field">697+ <label class="field">
504- <span class="field-label">"USERNAME"</span>698+ <span class="field-label">"FROM NAME"</span>
505- <input class="field-input" type="text" value=sender.username disabled/>699+ <input
506- </label>700+ class="field-input"
507- <label class="field">701+ type="text"
508- <span class="field-label">"PASSWORD"</span>702+ name="from_name"
509- <div class="field-stated">"Set — in the server's configuration"</div>703+ value=sender.from_name
510- <span class="field-note">704+ placeholder="Dizey"
511- "The password is read from DIZEY_SMTP_PASSWORD when the process starts and is never stored, never shown and never sent to this page. Changing it means changing that variable and restarting Dizey."705+ />
512- </span>706+ </label>
513- </label>707+ <label class="field">
514- <label class="field">708+ <span class="field-label">"FROM ADDRESS"</span>
515- <span class="field-label">"FROM ADDRESS"</span>709+ <input
516- <input class="field-input" type="text" value=sender.from disabled/>710+ class="field-input"
517- </label>711+ type="text"
518- <p class="panel-lede">712+ name="from_address"
519- "This whole panel is what the running process was configured with. It is read here and changed where it is set — DIZEY_SMTP_HOST, DIZEY_SMTP_PORT, DIZEY_SMTP_USERNAME, DIZEY_SMTP_PASSWORD and DIZEY_MAIL_FROM — followed by a restart."713+ value=sender.from_address
520- </p>714+ placeholder="board@dizey.sh"
521- </div>715+ />
522- </section>716+ </label>
523- }717+ </div>
524-}718+ <div class="panel-foot">
525-719+ <button class="button button-primary" type="submit">"Save"</button>
526-/// An admin on a workspace with no sender. Nothing is broken; nothing is sent.720+ <Show when=saved>
527-#[component]721+ <span class="field-note">"Saved."</span>
528-fn NoSenderPanel() -> impl IntoView {722+ </Show>
529- view! {723+ <Show when=move || refusal().is_some()>
530- <section class="panel">724+ <span class="field-refusal">{move || refusal()}</span>
531- <div class="panel-head">725+ </Show>
532- <h2 class="panel-title">"Outgoing mail"</h2>726+ </div>
533- <span class="chip chip-admin">"Admin only"</span>727+ </ActionForm>
534- <span class="chip chip-off">"Not configured"</span>
535- </div>
536- <div class="panel-body">
537- <p class="panel-lede">
538- "No sender is configured, so Dizey sends nothing. Cards still move and rules can still be written — what they owe is kept and goes out once a sender exists."
539- </p>
540- <p class="panel-lede">
541- "Set DIZEY_SMTP_HOST, DIZEY_SMTP_PORT, DIZEY_SMTP_USERNAME, DIZEY_SMTP_PASSWORD and DIZEY_MAIL_FROM — all five or none — and restart Dizey."
542- </p>
543 </div>728 </div>
544 </section>729 </section>
545 }730 }
crates/dizey-web/src/smtp.rsmodified+122 -7
@@ -6,18 +6,39 @@
6 //! engine testable — the tests hand it a mailer that remembers instead of6 //! engine testable — the tests hand it a mailer that remembers instead of
7 //! connecting.7 //! connecting.
8 //!8 //!
9-//! The credentials come from the environment through `Config`, never from a9+//! The credentials come from the workspace's own settings, written by an admin
10-//! literal in here, and the password is not in anything this module logs or10+//! on the Settings screen. They are never in a literal in here, and the
11-//! puts in an error message: a refusal that quoted the password would put it11+//! password is not in anything this module logs or puts in an error message: a
12-//! in the ledger, where an admin screen would later print it.12+//! refusal that quoted the password would put it in the ledger, where an admin
13+//! screen would later print it.
14+//!
15+//! Because the sender is editable while the process runs, the transport cannot
16+//! be built once at boot. [`WorkspaceSmtp`] holds the last one it built and the
17+//! settings it was built from; a send whose settings still match reuses the
18+//! connection pool, and a send after an edit builds a new one and drops the old.
19+
20+use std::sync::Arc;
13 21
14-use dizey_core::config::MailConfig;22+use dizey_core::store::Store;
15 use dizey_core::mail::{MailError, Mailer, Outgoing};23 use dizey_core::mail::{MailError, Mailer, Outgoing};
16 use lettre::message::header::ContentType;24 use lettre::message::header::ContentType;
17 use lettre::transport::smtp::authentication::Credentials;25 use lettre::transport::smtp::authentication::Credentials;
18 use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};26 use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};
19 27
20-/// A sender holding one connection pool for the life of the process.28+/// The sender as the mailer needs it: what the admin typed, password included.
29+/// It exists only inside this module and inside the store; nothing that can
30+/// reach a response body holds one.
31+#[derive(Clone, PartialEq, Eq)]
32+pub struct Sending {
33+ pub host: String,
34+ pub port: u16,
35+ pub username: String,
36+ pub password: String,
37+ /// `Name <address>` if a name was given, the bare address otherwise.
38+ pub from: String,
39+}
40+
41+/// A sender holding one connection pool.
21 pub struct Smtp {42 pub struct Smtp {
22 transport: AsyncSmtpTransport<Tokio1Executor>,43 transport: AsyncSmtpTransport<Tokio1Executor>,
23 from: String,44 from: String,
@@ -27,7 +48,7 @@ impl Smtp {
27 /// Builds the transport. Fails only on a host name TLS cannot be set up48 /// Builds the transport. Fails only on a host name TLS cannot be set up
28 /// against — a server that is merely unreachable is discovered per send,49 /// against — a server that is merely unreachable is discovered per send,
29 /// as a retryable refusal, which is the honest place for it.50 /// as a retryable refusal, which is the honest place for it.
30- pub fn new(mail: &MailConfig) -> Result<Self, String> {51+ pub fn new(mail: &Sending) -> Result<Self, String> {
31 // 465 is submissions, where TLS is up before the greeting. Everything52 // 465 is submissions, where TLS is up before the greeting. Everything
32 // else — 587 above all — is submission, where the session starts in53 // else — 587 above all — is submission, where the session starts in
33 // the clear and is upgraded. Both are encrypted before the password54 // the clear and is upgraded. Both are encrypted before the password
@@ -88,3 +109,97 @@ impl Mailer for Smtp {
88 })109 })
89 }110 }
90 }111 }
112+
113+/// The mailer the engine actually holds: it reads the workspace's sender at
114+/// send time, so an admin who fixes a typo in the host does not have to restart
115+/// anything for the next mail to go out.
116+pub struct WorkspaceSmtp {
117+ store: Arc<dyn Store>,
118+ /// The live transport and the settings it was built from. Rebuilt only when
119+ /// those settings change — building one per send would throw away the
120+ /// connection pool that makes a backlog drain quickly.
121+ current: tokio::sync::Mutex<Option<(Sending, Arc<Smtp>)>>,
122+}
123+
124+impl WorkspaceSmtp {
125+ pub fn new(store: Arc<dyn Store>) -> Self {
126+ Self {
127+ store,
128+ current: tokio::sync::Mutex::new(None),
129+ }
130+ }
131+
132+ /// The sender as it stands right now, or `None` while the panel is empty.
133+ ///
134+ /// A half-filled sender counts as none. The screen will not save one, but
135+ /// the check is here too, because this is the side that would otherwise
136+ /// hand lettre an empty host and turn a missing setting into a stack of
137+ /// refusals in the ledger.
138+ async fn sending(&self) -> Result<Option<Sending>, MailError> {
139+ let store = &self.store;
140+ let workspace = store
141+ .workspace()
142+ .await
143+ .map_err(|e| MailError::retryable(e.to_string()))?;
144+ let Some(ws) = workspace else {
145+ return Ok(None);
146+ };
147+ let (Some(host), Some(port), Some(username), Some(address)) = (
148+ ws.smtp_host.clone(),
149+ ws.smtp_port,
150+ ws.smtp_username.clone(),
151+ ws.smtp_from_address.clone(),
152+ ) else {
153+ return Ok(None);
154+ };
155+ let password = store
156+ .smtp_password(&ws.id)
157+ .await
158+ .map_err(|e| MailError::retryable(e.to_string()))?;
159+ let (Some(password), Ok(port)) = (password, u16::try_from(port)) else {
160+ return Ok(None);
161+ };
162+ if host.trim().is_empty() || username.trim().is_empty() || password.is_empty() {
163+ return Ok(None);
164+ }
165+ let from = match ws.smtp_from_name.as_deref().map(str::trim) {
166+ Some(name) if !name.is_empty() => format!("{name} <{address}>"),
167+ _ => address,
168+ };
169+ Ok(Some(Sending {
170+ host,
171+ port,
172+ username,
173+ password,
174+ from,
175+ }))
176+ }
177+
178+ /// The transport for the current settings, building a new one only when
179+ /// they have changed since the last send.
180+ async fn transport(&self, want: &Sending) -> Result<Arc<Smtp>, MailError> {
181+ let mut current = self.current.lock().await;
182+ if let Some((held, smtp)) = current.as_ref()
183+ && held == want
184+ {
185+ return Ok(smtp.clone());
186+ }
187+ let built = Arc::new(Smtp::new(want).map_err(MailError::retryable)?);
188+ *current = Some((want.clone(), built.clone()));
189+ Ok(built)
190+ }
191+}
192+
193+#[async_trait::async_trait]
194+impl Mailer for WorkspaceSmtp {
195+ async fn send(&self, mail: &Outgoing) -> Result<(), MailError> {
196+ let Some(want) = self.sending().await? else {
197+ // Not a failure, and pointedly not an attempt: the mail is owed
198+ // until somebody fills the sender in.
199+ return Err(MailError::unsent(
200+ "no sender is configured, so this is waiting rather than failing",
201+ ));
202+ };
203+ self.transport(&want).await?.send(mail).await
204+ }
205+}
crates/dizey-web/tests/http.rsmodified+226 -34
@@ -32,22 +32,6 @@ struct App {
32 32
33 impl App {33 impl App {
34 async fn open() -> Self {34 async fn open() -> Self {
35- Self::open_with(None).await
36- }
37-
38- /// The same app, started the way a deployment with a sender configured
39- /// starts it. The password is not among what the router is given.
40- async fn with_sender() -> Self {
41- Self::open_with(Some(dizey_web::settings::Sender {
42- host: "smtp.fastmail.com".to_string(),
43- port: 465,
44- username: "dizey".to_string(),
45- from: "dizey@dizey.sh".to_string(),
46- }))
47- .await
48- }
49-
50- async fn open_with(sender: Option<dizey_web::settings::Sender>) -> Self {
51 let dir = std::env::temp_dir().join(format!("dizey-http-{}", Uuid::new_v4()));35 let dir = std::env::temp_dir().join(format!("dizey-http-{}", Uuid::new_v4()));
52 std::fs::create_dir_all(&dir).unwrap();36 std::fs::create_dir_all(&dir).unwrap();
53 let store = TursoStore::open(dir.join("dizey.db").to_str().unwrap())37 let store = TursoStore::open(dir.join("dizey.db").to_str().unwrap())
@@ -57,7 +41,6 @@ impl App {
57 let router = dizey_web::server::router(41 let router = dizey_web::server::router(
58 Accounts::new(Arc::new(store)),42 Accounts::new(Arc::new(store)),
59 dizey_web::server::Mail::silent(),43 dizey_web::server::Mail::silent(),
60- sender,
61 options,44 options,
62 );45 );
63 Self { dir, router }46 Self { dir, router }
@@ -203,6 +186,29 @@ fn path<F: ServerFn>() -> &'static str {
203 F::PATH186 F::PATH
204 }187 }
205 188
189+/// What the tests type into the password field. It must never come back out.
190+const SENDER_PASSWORD: &str = "cavalry-battery-hinge-40";
191+
192+/// Fills in the sender panel the way an admin would, and reports whether the
193+/// server accepted it.
194+async fn sender_saved(app: &App, admin: &str) -> bool {
195+ let answer = app
196+ .post(
197+ path::<dizey_web::settings::SaveSender>(),
198+ Some(admin),
199+ &[
200+ ("host", "smtp.fastmail.com"),
201+ ("port", "465"),
202+ ("username", "dizey"),
203+ ("password", SENDER_PASSWORD),
204+ ("from_name", "Dizey"),
205+ ("from_address", "dizey@dizey.sh"),
206+ ],
207+ )
208+ .await;
209+ answer.status == StatusCode::OK && answer.body == "null"
210+}
211+
206 /// Claims the workspace and returns the admin's session cookie.212 /// Claims the workspace and returns the admin's session cookie.
207 async fn admin(app: &App) -> String {213 async fn admin(app: &App) -> String {
208 let answer = app214 let answer = app
@@ -837,8 +843,9 @@ async fn a_card_cannot_be_moved_into_another_boards_column() {
837 843
838 #[tokio::test]844 #[tokio::test]
839 async fn a_signed_out_browser_is_told_nothing_by_the_settings_call() {845 async fn a_signed_out_browser_is_told_nothing_by_the_settings_call() {
840- let app = App::with_sender().await;846+ let app = App::open().await;
841- let _ = admin(&app).await;847+ let admin_cookie = admin(&app).await;
848+ assert!(sender_saved(&app, &admin_cookie).await);
842 849
843 let answer = app850 let answer = app
844 .post(path::<dizey_web::settings::CurrentSettings>(), None, &[])851 .post(path::<dizey_web::settings::CurrentSettings>(), None, &[])
@@ -854,16 +861,10 @@ async fn a_signed_out_browser_is_told_nothing_by_the_settings_call() {
854 /// rather than a hidden panel whose contents rode along in the body.861 /// rather than a hidden panel whose contents rode along in the body.
855 #[tokio::test]862 #[tokio::test]
856 async fn a_member_is_told_nothing_about_the_sender() {863 async fn a_member_is_told_nothing_about_the_sender() {
857- let app = App::with_sender().await;864+ let app = App::open().await;
858 let admin_cookie = admin(&app).await;865 let admin_cookie = admin(&app).await;
859- let member = invited(866+ assert!(sender_saved(&app, &admin_cookie).await);
860- &app,867+ let member = invited(&app, &admin_cookie, "emre@dizey.sh", "Emre", Role::Member).await;
861- &admin_cookie,
862- "emre@dizey.sh",
863- "Emre",
864- Role::Member,
865- )
866- .await;
867 868
868 let answer = app869 let answer = app
869 .post(870 .post(
@@ -879,12 +880,13 @@ async fn a_member_is_told_nothing_about_the_sender() {
879 assert!(!answer.body.contains("fastmail"), "{}", answer.body);880 assert!(!answer.body.contains("fastmail"), "{}", answer.body);
880 }881 }
881 882
882-/// The admin sees what the process is configured with — and the password is883+/// The admin sees the sender they typed — and never the password, which the
883-/// not part of "what": it is never held anywhere this call can reach.884+/// answer carries as a boolean and cannot carry as anything else.
884 #[tokio::test]885 #[tokio::test]
885 async fn an_admin_sees_the_sender_and_never_a_password() {886 async fn an_admin_sees_the_sender_and_never_a_password() {
886- let app = App::with_sender().await;887+ let app = App::open().await;
887 let admin_cookie = admin(&app).await;888 let admin_cookie = admin(&app).await;
889+ assert!(sender_saved(&app, &admin_cookie).await);
888 890
889 let answer = app891 let answer = app
890 .post(892 .post(
@@ -895,16 +897,206 @@ async fn an_admin_sees_the_sender_and_never_a_password() {
895 .await;897 .await;
896 898
897 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);899 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
898- // The whole of what a screen may know about the sender, exactly: four
899- // fields, and no fifth one a password could be carried in.
900 assert!(900 assert!(
901 answer.body.contains(901 answer.body.contains(
902 "\"sender\":{\"host\":\"smtp.fastmail.com\",\"port\":465,\902 "\"sender\":{\"host\":\"smtp.fastmail.com\",\"port\":465,\
903- \"username\":\"dizey\",\"from\":\"dizey@dizey.sh\"}"903+ \"username\":\"dizey\",\"from_name\":\"Dizey\",\
904+ \"from_address\":\"dizey@dizey.sh\",\"password_set\":true}"
904 ),905 ),
905 "{}",906 "{}",
906 answer.body907 answer.body
907 );908 );
909+ assert!(
910+ !answer.body.contains(SENDER_PASSWORD),
911+ "the settings answer carried the SMTP password: {}",
912+ answer.body
913+ );
914+}
915+
916+/// A Member cannot write the sender either. The panel they never received is a
917+/// courtesy; this is the guard, and it is in the handler.
918+#[tokio::test]
919+async fn only_an_admin_may_write_the_sender() {
920+ let app = App::open().await;
921+ let admin_cookie = admin(&app).await;
922+ let member = invited(&app, &admin_cookie, "emre@dizey.sh", "Emre", Role::Member).await;
923+
924+ let answer = app
925+ .post(
926+ path::<dizey_web::settings::SaveSender>(),
927+ Some(&member),
928+ &[
929+ ("host", "smtp.attacker.example"),
930+ ("port", "587"),
931+ ("username", "emre"),
932+ ("password", "let-me-in"),
933+ ("from_name", "Dizey"),
934+ ("from_address", "emre@dizey.sh"),
935+ ],
936+ )
937+ .await;
938+
939+ assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
940+ assert!(answer.body.contains("Forbidden"), "{}", answer.body);
941+
942+ // And nothing was written: the admin's own view still shows no sender.
943+ let seen = app
944+ .post(
945+ path::<dizey_web::settings::CurrentSettings>(),
946+ Some(&admin_cookie),
947+ &[],
948+ )
949+ .await;
950+ assert!(!seen.body.contains("attacker"), "{}", seen.body);
951+}
952+
953+/// A signed-out browser gets the same refusal, and writes nothing.
954+#[tokio::test]
955+async fn a_signed_out_browser_may_not_write_the_sender() {
956+ let app = App::open().await;
957+ let admin_cookie = admin(&app).await;
958+
959+ let answer = app
960+ .post(
961+ path::<dizey_web::settings::SaveSender>(),
962+ None,
963+ &[
964+ ("host", "smtp.attacker.example"),
965+ ("port", "587"),
966+ ("username", "nobody"),
967+ ("password", "let-me-in"),
968+ ("from_name", "Dizey"),
969+ ("from_address", "nobody@dizey.sh"),
970+ ],
971+ )
972+ .await;
973+
974+ assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
975+ assert!(answer.body.contains("SignInFirst"), "{}", answer.body);
976+
977+ let seen = app
978+ .post(
979+ path::<dizey_web::settings::CurrentSettings>(),
980+ Some(&admin_cookie),
981+ &[],
982+ )
983+ .await;
984+ assert!(!seen.body.contains("attacker"), "{}", seen.body);
985+}
986+
987+/// The password field is write-only, so the form has nothing to send back for
988+/// a password that already exists. An edit with the field left empty must keep
989+/// the stored password rather than reading the blank as a deletion — otherwise
990+/// correcting a port silently stops the workspace sending mail.
991+#[tokio::test]
992+async fn an_edit_with_no_password_typed_keeps_the_stored_one() {
993+ let app = App::open().await;
994+ let admin_cookie = admin(&app).await;
995+ assert!(sender_saved(&app, &admin_cookie).await);
996+
997+ let answer = app
998+ .post(
999+ path::<dizey_web::settings::SaveSender>(),
1000+ Some(&admin_cookie),
1001+ &[
1002+ ("host", "smtp.fastmail.com"),
1003+ ("port", "587"),
1004+ ("username", "dizey"),
1005+ ("password", ""),
1006+ ("from_name", "Dizey"),
1007+ ("from_address", "dizey@dizey.sh"),
1008+ ],
1009+ )
1010+ .await;
1011+ assert_eq!(answer.body, "null", "{}", answer.body);
1012+
1013+ let seen = app
1014+ .post(
1015+ path::<dizey_web::settings::CurrentSettings>(),
1016+ Some(&admin_cookie),
1017+ &[],
1018+ )
1019+ .await;
1020+ assert!(seen.body.contains("\"port\":587"), "the edit did not land: {}", seen.body);
1021+ assert!(
1022+ seen.body.contains("\"password_set\":true"),
1023+ "an empty field blanked the password: {}",
1024+ seen.body
1025+ );
1026+}
1027+
1028+/// The first save has to carry one, though. A sender with no password is a
1029+/// sender that cannot sign in, and storing it would turn a form somebody can
1030+/// fix into a queue of refusals they have to read the ledger to find.
1031+#[tokio::test]
1032+async fn a_first_sender_with_no_password_is_refused_and_says_why() {
1033+ let app = App::open().await;
1034+ let admin_cookie = admin(&app).await;
1035+
1036+ let answer = app
1037+ .post(
1038+ path::<dizey_web::settings::SaveSender>(),
1039+ Some(&admin_cookie),
1040+ &[
1041+ ("host", "smtp.fastmail.com"),
1042+ ("port", "587"),
1043+ ("username", "dizey"),
1044+ ("password", ""),
1045+ ("from_name", "Dizey"),
1046+ ("from_address", "dizey@dizey.sh"),
1047+ ],
1048+ )
1049+ .await;
1050+
1051+ assert!(answer.body.contains("BadSender"), "{}", answer.body);
1052+ assert!(answer.body.contains("password"), "{}", answer.body);
1053+}
1054+
1055+/// Each field the sender cannot work without is refused by name. A form that
1056+/// answers "that did not work" sends somebody round the panel guessing.
1057+#[tokio::test]
1058+async fn a_sender_field_that_cannot_work_is_refused_by_name() {
1059+ let app = App::open().await;
1060+ let admin_cookie = admin(&app).await;
1061+
1062+ let bad: &[(&str, &[(&str, &str)])] = &[
1063+ ("host", &[("host", " ")]),
1064+ ("host", &[("host", "smtp.fastmail.com/inbox")]),
1065+ ("port", &[("port", "0")]),
1066+ ("port", &[("port", "99999")]),
1067+ ("username", &[("username", "")]),
1068+ ("from_address", &[("from_address", "board-at-dizey")]),
1069+ ("from_address", &[("from_address", "board@dizey")]),
1070+ ];
1071+ for (field, overrides) in bad {
1072+ let mut form: Vec<(&str, &str)> = vec![
1073+ ("host", "smtp.fastmail.com"),
1074+ ("port", "587"),
1075+ ("username", "dizey"),
1076+ ("password", SENDER_PASSWORD),
1077+ ("from_name", "Dizey"),
1078+ ("from_address", "dizey@dizey.sh"),
1079+ ];
1080+ for (key, value) in *overrides {
1081+ for slot in form.iter_mut() {
1082+ if slot.0 == *key {
1083+ slot.1 = value;
1084+ }
1085+ }
1086+ }
1087+ let answer = app
1088+ .post(
1089+ path::<dizey_web::settings::SaveSender>(),
1090+ Some(&admin_cookie),
1091+ &form,
1092+ )
1093+ .await;
1094+ assert!(
1095+ answer.body.contains("BadSender"),
1096+ "{field} was accepted with {overrides:?}: {}",
1097+ answer.body
1098+ );
1099+ }
908 }1100 }
909 1101
910 /// The form carries a name and nothing else. Who is renamed comes from the1102 /// The form carries a name and nothing else. Who is renamed comes from the