diff --git a/crates/dizey-core/src/config.rs b/crates/dizey-core/src/config.rs index f5b0ed7..031ef96 100644 --- a/crates/dizey-core/src/config.rs +++ b/crates/dizey-core/src/config.rs @@ -14,34 +14,17 @@ //! //! Whatever is finally resolved is printed once at startup — the database path //! absolute, the base URL as it will appear in mail — so "which file are we -//! on" is answered by the log rather than by someone's memory. Passwords are -//! never among the things printed. +//! on" is answered by the log rather than by someone's memory. +//! +//! The sender is not here. Host, port, username, password and from-address are +//! workspace settings an admin writes on the Settings screen, so that changing +//! where mail goes out through does not need a shell on the box and a restart. use std::fmt; use std::path::{Path, PathBuf}; /// Every variable the app reads, in the order the report prints them. -pub const VARIABLES: &[&str] = &[ - "DIZEY_DEV", - "DIZEY_DATABASE", - "DIZEY_BASE_URL", - "DIZEY_SMTP_HOST", - "DIZEY_SMTP_PORT", - "DIZEY_SMTP_USERNAME", - "DIZEY_SMTP_PASSWORD", - "DIZEY_MAIL_FROM", -]; - -/// The five variables that carry a sender. They are all-or-nothing: a host -/// without a from-address is not a half-configured sender, it is a mistake -/// that would be discovered by a mail that never arrives. -const MAIL_VARIABLES: &[&str] = &[ - "DIZEY_SMTP_HOST", - "DIZEY_SMTP_PORT", - "DIZEY_SMTP_USERNAME", - "DIZEY_SMTP_PASSWORD", - "DIZEY_MAIL_FROM", -]; +pub const VARIABLES: &[&str] = &["DIZEY_DEV", "DIZEY_DATABASE", "DIZEY_BASE_URL"]; /// What the process needs to know before it opens a socket. #[derive(Clone, Debug, PartialEq, Eq)] @@ -50,35 +33,10 @@ pub struct Config { pub database: PathBuf, /// The origin links in mail point at, with no trailing slash. pub base_url: String, - /// The sender, if one is configured. Mail stays quiet without it. - pub mail: Option, /// Whether the development defaults were taken. pub dev: bool, } -/// Where mail goes out through. The password is in here and stays out of every -/// rendering of it. -#[derive(Clone, PartialEq, Eq)] -pub struct MailConfig { - pub host: String, - pub port: u16, - pub username: String, - pub password: String, - pub from: String, -} - -impl fmt::Debug for MailConfig { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("MailConfig") - .field("host", &self.host) - .field("port", &self.port) - .field("username", &self.username) - .field("password", &"…") - .field("from", &self.from) - .finish() - } -} - /// Why the process is not starting. #[derive(Clone, Debug, PartialEq, Eq)] pub enum ConfigError { @@ -86,11 +44,6 @@ pub enum ConfigError { Missing(Vec<&'static str>), /// A variable is set to something the app cannot use. Invalid { variable: &'static str, why: String }, - /// Some of the sender's variables are set and some are not. - PartialMail { - set: Vec<&'static str>, - missing: Vec<&'static str>, - }, } impl fmt::Display for ConfigError { @@ -116,13 +69,6 @@ impl fmt::Display for ConfigError { "not starting: {variable} is set to something unusable — {why}" ) } - ConfigError::PartialMail { set, missing } => write!( - f, - "not starting: a mail sender is half configured — {} set, {} missing. \ - Set all five or none; with none, Dizey sends nothing and says so.", - set.join(", "), - missing.join(", ") - ), } } } @@ -169,12 +115,9 @@ impl Config { } let base_url = base_url.trim_end_matches('/').to_string(); - let mail = mail_from(&value)?; - Ok(Config { database: absolute(Path::new(&database.expect("checked above"))), base_url, - mail, dev, }) } @@ -185,13 +128,7 @@ impl Config { format!("database {}", self.database.display()), format!("base url {}", self.base_url), ]; - lines.push(match &self.mail { - Some(mail) => format!( - "mail {} via {}:{} as {}", - mail.from, mail.host, mail.port, mail.username - ), - None => "mail no sender configured — Dizey sends nothing".to_string(), - }); + lines.push("mail the sender is in Settings, not here".to_string()); if self.dev { lines.push("dev DIZEY_DEV=1, development defaults taken".to_string()); } @@ -199,55 +136,6 @@ impl Config { } } -fn mail_from(value: &impl Fn(&str) -> Option) -> Result, ConfigError> { - let read: Vec<(&'static str, Option)> = MAIL_VARIABLES - .iter() - .map(|name| (*name, value(name))) - .collect(); - let set: Vec<&'static str> = read - .iter() - .filter(|(_, held)| held.is_some()) - .map(|(name, _)| *name) - .collect(); - if set.is_empty() { - return Ok(None); - } - let missing: Vec<&'static str> = read - .iter() - .filter(|(_, held)| held.is_none()) - .map(|(name, _)| *name) - .collect(); - if !missing.is_empty() { - return Err(ConfigError::PartialMail { set, missing }); - } - - let held = |name: &str| { - read.iter() - .find(|(candidate, _)| *candidate == name) - .and_then(|(_, held)| held.clone()) - .expect("all five are set") - }; - let raw_port = held("DIZEY_SMTP_PORT"); - let port = raw_port.parse::().map_err(|_| ConfigError::Invalid { - variable: "DIZEY_SMTP_PORT", - why: format!("{raw_port:?} is not a port number"), - })?; - let from = held("DIZEY_MAIL_FROM"); - if !from.contains('@') { - return Err(ConfigError::Invalid { - variable: "DIZEY_MAIL_FROM", - why: format!("{from:?} is not an address"), - }); - } - - Ok(Some(MailConfig { - host: held("DIZEY_SMTP_HOST"), - port, - username: held("DIZEY_SMTP_USERNAME"), - password: held("DIZEY_SMTP_PASSWORD"), - from, - })) -} /// An absolute path for a file that may not exist yet: the directory is /// resolved, the file name is kept as written. @@ -309,7 +197,6 @@ mod tests { assert!(config.database.is_absolute(), "{:?}", config.database); assert!(config.database.ends_with("dizey.db")); assert_eq!(config.base_url, "http://127.0.0.1:3000"); - assert!(config.mail.is_none()); } #[test] @@ -357,49 +244,13 @@ mod tests { assert_eq!(config.base_url, "https://dizey.sh"); } + /// The sender used to be five environment variables. It is workspace + /// settings now, so a stale `DIZEY_SMTP_PASSWORD` left in a unit file or a + /// shell must do nothing at all — not half-configure a sender, not stop the + /// boot, and above all not quietly send through an account the Settings + /// screen does not show. #[test] - fn no_sender_is_a_configuration_not_an_error() { - let config = Config::read(env(&[ - ("DIZEY_DATABASE", "/srv/dizey.db"), - ("DIZEY_BASE_URL", "https://dizey.sh"), - ])) - .unwrap(); - assert!(config.mail.is_none()); - assert!( - config - .report() - .iter() - .any(|line| line.contains("no sender configured")), - "{:?}", - config.report() - ); - } - - #[test] - fn half_a_sender_stops_the_boot_and_names_both_halves() { - let problem = Config::read(env(&[ - ("DIZEY_DATABASE", "/srv/dizey.db"), - ("DIZEY_BASE_URL", "https://dizey.sh"), - ("DIZEY_SMTP_HOST", "smtp.example.net"), - ("DIZEY_SMTP_PORT", "587"), - ])) - .unwrap_err(); - let ConfigError::PartialMail { set, missing } = &problem else { - panic!("expected the half-configured sender, got {problem:?}"); - }; - assert_eq!(set, &["DIZEY_SMTP_HOST", "DIZEY_SMTP_PORT"]); - assert_eq!( - missing, - &[ - "DIZEY_SMTP_USERNAME", - "DIZEY_SMTP_PASSWORD", - "DIZEY_MAIL_FROM" - ] - ); - } - - #[test] - fn a_whole_sender_is_read_and_its_password_is_never_printed() { + fn leftover_sender_variables_are_ignored_entirely() { let config = Config::read(env(&[ ("DIZEY_DATABASE", "/srv/dizey.db"), ("DIZEY_BASE_URL", "https://dizey.sh"), @@ -409,71 +260,22 @@ mod tests { ("DIZEY_SMTP_PASSWORD", "hunter2-and-then-some"), ("DIZEY_MAIL_FROM", "board@dizey.sh"), ])) - .unwrap(); - let mail = config.mail.clone().expect("a sender"); - assert_eq!(mail.port, 587); - assert_eq!(mail.from, "board@dizey.sh"); + .expect("a stale sender in the environment is not an error"); let report = config.report().join("\n"); - assert!(report.contains("board@dizey.sh"), "{report}"); - assert!(!report.contains("hunter2-and-then-some"), "{report}"); - let debugged = format!("{mail:?}"); - assert!(!debugged.contains("hunter2-and-then-some"), "{debugged}"); - } - - #[test] - fn a_port_that_is_not_a_port_stops_the_boot() { - let problem = Config::read(env(&[ - ("DIZEY_DATABASE", "/srv/dizey.db"), - ("DIZEY_BASE_URL", "https://dizey.sh"), - ("DIZEY_SMTP_HOST", "smtp.example.net"), - ("DIZEY_SMTP_PORT", "not-a-port"), - ("DIZEY_SMTP_USERNAME", "dizey"), - ("DIZEY_SMTP_PASSWORD", "secret"), - ("DIZEY_MAIL_FROM", "board@dizey.sh"), - ])) - .unwrap_err(); assert!( - matches!( - problem, - ConfigError::Invalid { - variable: "DIZEY_SMTP_PORT", - .. - } - ), - "{problem:?}" + !report.contains("hunter2-and-then-some") && !report.contains("smtp.example.net"), + "the report read a variable it no longer honours: {report}" ); - } - - #[test] - fn a_from_address_without_an_at_sign_stops_the_boot() { - let problem = Config::read(env(&[ - ("DIZEY_DATABASE", "/srv/dizey.db"), - ("DIZEY_BASE_URL", "https://dizey.sh"), - ("DIZEY_SMTP_HOST", "smtp.example.net"), - ("DIZEY_SMTP_PORT", "587"), - ("DIZEY_SMTP_USERNAME", "dizey"), - ("DIZEY_SMTP_PASSWORD", "secret"), - ("DIZEY_MAIL_FROM", "board-at-dizey"), - ])) - .unwrap_err(); assert!( - matches!( - problem, - ConfigError::Invalid { - variable: "DIZEY_MAIL_FROM", - .. - } - ), - "{problem:?}" + report.contains("the sender is in Settings"), + "the report should say where the sender lives: {report}" ); } #[test] fn every_variable_the_app_reads_is_named_in_one_list() { - for name in MAIL_VARIABLES { - assert!(VARIABLES.contains(name), "{name} is missing from VARIABLES"); - } + assert_eq!(VARIABLES.len(), 3, "a variable was added without a line here"); assert!(VARIABLES.contains(&"DIZEY_DEV")); assert!(VARIABLES.contains(&"DIZEY_DATABASE")); assert!(VARIABLES.contains(&"DIZEY_BASE_URL")); diff --git a/crates/dizey-core/src/mail.rs b/crates/dizey-core/src/mail.rs index 701510a..0a3e714 100644 --- a/crates/dizey-core/src/mail.rs +++ b/crates/dizey-core/src/mail.rs @@ -34,6 +34,11 @@ pub struct MailError { /// A timeout or a host that is down may work in a minute. A refused /// address will not, and retrying it forever is noise nobody reads. pub retryable: bool, + /// Whether a mail server was actually asked. `false` means the mail never + /// left the building — there is no sender configured yet — and that must + /// not spend one of the five attempts, or a workspace whose admin sets the + /// sender up tomorrow finds that today's mail was given up on overnight. + pub attempted: bool, } impl MailError { @@ -41,6 +46,7 @@ impl MailError { Self { message: message.into(), retryable: true, + attempted: true, } } @@ -48,6 +54,18 @@ impl MailError { Self { message: message.into(), retryable: false, + attempted: true, + } + } + + /// Nothing was sent and nothing was asked: the workspace has no sender. + /// The mail stays owed, at no cost to its attempts, and goes out when a + /// sender exists — which is exactly what the empty-sender panel promises. + pub fn unsent(message: impl Into) -> Self { + Self { + message: message.into(), + retryable: true, + attempted: false, } } } @@ -71,6 +89,11 @@ pub trait Mailer: Send + Sync { /// written down as abandoned. pub const MAX_ATTEMPTS: u32 = 5; +/// How long a mail with no sender waits before it is looked at again. Short, +/// because the thing it waits on is an admin finishing a form and then watching +/// to see whether mail starts moving. +pub const HOLD: Duration = Duration::minutes(1); + /// The wait before the next attempt, doubling and capped: five minutes, ten, /// twenty, forty, an hour. pub fn backoff(attempts: u32) -> Duration { @@ -89,6 +112,9 @@ pub struct Report { pub failed: u32, /// Refusals that will not. pub abandoned: u32, + /// Mails held back because there is no sender to send them through. Owed, + /// not failed: no attempt was spent and none will be until one exists. + pub held: u32, } pub struct Engine { @@ -284,6 +310,15 @@ impl Engine { self.store.record_send_accepted(&send.id, now).await?; report.sent += 1; } + Err(problem) if !problem.attempted => { + // No sender. The mail keeps its place in the ledger and its + // attempts, and is looked at again on the next sweep — by then + // an admin may have filled the panel in. + self.store + .defer_send(&send.id, &problem.message, now + HOLD, now) + .await?; + report.held += 1; + } Err(problem) => { let attempts = send.attempts + 1; // The last attempt is written down as given up on rather than diff --git a/crates/dizey-core/src/store/mod.rs b/crates/dizey-core/src/store/mod.rs index 5d074cd..d7dc785 100644 --- a/crates/dizey-core/src/store/mod.rs +++ b/crates/dizey-core/src/store/mod.rs @@ -605,6 +605,18 @@ pub trait Store: BoardReads + DetailReads + 'static { at: OffsetDateTime, ) -> Result<()>; + /// Holds a send that was never attempted, because the workspace has no + /// sender. The reason is written down like any refusal so the ledger does + /// not go quiet, but `attempts` is left alone: nothing was spent, so + /// nothing is charged, and the mail is still owed when a sender appears. + async fn defer_send( + &self, + send_id: &str, + reason: &str, + retry_at: OffsetDateTime, + at: OffsetDateTime, + ) -> Result<()>; + /// Sends owed right now: claimed but never accepted, and due. async fn sends_owed(&self, now: OffsetDateTime, limit: u32) -> Result>; diff --git a/crates/dizey-core/src/store/turso_store.rs b/crates/dizey-core/src/store/turso_store.rs index e85c81a..28b65d6 100644 --- a/crates/dizey-core/src/store/turso_store.rs +++ b/crates/dizey-core/src/store/turso_store.rs @@ -1968,6 +1968,32 @@ impl Store for TursoStore { Ok(()) } + async fn defer_send( + &self, + send_id: &str, + reason: &str, + retry_at: OffsetDateTime, + _at: OffsetDateTime, + ) -> Result<()> { + // `attempts` is deliberately not touched. Everything else reads like a + // refusal that will be retried, because that is what it is — the mail + // is owed, it is due again shortly, and the reason says why it waited. + let n = self + .conn + .execute( + "UPDATE mail_send \ + SET state = 'failed', last_error = ?1, next_attempt_at = ?2 \ + WHERE id = ?3", + params![reason, stamp(retry_at)?, send_id], + ) + .await + .map_err(backend)?; + if n == 0 { + return Err(StoreError::NotFound); + } + Ok(()) + } + async fn sends_owed(&self, now: OffsetDateTime, limit: u32) -> Result> { let sql = format!( "SELECT {SEND_COLUMNS} FROM mail_send \ diff --git a/crates/dizey-web/src/auth.rs b/crates/dizey-web/src/auth.rs index 80d614d..72ddd3a 100644 --- a/crates/dizey-web/src/auth.rs +++ b/crates/dizey-web/src/auth.rs @@ -39,6 +39,11 @@ pub enum Refusal { BadLimit, /// Something in the allowed-types list is not a file extension. BadFileType, + /// The sender panel was saved with a field it cannot work without, or with + /// one that is not what it claims to be. The message names the field: this + /// is a form somebody is filling in, not an attacker probing, and "that did + /// not work" would send them round the panel guessing. + BadSender(String), /// A comment with nothing in it. EmptyComment, /// The date field did not hold a date. @@ -78,6 +83,7 @@ impl Refusal { Refusal::BadFileType => { "File types are extensions — png, pdf, zip — separated by commas.".to_string() } + Refusal::BadSender(problem) => problem.clone(), Refusal::EmptyComment => "Write something first.".to_string(), Refusal::BadDeadline => "That is not a date.".to_string(), Refusal::Cycle => "That link would put this task behind itself.".to_string(), @@ -119,6 +125,7 @@ impl Refusal { Refusal::EmptyName => "empty-name", Refusal::BadLimit => "bad-limit", Refusal::BadFileType => "bad-file-type", + Refusal::BadSender(_) => "bad-sender", Refusal::EmptyComment => "empty-comment", Refusal::BadDeadline => "bad-deadline", Refusal::Cycle => "cycle", diff --git a/crates/dizey-web/src/main.rs b/crates/dizey-web/src/main.rs index 60253f3..642b9d5 100644 --- a/crates/dizey-web/src/main.rs +++ b/crates/dizey-web/src/main.rs @@ -32,40 +32,23 @@ async fn main() { let store: Arc = Arc::new(store); let accounts = Accounts::new(store.clone()); - // A workspace without a sender still works: cards move, rules can be - // written, nothing goes out. With one, the engine is built once — it holds - // a connection pool — and two things use it: every committed crossing, and - // the sweep below. - let mail = match &config.mail { - Some(sender) => { - let smtp = dizey_web::smtp::Smtp::new(sender).unwrap_or_else(|problem| { - eprintln!("dizey: {problem}"); - std::process::exit(2); - }); - let engine = Arc::new(dizey_core::MailEngine::new( - store.clone(), - Arc::new(smtp), - config.base_url.clone(), - )); - tokio::spawn(sweep(engine.clone())); - dizey_web::server::Mail::sending(engine) - } - None => dizey_web::server::Mail::silent(), - }; + // The engine is always built, because a sender can appear at any moment: + // an admin fills the panel in and the next sweep sends what was held. It + // holds one connection pool, rebuilt only when the settings behind it + // change, and two things use it — every committed crossing, and the sweep. + let engine = Arc::new(dizey_core::MailEngine::new( + store.clone(), + Arc::new(dizey_web::smtp::WorkspaceSmtp::new(store.clone())), + config.base_url.clone(), + )); + tokio::spawn(sweep(engine.clone())); + let mail = dizey_web::server::Mail::sending(engine); let conf = get_configuration(None).expect("failed to read leptos configuration"); let leptos_options = conf.leptos_options; let addr = leptos_options.site_addr; - // What the settings screen may show of the sender: host, port, username - // and from-address, and nothing else. The password stays in `config.mail` - // where the mailer reads it. - let sender = config - .mail - .as_ref() - .map(dizey_web::settings::Sender::of); - - let app = dizey_web::server::router(accounts, mail, sender, leptos_options); + let app = dizey_web::server::router(accounts, mail, leptos_options); let listener = tokio::net::TcpListener::bind(&addr) .await diff --git a/crates/dizey-web/src/server.rs b/crates/dizey-web/src/server.rs index 13d5bef..0de95e8 100644 --- a/crates/dizey-web/src/server.rs +++ b/crates/dizey-web/src/server.rs @@ -22,17 +22,17 @@ pub fn accounts() -> Accounts { expect_context::() } -/// The mail engine, or the fact that there is nobody to send through. +/// The mail engine, or the fact that there is nobody to hand a crossing to. /// -/// A workspace with no sender configured is a working workspace: cards move, -/// rules can be written, and nothing is mailed. That is a configuration, not a -/// broken deployment, so it is a `None` here rather than an error at the call -/// site of every move. +/// The running server always has an engine: the sender is workspace settings +/// now, so it can appear at any moment and the engine reads it per send. The +/// `None` is for tests, which drive the router without one and assert on the +/// ledger rather than on a mail server. #[derive(Clone)] pub struct Mail(Option>); impl Mail { - /// No sender. Crossings are recorded and nothing goes out. + /// No engine at all. Crossings are recorded and nothing is handed on. pub fn silent() -> Self { Self(None) } @@ -88,7 +88,7 @@ impl Mail { } /// The engine for this request, or a silent one when the router was built -/// without a sender. +/// without an engine at all. pub fn mail() -> Mail { use_context::().unwrap_or_else(Mail::silent) } @@ -229,7 +229,6 @@ impl From for Refusal { pub fn router( accounts: Accounts, mail: Mail, - sender: Option, leptos_options: LeptosOptions, ) -> axum::Router { use axum::Router; @@ -246,13 +245,9 @@ pub fn router( // `leptos_routes_with_context` registers with the same closure. let accounts = accounts.clone(); let mail = mail.clone(); - let sender = sender.clone(); move || { provide_context(accounts.clone()); provide_context(mail.clone()); - // What a settings screen may say about the sender. The - // password is not in it and has no field to be in. - provide_context(sender.clone()); } }, { diff --git a/crates/dizey-web/src/settings.rs b/crates/dizey-web/src/settings.rs index 2d35c9f..a1c1ddd 100644 --- a/crates/dizey-web/src/settings.rs +++ b/crates/dizey-web/src/settings.rs @@ -11,31 +11,47 @@ use serde::{Deserialize, Serialize}; use crate::auth::{Me, Refusal}; -/// The sender the process was started with, as a screen may see it. +/// The sender as the admin's screen may see it. /// /// The password is not a field here and there is no field it could be put in. -/// It lives in `DIZEY_SMTP_PASSWORD`, is read once at boot and is held only by -/// the mailer; the database has no column for it since migration 0006. A -/// sender is all-or-nothing in configuration — five variables or none — so a -/// sender that exists is a sender whose password is set, and that is the whole -/// of what this type can say about it. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +/// The store keeps it in a column the workspace read path never selects, and +/// the only reader is the mailer. What the screen gets instead is +/// `password_set`: enough to say "set" beside the field, and enough to know +/// that a save which sends no password is an edit rather than a deletion. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Sender { pub host: String, pub port: u16, pub username: String, - pub from: String, + pub from_name: String, + pub from_address: String, + pub password_set: bool, +} + +impl Sender { + /// Whether this is a sender at all, or an empty panel waiting to be filled + /// in. Mail waits, rather than fails, until this is true. + pub fn is_connected(&self) -> bool { + !self.host.trim().is_empty() + && !self.username.trim().is_empty() + && !self.from_address.trim().is_empty() + && self.password_set + } } #[cfg(feature = "ssr")] impl Sender { - /// What the screen may see of the sender the process is running with. - pub fn of(config: &dizey_core::config::MailConfig) -> Self { + /// What the screen may see of the workspace's sender. + pub fn of(workspace: &dizey_core::store::Workspace) -> Self { Self { - host: config.host.clone(), - port: config.port, - username: config.username.clone(), - from: config.from.clone(), + host: workspace.smtp_host.clone().unwrap_or_default(), + // 587 is submission with STARTTLS, which is what a new panel should + // suggest rather than making somebody look it up. + port: workspace.smtp_port.and_then(|p| u16::try_from(p).ok()).unwrap_or(587), + username: workspace.smtp_username.clone().unwrap_or_default(), + from_name: workspace.smtp_from_name.clone().unwrap_or_default(), + from_address: workspace.smtp_from_address.clone().unwrap_or_default(), + password_set: workspace.smtp_password_set, } } } @@ -77,10 +93,10 @@ pub struct Member { pub is_owner: bool, } -/// One settings screen's worth of state. `sender` is `None` for two different -/// reasons — no sender configured, or not an admin asking — and neither of -/// them is a reason to send a host name to somebody who may not have it, so -/// the two are one answer here. +/// One settings screen's worth of state. `sender` is `None` for exactly one +/// reason — the person asking does not administer the workspace — and a +/// workspace with no sender yet carries an empty one, which is the panel an +/// admin fills in. Nobody else is told a host name. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SettingsSnapshot { pub me: Me, @@ -121,14 +137,28 @@ pub async fn current_settings() -> Result, Ser }, administers, // Only an admin is told anything about the sender at all. - sender: administers - .then(|| use_context::>().flatten()) - .flatten(), + sender: match administers { + true => Some(sender_now().await?), + false => None, + }, limits, members, })) } +#[cfg(feature = "ssr")] +async fn sender_now() -> Result { + let store = crate::server::accounts().store().clone(); + let workspace = store + .workspace() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + // A workspace that somehow is not there yet reads as an empty panel rather + // than an error: there is nothing to correct and nothing to alarm anyone + // with, and the fields are the same ones either way. + Ok(workspace.as_ref().map(Sender::of).unwrap_or_default()) +} + #[cfg(feature = "ssr")] async fn members_now(asking: &dizey_core::store::User) -> Result, ServerFnError> { let store = crate::server::accounts().store().clone(); @@ -237,6 +267,106 @@ pub async fn save_limits( } } +/// Writes the workspace's sender. Admin-only, checked here. +/// +/// `password` is empty when the admin did not type one, and empty means "leave +/// the stored one alone" rather than "delete it": the field is write-only, so +/// the form has nothing to send back for a password that already exists, and a +/// save that took the blank literally would stop the workspace sending mail as +/// a side effect of fixing a typo in the port. +/// +/// A sender with no password at all is refused rather than stored, because a +/// half-filled sender is not a configuration — it is a mail nobody receives and +/// a ledger nobody reads. +#[server] +pub async fn save_sender( + host: String, + port: u32, + username: String, + password: String, + from_name: String, + from_address: String, +) -> Result, ServerFnError> { + use crate::server::{accounts, require_admin}; + use dizey_core::store::NewSender; + + let admin = match require_admin().await { + Ok(admin) => admin, + Err(refusal) => return Ok(Some(refusal)), + }; + + let host = host.trim().to_string(); + let username = username.trim().to_string(); + let from_name = from_name.trim().to_string(); + let from_address = from_address.trim().to_string(); + // Not typed is not the same as blanked. Nothing here can clear a stored + // password; replacing it means typing a new one. + let password = (!password.is_empty()).then_some(password); + + let store = accounts().store().clone(); + let known = store + .workspace() + .await + .map_err(|e| ServerFnError::new(e.to_string()))? + .map(|ws| ws.smtp_password_set) + .unwrap_or(false); + + let complaint = if host.is_empty() { + Some("The SMTP host is the server your mail goes out through — smtp.fastmail.com, for instance.") + } else if host.contains(char::is_whitespace) || host.contains('@') || host.contains('/') { + Some("The SMTP host is a host name, not an address or a URL.") + } else if !(1..=65535).contains(&port) { + Some("A port is a number between 1 and 65535. 587 is the usual one; 465 is the other.") + } else if username.is_empty() { + Some("The username is the account Dizey signs in to the mail server with.") + } else if password.is_none() && !known { + Some("A password is needed the first time. It is stored so Dizey can sign in on every send, and is never shown again.") + } else if !is_address(&from_address) { + Some("The from-address is the address people will see this mail come from.") + } else { + None + }; + if let Some(problem) = complaint { + return Ok(Some(Refusal::BadSender(problem.to_string()))); + } + + match store + .set_sender( + &admin.workspace_id, + NewSender { + host, + port, + username, + password, + from_name, + from_address, + }, + ) + .await + { + Ok(()) => Ok(None), + Err(problem) => { + eprintln!("store error: {problem}"); + Ok(Some(Refusal::Unavailable)) + } + } +} + +/// The shallowest check that catches a typo without rejecting a real address. +/// Nothing here is trying to decide what RFC 5322 permits — the mail server +/// settles that, and a refusal from it lands in the ledger with its own words. +pub fn is_address(raw: &str) -> bool { + let mut halves = raw.split('@'); + let (Some(local), Some(domain), None) = (halves.next(), halves.next(), halves.next()) else { + return false; + }; + !local.is_empty() + && domain.contains('.') + && !domain.starts_with('.') + && !domain.ends_with('.') + && !raw.contains(char::is_whitespace) +} + /// The typed list as extensions, or `None` if one of them is not an extension. /// /// Lowercased, dots dropped, duplicates dropped, and nothing but letters and @@ -347,7 +477,6 @@ fn SettingsScreen( link_refusal: RwSignal>, ) -> impl IntoView { let me = snapshot.me.clone(); - let has_sender = snapshot.sender.is_some(); // Three roles, three true sentences. A Viewer is never mailed by a rule, so // the member's line is not merely vague for them, it is wrong. let role_note = match me.role { @@ -396,9 +525,7 @@ fn SettingsScreen( {snapshot .sender - .map(|sender| view! { })} - {(snapshot.administers && !has_sender) - .then(|| view! { })} + .map(|sender| view! { })} {snapshot.limits.map(|limits| view! { })} {snapshot .members @@ -469,77 +596,135 @@ fn ProfilePanel(me: Me) -> impl IntoView { } } -/// The sender, as the process is running it. Every control is disabled and -/// says why: none of this is workspace content, so there is nothing here a -/// save could write. +/// The sender the whole workspace mails through, as an admin edits it. +/// +/// The password field is write-only in both directions: it is never filled in, +/// because the server does not send it, and leaving it empty on a save means +/// "keep the one you have". The row underneath says which of those is true, so +/// an empty box is never ambiguous. #[component] -fn SenderPanel(sender: Sender) -> impl IntoView { +fn SenderPanel(sender: Sender, on_change: Callback<()>) -> impl IntoView { + let action = ServerAction::::new(); + let value = action.value(); + let saved = move || matches!(value.get(), Some(Ok(None))); + let refusal = move || match value.get() { + Some(Ok(Some(refusal))) => Some(refusal.message()), + Some(Err(_)) => Some(Refusal::Unavailable.message()), + _ => None, + }; + // A saved sender changes the chip, the password row and whether mail moves + // at all, so the snapshot behind this panel is refetched rather than left + // saying what was true before the save. + Effect::new(move |_| { + if matches!(value.get(), Some(Ok(None))) { + on_change.run(()); + } + }); + + let connected = sender.is_connected(); + let password_set = sender.password_set; + view! {

