//! Outbound mail: what each mail says, how it is queued, and how the queue is sent. //! //! A mail is queued with [`queue`]: its text is rendered in the recipient's language, then sealed under the //! instance key and stored in `mail_outbox` (architecture section 3). The worker in [`worker`] sends the //! queued rows with retries. Nothing in this module logs a body, a link or a recipient address. //! //! - [`message`] builds the lettre message from typed parts only. A name or address that is not valid is //! refused before any header is written, so no user text can add a header. //! - [`templates`] renders the text and HTML of each kind. Every value goes through HTML escaping. //! - [`transport`] builds the SMTP connection from the config, reading the password file each time. pub mod message; pub mod templates; pub mod transport; pub mod worker; use im_core::Result; use im_core::model::User; use im_core::secret; use im_core::store::Store; use im_core::store::mail::NewMail; use serde_json::json; use crate::i18n::Lang; pub use message::Recipient; /// The security notices sent to the account's own address. Each is kind `security`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Notice { /// The password was changed on the security page. PasswordChanged, /// The password was set through a reset link. PasswordReset, /// Two-factor sign-in was turned on. TwoFactorOn, /// Two-factor sign-in was turned off. TwoFactorOff, /// The recovery codes were replaced. RecoveryCodes, } /// One kind of mail, with the values its text needs. A link is already built by the caller. #[derive(Clone, Copy)] pub enum Mail<'a> { /// An administrator invited the recipient to create an account. Invite { /// The invitation link. link: &'a str, /// Days the link lasts. days: u32, }, /// A password reset was asked for. Reset { /// The reset link. link: &'a str, /// Minutes the link lasts. minutes: u32, }, /// Sent to the current address of an email change, with the cancel-or-confirm link. EmailOld { /// The link of the old half. link: &'a str, /// The address the account would move to. new_email: &'a str, /// Hours the link lasts. hours: u32, }, /// Sent to the new address of an email change. EmailNew { /// The link of the new half. link: &'a str, /// Hours the link lasts. hours: u32, }, /// The change happened. Sent to both addresses. EmailDone { /// The address the account has now. new_email: &'a str, }, /// Sent to the owner of an address that someone tried to use for another account. Nothing changed. EmailTaken { /// The service's public origin, which names the account the attempt was for. issuer: &'a str, }, /// A security notice. Security(Notice), /// A message from an administrator. The subject and the body are the administrator's own words; they /// are escaped like every other value, and the body is split into paragraphs at blank lines. Notice { /// The subject line. Single line, checked by the caller. subject: &'a str, /// The body, plain text. body: &'a str, }, /// A test mail sent from the administrator's mail page. Its text is fixed. Test { /// The subject. subject: &'a str, /// The body, paragraphs separated by a blank line. body: &'a str, }, } /// Prints every value except the links, which print as ``: each link carries a token. impl std::fmt::Debug for Mail<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Mail::Invite { days, .. } => f .debug_struct("Invite") .field("link", &format_args!("")) .field("days", days) .finish(), Mail::Reset { minutes, .. } => f .debug_struct("Reset") .field("link", &format_args!("")) .field("minutes", minutes) .finish(), Mail::EmailOld { new_email, hours, .. } => f .debug_struct("EmailOld") .field("link", &format_args!("")) .field("new_email", new_email) .field("hours", hours) .finish(), Mail::EmailNew { hours, .. } => f .debug_struct("EmailNew") .field("link", &format_args!("")) .field("hours", hours) .finish(), Mail::EmailDone { new_email } => f .debug_struct("EmailDone") .field("new_email", new_email) .finish(), Mail::EmailTaken { issuer } => f .debug_struct("EmailTaken") .field("issuer", issuer) .finish(), Mail::Security(notice) => f.debug_tuple("Security").field(notice).finish(), Mail::Notice { subject, body } => f .debug_struct("Notice") .field("subject", subject) .field("body", body) .finish(), Mail::Test { subject, body } => f .debug_struct("Test") .field("subject", subject) .field("body", body) .finish(), } } } impl Mail<'_> { /// The stored kind, one of the values `mail_outbox.kind` allows. pub fn kind(&self) -> &'static str { match self { Mail::Invite { .. } => "invite", Mail::Reset { .. } => "reset", Mail::EmailOld { .. } => "email_old", Mail::EmailNew { .. } => "email_new", Mail::EmailDone { .. } => "email_done", Mail::EmailTaken { .. } => "security", Mail::Security(_) => "security", Mail::Notice { .. } => "notice", Mail::Test { .. } => "test", } } } /// The language a mail to `user` is written in: the stored choice, unless the person chose the /// browser's language. Then the language of the request that triggered the mail. pub fn lang_for(user: &User, request: Lang) -> Lang { if user.locale_auto { request } else { Lang::from_code(&user.locale).unwrap_or(request) } } /// A mail rendered and sealed, not yet in the outbox. Built before any link it carries is created, so the /// store can check its limits and create the links in one transaction (see `store::links`). pub struct Sealed { kind: &'static str, to_addr: String, subject: String, sealed_body: String, } impl Sealed { /// The outbox row this mail becomes. pub fn as_new(&self) -> NewMail<'_> { NewMail { kind: self.kind, to_addr: &self.to_addr, subject: &self.subject, sealed_body: &self.sealed_body, } } } /// Renders `mail` for `to` in `lang` and seals it under the instance key. The subject is fixed text; the /// body (text and HTML, with the recipient's name) is sealed as one JSON document. pub fn seal(key: &[u8; 32], to: &Recipient, lang: Lang, mail: &Mail<'_>) -> Result { let rendered = templates::render(lang, to.name(), mail); let payload = json!({ "to_name": to.name(), "text": rendered.text, "html": rendered.html, }) .to_string(); let sealed = secret::seal(key, secret::purpose::MAIL_BODY, payload.as_bytes())?; Ok(Sealed { kind: mail.kind(), to_addr: to.email().to_string(), subject: rendered.subject, sealed_body: sealed, }) } /// Renders `mail` for `to` in `lang`, seals it, and adds it to the outbox. A mail that the store drops by /// its limits is not an error here: the caller answers the same either way. pub async fn queue( store: &Store, key: &[u8; 32], to: &Recipient, lang: Lang, mail: &Mail<'_>, ) -> Result<()> { let sealed = seal(key, to, lang, mail)?; store.enqueue_mail(&sealed.as_new()).await?; Ok(()) } /// Queues a security notice for the account's own address, in the person's language. A failure is /// logged and never reaches the caller: the change it reports has already been made. pub async fn notify(store: &Store, key: &[u8; 32], user: &User, request: Lang, notice: Notice) { let to = match Recipient::new(Some(&user.name), &user.email) { Ok(to) => to, Err(error) => { tracing::error!( error, "security notice not queued: stored address is not valid" ); return; } }; let lang = lang_for(user, request); if let Err(error) = queue(store, key, &to, lang, &Mail::Security(notice)).await { tracing::error!(error = %error, "security notice not queued"); } }