saola-kit 0.1.4

Saola core toolkit for Laravel for Rust (contexts, envelope protocol, i18n, masks, modules, Sanctum-compatible tokens)
Documentation
use std::net::IpAddr;

use laravel::config::mail::MailerConfig;
use laravel::config::{Config, Env};
use laravel::container::Registrar;
use laravel::mail::{Email, SentMessage, Transport};
use laravel::{Error, Result};
use lettre::address::Envelope;
use lettre::transport::smtp::authentication::Credentials;
use lettre::{AsyncSmtpTransport, AsyncTransport, Tokio1Executor};

use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, RwLock};

use lettre::message::header::{From as FromHeader, Headers};
use lettre::message::{Mailbox, Mailboxes};

const DRIVER: &str = "smtp";
/// Mailer/driver whose behavior follows [`set_mail_mode`] (settings stored by the application).
pub const RUNTIME_MAILER: &str = "saola";

struct SmtpConfig {
    host: String,
    scheme: String,
    port: Option<String>,
    username: Option<String>,
    password: Option<String>,
}

/// How the `saola` mailer delivers right now. The application sets it from stored settings (an admin
/// "email" settings page) and may change it at any time; the next send follows it.
#[derive(Debug, Clone, Default)]
pub enum MailMode {
    /// What `.env` says: SMTP through `MAIL_*` when `MAIL_MAILER=smtp`, otherwise the log.
    #[default]
    Env,
    /// Write the email to the log and send nothing.
    Log,
    /// Send through this SMTP server.
    Smtp(SmtpSettings),
}

/// Connection security of an SMTP server.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SmtpTls {
    /// TLS from the first byte (`smtps`, usually port 465).
    Implicit,
    /// Plain connection upgraded with STARTTLS (usually port 587).
    StartTls,
    /// No encryption; accepted only for a loopback host and without credentials.
    None,
}

/// An SMTP server plus an optional sender that replaces the one the email was built with.
#[derive(Debug, Clone)]
pub struct SmtpSettings {
    pub host: String,
    pub port: Option<u16>,
    pub tls: SmtpTls,
    pub username: Option<String>,
    pub password: Option<String>,
    /// `(address, display name)` written into the `From` header and the envelope sender.
    pub from: Option<(String, String)>,
}

type ModeFuture = Pin<Box<dyn Future<Output = MailMode> + Send>>;
type ModeProvider = Arc<dyn Fn() -> ModeFuture + Send + Sync>;

static MODE: RwLock<MailMode> = RwLock::new(MailMode::Env);
static PROVIDER: RwLock<Option<ModeProvider>> = RwLock::new(None);

/// Sets a fixed mode for the `saola` mailer; takes effect on the next send. Ignored while a provider is set.
pub fn set_mail_mode(mode: MailMode) {
    *MODE.write().unwrap_or_else(|poisoned| poisoned.into_inner()) = mode;
}

/// Asks `provider` for the mode before every send, so settings changed in the database apply at once
/// in every process (web server and queue worker alike). Install it where services are registered.
pub fn set_mail_mode_provider<F, Fut>(provider: F)
where
    F: Fn() -> Fut + Send + Sync + 'static,
    Fut: Future<Output = MailMode> + Send + 'static,
{
    let provider: ModeProvider = Arc::new(move || Box::pin(provider()));
    *PROVIDER.write().unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(provider);
}

/// The mode in force right now: the provider's answer, else the fixed one.
pub async fn mail_mode() -> MailMode {
    let provider = PROVIDER.read().unwrap_or_else(|poisoned| poisoned.into_inner()).clone();
    match provider {
        Some(provider) => provider().await,
        None => MODE.read().unwrap_or_else(|poisoned| poisoned.into_inner()).clone(),
    }
}

/// Makes the `saola` mailer the default one, so [`set_mail_mode`] decides how every email goes out.
/// Call it from `with_config`. `.env` stays the fallback ([`MailMode::Env`]): with `MAIL_MAILER=smtp`
/// emails go through `MAIL_*`, with anything else they are logged.
pub fn use_runtime_mailer(config: &mut Config, env: &Env) {
    let env_mailer: String = env.get("MAIL_MAILER").unwrap_or_else(|| "log".into());
    config.set(EnvMailer(env_mailer));
    config.mail.add_mailer(RUNTIME_MAILER, MailerConfig::custom(RUNTIME_MAILER));
    config.mail.default = RUNTIME_MAILER.into();
}