"Outgoing mail"

"Admin only" - "Connected" + {match connected { + true => view! { "Connected" }.into_any(), + false => view! { "Not configured" }.into_any(), + }}

"One sender for the whole workspace. Every mail rule, for every member, sends through this account — nobody sets their own."

-
+ {(!connected) + .then(|| { + view! { +

+ "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." +

+ } + })} + +
+ + +
-
- - - -

- "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." -

-
-
- } -} - -/// An admin on a workspace with no sender. Nothing is broken; nothing is sent. -#[component] -fn NoSenderPanel() -> impl IntoView { - view! { -
-
-

"Outgoing mail"

- "Admin only" - "Not configured" -
-
-

- "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." -

-

- "Set DIZEY_SMTP_HOST, DIZEY_SMTP_PORT, DIZEY_SMTP_USERNAME, DIZEY_SMTP_PASSWORD and DIZEY_MAIL_FROM — all five or none — and restart Dizey." -

+
+ + +
+
+ + + "Saved." + + + {move || refusal()} + +
+
} diff --git a/crates/dizey-web/src/smtp.rs b/crates/dizey-web/src/smtp.rs index 9f28112..1979bea 100644 --- a/crates/dizey-web/src/smtp.rs +++ b/crates/dizey-web/src/smtp.rs @@ -6,18 +6,39 @@ //! engine testable — the tests hand it a mailer that remembers instead of //! connecting. //! -//! The credentials come from the environment through `Config`, never from a -//! literal in here, and the password is not in anything this module logs or -//! puts in an error message: a refusal that quoted the password would put it -//! in the ledger, where an admin screen would later print it. +//! The credentials come from the workspace's own settings, written by an admin +//! on the Settings screen. They are never in a literal in here, and the +//! password is not in anything this module logs or puts in an error message: a +//! refusal that quoted the password would put it in the ledger, where an admin +//! screen would later print it. +//! +//! Because the sender is editable while the process runs, the transport cannot +//! be built once at boot. [`WorkspaceSmtp`] holds the last one it built and the +//! settings it was built from; a send whose settings still match reuses the +//! connection pool, and a send after an edit builds a new one and drops the old. + +use std::sync::Arc; -use dizey_core::config::MailConfig; +use dizey_core::store::Store; use dizey_core::mail::{MailError, Mailer, Outgoing}; use lettre::message::header::ContentType; use lettre::transport::smtp::authentication::Credentials; use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor}; -/// A sender holding one connection pool for the life of the process. +/// The sender as the mailer needs it: what the admin typed, password included. +/// It exists only inside this module and inside the store; nothing that can +/// reach a response body holds one. +#[derive(Clone, PartialEq, Eq)] +pub struct Sending { + pub host: String, + pub port: u16, + pub username: String, + pub password: String, + /// `Name
` if a name was given, the bare address otherwise. + pub from: String, +} + +/// A sender holding one connection pool. pub struct Smtp { transport: AsyncSmtpTransport, from: String, @@ -27,7 +48,7 @@ impl Smtp { /// Builds the transport. Fails only on a host name TLS cannot be set up /// against — a server that is merely unreachable is discovered per send, /// as a retryable refusal, which is the honest place for it. - pub fn new(mail: &MailConfig) -> Result { + pub fn new(mail: &Sending) -> Result { // 465 is submissions, where TLS is up before the greeting. Everything // else — 587 above all — is submission, where the session starts in // the clear and is upgraded. Both are encrypted before the password @@ -88,3 +109,97 @@ impl Mailer for Smtp { }) } } + +/// The mailer the engine actually holds: it reads the workspace's sender at +/// send time, so an admin who fixes a typo in the host does not have to restart +/// anything for the next mail to go out. +pub struct WorkspaceSmtp { + store: Arc, + /// The live transport and the settings it was built from. Rebuilt only when + /// those settings change — building one per send would throw away the + /// connection pool that makes a backlog drain quickly. + current: tokio::sync::Mutex)>>, +} + +impl WorkspaceSmtp { + pub fn new(store: Arc) -> Self { + Self { + store, + current: tokio::sync::Mutex::new(None), + } + } + + /// The sender as it stands right now, or `None` while the panel is empty. + /// + /// A half-filled sender counts as none. The screen will not save one, but + /// the check is here too, because this is the side that would otherwise + /// hand lettre an empty host and turn a missing setting into a stack of + /// refusals in the ledger. + async fn sending(&self) -> Result, MailError> { + let store = &self.store; + let workspace = store + .workspace() + .await + .map_err(|e| MailError::retryable(e.to_string()))?; + let Some(ws) = workspace else { + return Ok(None); + }; + let (Some(host), Some(port), Some(username), Some(address)) = ( + ws.smtp_host.clone(), + ws.smtp_port, + ws.smtp_username.clone(), + ws.smtp_from_address.clone(), + ) else { + return Ok(None); + }; + let password = store + .smtp_password(&ws.id) + .await + .map_err(|e| MailError::retryable(e.to_string()))?; + let (Some(password), Ok(port)) = (password, u16::try_from(port)) else { + return Ok(None); + }; + if host.trim().is_empty() || username.trim().is_empty() || password.is_empty() { + return Ok(None); + } + let from = match ws.smtp_from_name.as_deref().map(str::trim) { + Some(name) if !name.is_empty() => format!("{name} <{address}>"), + _ => address, + }; + Ok(Some(Sending { + host, + port, + username, + password, + from, + })) + } + + /// The transport for the current settings, building a new one only when + /// they have changed since the last send. + async fn transport(&self, want: &Sending) -> Result, MailError> { + let mut current = self.current.lock().await; + if let Some((held, smtp)) = current.as_ref() + && held == want + { + return Ok(smtp.clone()); + } + let built = Arc::new(Smtp::new(want).map_err(MailError::retryable)?); + *current = Some((want.clone(), built.clone())); + Ok(built) + } +} + +#[async_trait::async_trait] +impl Mailer for WorkspaceSmtp { + async fn send(&self, mail: &Outgoing) -> Result<(), MailError> { + let Some(want) = self.sending().await? else { + // Not a failure, and pointedly not an attempt: the mail is owed + // until somebody fills the sender in. + return Err(MailError::unsent( + "no sender is configured, so this is waiting rather than failing", + )); + }; + self.transport(&want).await?.send(mail).await + } +} diff --git a/crates/dizey-web/tests/http.rs b/crates/dizey-web/tests/http.rs index 4c88260..06cd579 100644 --- a/crates/dizey-web/tests/http.rs +++ b/crates/dizey-web/tests/http.rs @@ -32,22 +32,6 @@ struct App { impl App { async fn open() -> Self { - Self::open_with(None).await - } - - /// The same app, started the way a deployment with a sender configured - /// starts it. The password is not among what the router is given. - async fn with_sender() -> Self { - Self::open_with(Some(dizey_web::settings::Sender { - host: "smtp.fastmail.com".to_string(), - port: 465, - username: "dizey".to_string(), - from: "dizey@dizey.sh".to_string(), - })) - .await - } - - async fn open_with(sender: Option) -> Self { let dir = std::env::temp_dir().join(format!("dizey-http-{}", Uuid::new_v4())); std::fs::create_dir_all(&dir).unwrap(); let store = TursoStore::open(dir.join("dizey.db").to_str().unwrap()) @@ -57,7 +41,6 @@ impl App { let router = dizey_web::server::router( Accounts::new(Arc::new(store)), dizey_web::server::Mail::silent(), - sender, options, ); Self { dir, router } @@ -203,6 +186,29 @@ fn path() -> &'static str { F::PATH } +/// What the tests type into the password field. It must never come back out. +const SENDER_PASSWORD: &str = "cavalry-battery-hinge-40"; + +/// Fills in the sender panel the way an admin would, and reports whether the +/// server accepted it. +async fn sender_saved(app: &App, admin: &str) -> bool { + let answer = app + .post( + path::(), + Some(admin), + &[ + ("host", "smtp.fastmail.com"), + ("port", "465"), + ("username", "dizey"), + ("password", SENDER_PASSWORD), + ("from_name", "Dizey"), + ("from_address", "dizey@dizey.sh"), + ], + ) + .await; + answer.status == StatusCode::OK && answer.body == "null" +} + /// Claims the workspace and returns the admin's session cookie. async fn admin(app: &App) -> String { let answer = app @@ -837,8 +843,9 @@ async fn a_card_cannot_be_moved_into_another_boards_column() { #[tokio::test] async fn a_signed_out_browser_is_told_nothing_by_the_settings_call() { - let app = App::with_sender().await; - let _ = admin(&app).await; + let app = App::open().await; + let admin_cookie = admin(&app).await; + assert!(sender_saved(&app, &admin_cookie).await); let answer = app .post(path::(), None, &[]) @@ -854,16 +861,10 @@ async fn a_signed_out_browser_is_told_nothing_by_the_settings_call() { /// rather than a hidden panel whose contents rode along in the body. #[tokio::test] async fn a_member_is_told_nothing_about_the_sender() { - let app = App::with_sender().await; + let app = App::open().await; let admin_cookie = admin(&app).await; - let member = invited( - &app, - &admin_cookie, - "emre@dizey.sh", - "Emre", - Role::Member, - ) - .await; + assert!(sender_saved(&app, &admin_cookie).await); + let member = invited(&app, &admin_cookie, "emre@dizey.sh", "Emre", Role::Member).await; let answer = app .post( @@ -879,12 +880,13 @@ async fn a_member_is_told_nothing_about_the_sender() { assert!(!answer.body.contains("fastmail"), "{}", answer.body); } -/// The admin sees what the process is configured with — and the password is -/// not part of "what": it is never held anywhere this call can reach. +/// The admin sees the sender they typed — and never the password, which the +/// answer carries as a boolean and cannot carry as anything else. #[tokio::test] async fn an_admin_sees_the_sender_and_never_a_password() { - let app = App::with_sender().await; + let app = App::open().await; let admin_cookie = admin(&app).await; + assert!(sender_saved(&app, &admin_cookie).await); let answer = app .post( @@ -895,16 +897,206 @@ async fn an_admin_sees_the_sender_and_never_a_password() { .await; assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); - // The whole of what a screen may know about the sender, exactly: four - // fields, and no fifth one a password could be carried in. assert!( answer.body.contains( "\"sender\":{\"host\":\"smtp.fastmail.com\",\"port\":465,\ - \"username\":\"dizey\",\"from\":\"dizey@dizey.sh\"}" + \"username\":\"dizey\",\"from_name\":\"Dizey\",\ + \"from_address\":\"dizey@dizey.sh\",\"password_set\":true}" ), "{}", answer.body ); + assert!( + !answer.body.contains(SENDER_PASSWORD), + "the settings answer carried the SMTP password: {}", + answer.body + ); +} + +/// A Member cannot write the sender either. The panel they never received is a +/// courtesy; this is the guard, and it is in the handler. +#[tokio::test] +async fn only_an_admin_may_write_the_sender() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let member = invited(&app, &admin_cookie, "emre@dizey.sh", "Emre", Role::Member).await; + + let answer = app + .post( + path::(), + Some(&member), + &[ + ("host", "smtp.attacker.example"), + ("port", "587"), + ("username", "emre"), + ("password", "let-me-in"), + ("from_name", "Dizey"), + ("from_address", "emre@dizey.sh"), + ], + ) + .await; + + assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); + assert!(answer.body.contains("Forbidden"), "{}", answer.body); + + // And nothing was written: the admin's own view still shows no sender. + let seen = app + .post( + path::(), + Some(&admin_cookie), + &[], + ) + .await; + assert!(!seen.body.contains("attacker"), "{}", seen.body); +} + +/// A signed-out browser gets the same refusal, and writes nothing. +#[tokio::test] +async fn a_signed_out_browser_may_not_write_the_sender() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + + let answer = app + .post( + path::(), + None, + &[ + ("host", "smtp.attacker.example"), + ("port", "587"), + ("username", "nobody"), + ("password", "let-me-in"), + ("from_name", "Dizey"), + ("from_address", "nobody@dizey.sh"), + ], + ) + .await; + + assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); + assert!(answer.body.contains("SignInFirst"), "{}", answer.body); + + let seen = app + .post( + path::(), + Some(&admin_cookie), + &[], + ) + .await; + assert!(!seen.body.contains("attacker"), "{}", seen.body); +} + +/// The password field is write-only, so the form has nothing to send back for +/// a password that already exists. An edit with the field left empty must keep +/// the stored password rather than reading the blank as a deletion — otherwise +/// correcting a port silently stops the workspace sending mail. +#[tokio::test] +async fn an_edit_with_no_password_typed_keeps_the_stored_one() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + assert!(sender_saved(&app, &admin_cookie).await); + + let answer = app + .post( + path::(), + Some(&admin_cookie), + &[ + ("host", "smtp.fastmail.com"), + ("port", "587"), + ("username", "dizey"), + ("password", ""), + ("from_name", "Dizey"), + ("from_address", "dizey@dizey.sh"), + ], + ) + .await; + assert_eq!(answer.body, "null", "{}", answer.body); + + let seen = app + .post( + path::(), + Some(&admin_cookie), + &[], + ) + .await; + assert!(seen.body.contains("\"port\":587"), "the edit did not land: {}", seen.body); + assert!( + seen.body.contains("\"password_set\":true"), + "an empty field blanked the password: {}", + seen.body + ); +} + +/// The first save has to carry one, though. A sender with no password is a +/// sender that cannot sign in, and storing it would turn a form somebody can +/// fix into a queue of refusals they have to read the ledger to find. +#[tokio::test] +async fn a_first_sender_with_no_password_is_refused_and_says_why() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + + let answer = app + .post( + path::(), + Some(&admin_cookie), + &[ + ("host", "smtp.fastmail.com"), + ("port", "587"), + ("username", "dizey"), + ("password", ""), + ("from_name", "Dizey"), + ("from_address", "dizey@dizey.sh"), + ], + ) + .await; + + assert!(answer.body.contains("BadSender"), "{}", answer.body); + assert!(answer.body.contains("password"), "{}", answer.body); +} + +/// Each field the sender cannot work without is refused by name. A form that +/// answers "that did not work" sends somebody round the panel guessing. +#[tokio::test] +async fn a_sender_field_that_cannot_work_is_refused_by_name() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + + let bad: &[(&str, &[(&str, &str)])] = &[ + ("host", &[("host", " ")]), + ("host", &[("host", "smtp.fastmail.com/inbox")]), + ("port", &[("port", "0")]), + ("port", &[("port", "99999")]), + ("username", &[("username", "")]), + ("from_address", &[("from_address", "board-at-dizey")]), + ("from_address", &[("from_address", "board@dizey")]), + ]; + for (field, overrides) in bad { + let mut form: Vec<(&str, &str)> = vec![ + ("host", "smtp.fastmail.com"), + ("port", "587"), + ("username", "dizey"), + ("password", SENDER_PASSWORD), + ("from_name", "Dizey"), + ("from_address", "dizey@dizey.sh"), + ]; + for (key, value) in *overrides { + for slot in form.iter_mut() { + if slot.0 == *key { + slot.1 = value; + } + } + } + let answer = app + .post( + path::(), + Some(&admin_cookie), + &form, + ) + .await; + assert!( + answer.body.contains("BadSender"), + "{field} was accepted with {overrides:?}: {}", + answer.body + ); + } } /// The form carries a name and nothing else. Who is renamed comes from the