15.4 KiB · text History 952e601
//! Outbound mail.
//!
//! Everything that sends mail builds a [`Message`] and hands it to the
//! [`Mailer`] in `AppState`. Which one that is is decided by [`build`]:
//!
//! * [`MailPrismMailer`] when `MAIL_PRISM_URL` and `MAIL_PRISM_API_KEY` are
//!   set: mail-prism renders the message's template (kept in the repo's
//!   `mail_prism/` directory and synced at startup, see [`sync_templates`]) and
//!   delivers it.
//! * [`LogMailer`] otherwise: the message is written to the log, which is how
//!   a development setup (or an operator without mail) gets a link to a user.
//!
//! A message carries both a template and a plain-text rendering of the same
//! thing, so either transport has what it needs. Modelled on jupiter-trojan's
//! `tower-login-server/src/mailer.rs`.

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

use mail_prism_client::{Client, SendRequest, SyncTemplates, TemplateSpec};
use serde_json::{json, Value};
use tracing::{error, info, warn};

use crate::Config;

pub type SendFuture<'a> = Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>>;

pub trait Mailer: Send + Sync {
    fn send<'a>(&'a self, message: &'a Message) -> SendFuture<'a>;
    /// A mail with no mail-prism template: the text (and HTML) as given.
    /// For mail composed elsewhere (neiam-auth's password reset). Both real
    /// transports implement it; the default refuses (test doubles).
    fn send_raw<'a>(&'a self, message: &'a RawMessage) -> SendFuture<'a> {
        Box::pin(async move { Err(MailError(format!("this transport can't send {}", message.label))) })
    }
    /// `true` when mail actually leaves the building (not the log transport).
    fn delivers(&self) -> bool;
}

#[derive(Debug, Clone)]
pub struct Message {
    pub to: String,
    /// mail-prism template slug (`mail_prism/<template>.*`).
    pub template: &'static str,
    /// The template's variables. Rendering is strict, so this must define
    /// every one the template uses — `mail_prism/<template>.json` is the
    /// sample the sync checks it against.
    pub context: Value,
    /// mail-prism `idempotency_key`: a retry of the same logical message
    /// (e.g. the same verification token) is not sent twice.
    pub idempotency_key: Option<String>,
    /// Plain-text rendering, for the log transport.
    pub subject: String,
    pub body: String,
}

/// A pre-rendered mail ([`Mailer::send_raw`]).
#[derive(Clone)]
pub struct RawMessage {
    pub to: String,
    pub subject: String,
    pub text: String,
    pub html: Option<String>,
    pub idempotency_key: Option<String>,
    /// Names the mail in the log, as a template slug would.
    pub label: &'static str,
}

#[derive(Debug)]
pub struct MailError(pub String);

impl std::fmt::Display for MailError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::error::Error for MailError {}

/// Writes the message to the log at INFO. In a deployment without a mail
/// transport this is how an operator (or a developer) gets a link to a user.
pub struct LogMailer;

impl Mailer for LogMailer {
    fn send_raw<'a>(&'a self, message: &'a RawMessage) -> SendFuture<'a> {
        Box::pin(async move {
            info!(
                to = %message.to,
                subject = %message.subject,
                template = message.label,
                "outbound mail (log transport; set MAIL_PRISM_URL + MAIL_PRISM_API_KEY to send)\n{}",
                message.text
            );
            Ok(())
        })
    }

    fn send<'a>(&'a self, message: &'a Message) -> SendFuture<'a> {
        Box::pin(async move {
            info!(
                to = %message.to,
                subject = %message.subject,
                template = message.template,
                "outbound mail (log transport; set MAIL_PRISM_URL + MAIL_PRISM_API_KEY to send)\n{}",
                message.body
            );
            Ok(())
        })
    }

    fn delivers(&self) -> bool {
        false
    }
}

/// Sends through mail-prism. `from_address`, when set, must be the address
/// the API key was issued for (mail-prism refuses anything else:
/// `from_mismatch`); unset, mail-prism uses the application's own address.
pub struct MailPrismMailer {
    client: Client,
    from_address: Option<String>,
    from_name: String,
}

impl MailPrismMailer {
    pub fn new(
        url: &str,
        api_key: &str,
        from_address: Option<&str>,
        from_name: &str,
    ) -> Result<Self, MailError> {
        let client = Client::new(url, api_key).map_err(|e| MailError(e.to_string()))?;
        Ok(Self {
            client,
            from_address: from_address.map(str::to_string),
            from_name: from_name.to_string(),
        })
    }

    pub fn client(&self) -> &Client {
        &self.client
    }