struct EnvMailer(String);

/// What `MAIL_MAILER` said before [`use_runtime_mailer`] replaced the default (`log` when it was unset).
pub fn env_mailer(config: &Config) -> String {
    config.section::<EnvMailer>().0.clone()
}

pub(super) fn configure(config: &mut Config, env: &Env) {
    config.set(SmtpConfig {
        host: env.get("MAIL_HOST").unwrap_or_default(),
        scheme: env.get("MAIL_SCHEME").unwrap_or_else(|| "smtp".into()),
        port: env.get("MAIL_PORT"),
        username: env
            .get::<String>("MAIL_USERNAME")
            .filter(|value| !value.is_empty()),
        password: env
            .get::<String>("MAIL_PASSWORD")
            .filter(|value| !value.is_empty()),
    });
    config.mail.add_mailer(DRIVER, MailerConfig::custom(DRIVER));
}

pub(super) fn register(app: &mut Registrar) {
    app.mail().extend(DRIVER, async |app, _| {
        SmtpTransport::new(app.config().section::<SmtpConfig>())
    });
    app.mail().extend(RUNTIME_MAILER, async |app, _| {
        // Only reached through the mailer `use_runtime_mailer` adds, which also stores `EnvMailer`.
        let smtp_from_env = app.config().section::<EnvMailer>().0 == DRIVER;
        let env = smtp_from_env
            .then(|| SmtpTransport::new(app.config().section::<SmtpConfig>()))
            .transpose()?;
        Ok(RuntimeTransport { env })
    });
}

/// Delivers according to [`mail_mode`], building the SMTP client per send so changed settings apply at once.
struct RuntimeTransport {
    env: Option<SmtpTransport>,
}

impl Transport for RuntimeTransport {
    async fn send(&self, email: &Email) -> Result<SentMessage> {
        match mail_mode().await {
            MailMode::Smtp(settings) => SmtpTransport::from_settings(&settings)?.send_as(email, settings.from.as_ref()).await,
            MailMode::Env if self.env.is_some() => self.env.as_ref().expect("checked").send(email).await,
            MailMode::Env | MailMode::Log => {
                tracing::info!(subject = email.subject(), recipients = email.to().len(), "email not sent: log mailer");
                Ok(SentMessage::default())
            }
        }
    }
}

type SmtpClient = AsyncSmtpTransport<Tokio1Executor>;

struct SmtpTransport(SmtpClient);

impl SmtpTransport {
    fn from_settings(settings: &SmtpSettings) -> Result<Self> {
        Self::new(&SmtpConfig {
            host: settings.host.clone(),
            scheme: match settings.tls {
                SmtpTls::Implicit => "smtps",
                SmtpTls::StartTls => "smtp",
                SmtpTls::None => "none",
            }
            .into(),
            port: settings.port.map(|port| port.to_string()),
            username: settings.username.clone().filter(|value| !value.is_empty()),
            password: settings.password.clone().filter(|value| !value.is_empty()),
        })
    }

    fn new(config: &SmtpConfig) -> Result<Self> {
        let host = config.host.trim();
        if host.is_empty() {
            return Err(Error::msg("SMTP requires MAIL_HOST"));
        }

        let builder = match config.scheme.as_str() {
            "smtp" => SmtpClient::starttls_relay(host),
            "smtps" => SmtpClient::relay(host),
            "none" => {
                if !host.eq_ignore_ascii_case("localhost")
                    && !host.parse::<IpAddr>().is_ok_and(|ip| ip.is_loopback())
                {
                    return Err(Error::msg("Unencrypted SMTP requires a loopback MAIL_HOST"));
                }
                if config.username.is_some() || config.password.is_some() {
                    return Err(Error::msg("SMTP authentication requires TLS"));
                }
                Ok(SmtpClient::builder_dangerous(host))
            }
            _ => return Err(Error::msg("MAIL_SCHEME must be smtp, smtps, or none")),
        };
        let mut builder = builder.map_err(|_| Error::msg("Invalid SMTP host for TLS"))?;

        if let Some(port) = &config.port {
            let port = port
                .parse::<u16>()
                .ok()
                .filter(|port| *port != 0)
                .ok_or_else(|| Error::msg("MAIL_PORT must be between 1 and 65535"))?;
            builder = builder.port(port);
        }

        match (&config.username, &config.password) {
            (Some(username), Some(password)) => {
                builder = builder.credentials(Credentials::new(username.clone(), password.clone()));
            }
            (None, None) => {}
            _ => return Err(Error::msg("Set MAIL_USERNAME and MAIL_PASSWORD together")),
        }

        Ok(Self(builder.build()))
    }
}