    /// A template-less test message (`manage email test`). Returns the
    /// mail-prism message id.
    pub async fn send_test(&self, to: &str, site_name: &str) -> Result<String, MailError> {
        let mut request = SendRequest::raw(format!("{site_name}: mail-prism test"))
            .to(to)
            .from_name(self.from_name.as_str())
            .text(format!(
                "This is a test message from {site_name}, sent through mail-prism.\n\
                 If you can read it, outbound mail (email verification) works.\n"
            ));
        request.from = self.from_address.clone();
        self.client
            .send(&request)
            .await
            .map(|r| r.id.to_string())
            .map_err(|e| MailError(e.to_string()))
    }
}

impl MailPrismMailer {
    /// Send `request`, with one retry for what a retry can fix (transport,
    /// 5xx, 429); a 4xx is this request being wrong and fails straight away,
    /// loudly. The idempotency key makes the retry safe. `what` names the
    /// mail in the log (its template slug).
    async fn deliver(&self, request: &SendRequest, what: &str) -> Result<(), MailError> {
        let mut attempt = 0;
        loop {
            attempt += 1;
            match self.client.send(request).await {
                Ok(receipt) => {
                    info!(
                        template = what,
                        id = %receipt.id,
                        duplicate = receipt.duplicate,
                        "mail queued with mail-prism"
                    );
                    return Ok(());
                }
                Err(e) if e.is_retryable() && attempt < 2 => {
                    warn!(template = what, "mail-prism send failed, retrying: {e}");
                    tokio::time::sleep(Duration::from_secs(1)).await;
                }
                Err(e) => {
                    error!(template = what, "mail-prism send failed: {e}");
                    return Err(MailError(e.to_string()));
                }
            }
        }
    }
}

impl Mailer for MailPrismMailer {
    fn send<'a>(&'a self, message: &'a Message) -> SendFuture<'a> {
        Box::pin(async move {
            let mut request = SendRequest::template(message.template)
                .to(message.to.as_str())
                .from_name(self.from_name.as_str())
                .context(message.context.clone());
            request.from = self.from_address.clone();
            request.idempotency_key = message.idempotency_key.clone();
            self.deliver(&request, message.template).await
        })
    }

    fn send_raw<'a>(&'a self, message: &'a RawMessage) -> SendFuture<'a> {
        Box::pin(async move {
            let mut request = SendRequest::raw(message.subject.as_str())
                .to(message.to.as_str())
                .from_name(self.from_name.as_str())
                .text(message.text.as_str());
            request.html = message.html.clone();
            request.from = self.from_address.clone();
            request.idempotency_key = message.idempotency_key.clone();
            self.deliver(&request, message.label).await
        })
    }

    fn delivers(&self) -> bool {
        true
    }
}

/// mail-prism when it's configured, else the log. `sync` also pushes
/// `mail_prism/` to mail-prism in the background (the webservice does; the
/// CLI doesn't), so a slow or absent mail service never holds up startup.
pub fn build(config: &Config, sync: bool) -> Arc<dyn Mailer> {
    match mail_prism_mailer(config) {
        None => {
            info!("MAIL_PRISM_URL / MAIL_PRISM_API_KEY not set; outbound mail is only logged");
            Arc::new(LogMailer)
        }
        Some(Ok(mailer)) => {
            info!(
                "sending mail through mail-prism at {} as {}",
                config.mail_prism_url.as_deref().unwrap_or_default(),
                config.mail_from_address.as_deref().unwrap_or("the API key's application address"),
            );
            if sync {
                tokio::spawn(sync_templates(mailer.client().clone()));
            }
            Arc::new(mailer)
        }
        Some(Err(e)) => {
            error!("mail-prism client could not be built ({e}); outbound mail is only logged");
            Arc::new(LogMailer)
        }
    }
}

/// The mail-prism mailer, or `None` when mail-prism isn't configured.
pub fn mail_prism_mailer(config: &Config) -> Option<Result<MailPrismMailer, MailError>> {
    let (Some(url), Some(key)) = (&config.mail_prism_url, &config.mail_prism_api_key) else {
        return None;
    };
    Some(MailPrismMailer::new(
        url,
        key,
        config.mail_from_address.as_deref(),
        &config.mail_from_name,
    ))
}

// --------------------------------------------------------------- templates

/// One template's files, compiled in from `mail_prism/<slug>.*`.
macro_rules! template {
    ($slug:literal) => {
        (
            $slug,
            include_str!(concat!("../mail_prism/", $slug, ".subject")),
            include_str!(concat!("../mail_prism/", $slug, ".html")),
            include_str!(concat!("../mail_prism/", $slug, ".txt")),
            include_str!(concat!("../mail_prism/", $slug, ".json")),
        )
    };
}

/// The templates in `mail_prism/`: slug, subject, html, text, sample context
/// (with optional `_name` / `_description` for mail-prism's admin UI). A new
/// template needs a line here as well as its files.
const TEMPLATE_FILES: &[(&str, &str, &str, &str, &str)] = &[template!("layout"), template!("verify-email")];

pub fn template_specs() -> Result<Vec<TemplateSpec>, String> {
    TEMPLATE_FILES
        .iter()
        .map(|(slug, subject, html, text, sample)| {
            let mut sample: serde_json::Map<String, Value> =
                serde_json::from_str(sample).map_err(|e| format!("mail_prism/{slug}.json: {e}"))?;
            let name = sample.remove("_name").and_then(|v| v.as_str().map(String::from));
            let description = sample
                .remove("_description")
                .and_then(|v| v.as_str().map(String::from))
                .unwrap_or_default();
            Ok(TemplateSpec {
                slug: slug.to_string(),
                name,
                description,
                subject: subject.trim_end_matches('\n').to_string(),
                html: html.to_string(),
                text: text.to_string(),
                sample_context: Value::Object(sample),
            })
        })
        .collect()
}

/// Push the compiled-in templates to mail-prism, replacing what this key's
/// application had synced before. Retries for about a minute (mail-prism may be
/// starting alongside us), then gives up with an error in the log: sends that
/// name a template that never arrived fail with `unknown_template`, so a broken
/// sync is loud, not silent.
pub async fn sync_templates(client: Client) {
    let templates = match template_specs() {
        Ok(t) => t,
        Err(e) => {
            error!("mail-prism templates not synced: {e}");
            return;
        }
    };
    let request = SyncTemplates { templates, prune: true };

    let mut delay = Duration::from_secs(2);
    let mut waited = Duration::ZERO;
    loop {
        match client.sync_templates(&request).await {
            Ok(report) => {
                info!(
                    "mail-prism templates synced: {} created, {} updated, {} unchanged, {} deleted",
                    report.created.len(),
                    report.updated.len(),
                    report.unchanged.len(),
                    report.deleted.len()
                );
                return;
            }
            Err(e) if e.is_retryable() && waited < Duration::from_secs(60) => {
                warn!("mail-prism template sync failed, retrying in {delay:?}: {e}");
                tokio::time::sleep(delay).await;
                waited += delay;
                delay = (delay * 2).min(Duration::from_secs(15));
            }
            Err(e) => {
                error!("mail-prism template sync failed: {e}");
                return;
            }
        }
    }
}

// ---------------------------------------------------------------- messages

/// Verify the address an account signed up with. `token_id` keys the
/// idempotency: one token, at most one mail.
pub fn verify_email_message(
    to: &str,
    site_name: &str,
    username: &str,
    verify_url: &str,
    ttl_hours: i64,
    token_id: uuid::Uuid,
) -> Message {
    Message {
        to: to.to_string(),
        template: "verify-email",
        context: json!({
            "site_name": site_name,
            "username": username,
            "url": verify_url,
            "ttl_hours": ttl_hours,
        }),
        idempotency_key: Some(format!("verify-email-{token_id}")),
        subject: format!("Verify your email for {site_name}"),
        body: format!(
            "Verify the email address for your {site_name} account, {username}, \
             by opening this link:\n\n  {verify_url}\n\n\
             Until you do, you can read but not post, reply, react or bookmark. \
             The link works once and expires in {ttl_hours} hours. If you didn't \
             make this account, ignore this message.\n"
        ),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn every_template_loads_with_a_subject_and_sample() {
        let specs = template_specs().expect("templates load");
        let slugs: Vec<&str> = specs.iter().map(|s| s.slug.as_str()).collect();
        assert_eq!(slugs, ["layout", "verify-email"]);
        for spec in &specs {
            assert!(!spec.subject.is_empty(), "{} has no subject", spec.slug);
            assert!(spec.sample_context.is_object());
        }
    }

    /// The context each message sends must be exactly what its template's
    /// sample defines: mail-prism renders strictly, so a variable the template
    /// uses but the message lacks is a refused send.
    #[test]
    fn message_contexts_match_template_samples() {
        let specs = template_specs().unwrap();
        let sample_keys = |slug: &str| {
            let spec = specs.iter().find(|s| s.slug == slug).unwrap();
            let mut keys: Vec<String> = spec.sample_context.as_object().unwrap().keys().cloned().collect();
            keys.sort();
            keys
        };
        let url = "https://example.com/verify-email?token=x";
        let message = verify_email_message("a@example.com", "Site", "ada", url, 48, uuid::Uuid::nil());
        let mut keys: Vec<String> = message.context.as_object().unwrap().keys().cloned().collect();
        keys.sort();
        assert_eq!(keys, sample_keys(message.template));
        assert!(message.body.contains(url));
        assert!(message.idempotency_key.unwrap().starts_with("verify-email-"));
    }
}