impl Transport for SmtpTransport {
    async fn send(&self, email: &Email) -> Result<SentMessage> {
        self.send_as(email, None).await
    }
}

impl SmtpTransport {
    async fn send_as(&self, email: &Email, from: Option<&(String, String)>) -> Result<SentMessage> {
        let sender = from
            .map_or_else(|| email.from().email().to_owned(), |(address, _)| address.clone())
            .parse()
            .map_err(|_| Error::msg("Invalid SMTP sender"))?;
        let recipients = email
            .to()
            .iter()
            .chain(email.cc())
            .chain(email.bcc())
            .map(|address| address.email().parse())
            .collect::<std::result::Result<_, _>>()
            .map_err(|_| Error::msg("Invalid SMTP recipient"))?;
        let envelope = Envelope::new(Some(sender), recipients)
            .map_err(|_| Error::msg("SMTP requires at least one recipient"))?;
        let mut mime = email.to_mime().await?;
        if let Some((address, name)) = from {
            mime = replace_from(&mime, address, name)?;
        }

        self.0.send_raw(&envelope, &mime).await.map_err(|error| {
            if let Some(status) = error.status() {
                Error::msg(format!("SMTP server rejected the message or session ({status})"))
            } else {
                Error::msg("SMTP delivery failed while connecting or communicating with the server")
            }
        })?;

        Ok(SentMessage::default())
    }
}

/// Replaces the `From` header of a rendered message (headers end at the first blank line).
fn replace_from(mime: &[u8], address: &str, name: &str) -> Result<Vec<u8>> {
    let mailbox = Mailbox::new(
        (!name.is_empty()).then(|| name.to_owned()),
        address.parse().map_err(|_| Error::msg("Invalid SMTP sender"))?,
    );
    let mut headers = Headers::new();
    headers.set(FromHeader::from(Mailboxes::from(mailbox)));
    let header = headers.to_string();

    let end = mime.windows(4).position(|w| w == b"\r\n\r\n").map_or(mime.len(), |at| at + 2);
    let (head, rest) = mime.split_at(end);
    let head = String::from_utf8_lossy(head);
    let mut out = String::new();
    let mut skipping = false;
    let mut replaced = false;
    for line in head.split_inclusive("\r\n") {
        let folded = line.starts_with([' ', '\t']);
        if skipping && folded {
            continue;
        }
        skipping = line.len() >= 5 && line[..5].eq_ignore_ascii_case("from:");
        if skipping {
            out.push_str(&header);
            replaced = true;
        } else {
            out.push_str(line);
        }
    }
    if !replaced {
        out.push_str(&header);
    }
    let mut bytes = out.into_bytes();
    bytes.extend_from_slice(rest);
    Ok(bytes)
}

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

    #[test]
    fn replaces_a_folded_from_header_and_keeps_the_body() {
        let mime = b"Message-ID: <1@x>\r\nFrom: Old Name\r\n <old@example.test>\r\nSubject: Hi\r\n\r\nBody\r\n";
        let out = String::from_utf8(replace_from(mime, "new@example.test", "Nguyen Van A").unwrap()).unwrap();
        assert!(out.contains("new@example.test"));
        assert!(!out.contains("old@example.test") && !out.contains("Old Name"));
        assert!(out.contains("Subject: Hi\r\n\r\nBody\r\n"));
        assert_eq!(out.matches("From:").count(), 1);
    }
}