mailman 0.2.0

SDK for mailman, a microservice that sends emails on your behalf over SMTP.
Documentation
use std::env;
use std::net::{Ipv6Addr, SocketAddr};
use std::sync::Arc;

use axum::{
    Router,
    extract::{Request, State},
    http::{StatusCode, header::AUTHORIZATION},
    middleware::{self, Next},
    response::{IntoResponse, Json, Response},
    routing::{get, post},
};
use base64::{Engine, engine::general_purpose::STANDARD};
use lettre::{
    AsyncSmtpTransport, AsyncTransport, Tokio1Executor,
    message::{Mailbox, Message, MultiPart, SinglePart, header::ContentType},
    transport::smtp::authentication::Credentials,
};
use mailman::{Attachment, ErrorResponse, SendEmailRequest, SendEmailResponse};
use utoipa::{
    Modify, OpenApi,
    openapi::security::{HttpAuthScheme, HttpBuilder, SecurityScheme},
};
use utoipa_swagger_ui::SwaggerUi;

struct AppState {
    mailer: AsyncSmtpTransport<Tokio1Executor>,
    default_from: Option<Mailbox>,
    token: Option<String>,
}

/// How mailman negotiates TLS with the SMTP server. Configured via
/// `SMTP_ENCRYPTION`.
enum Encryption {
    /// Connect in the clear, then upgrade with STARTTLS (typically port 587).
    StartTls,
    /// Connect over implicit TLS from the first byte (typically port 465).
    Tls,
    /// No TLS at all. Only sensible for a local relay in development.
    None,
}

#[derive(OpenApi)]
#[openapi(
    info(
        title = "Mailman API",
        description = "Send email through Mailman. Bearer authentication is required unless MAILMAN_REQUIRE_API_TOKEN is disabled."
    ),
    paths(health, send),
    components(schemas(
        Attachment,
        SendEmailRequest,
        SendEmailResponse,
        ErrorResponse
    )),
    modifiers(&SecurityAddon),
    tags((name = "mail", description = "Email delivery endpoints"))
)]
struct ApiDoc;

struct SecurityAddon;

impl Modify for SecurityAddon {
    fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) {
        if let Some(components) = openapi.components.as_mut() {
            components.add_security_scheme(
                "bearer_auth",
                SecurityScheme::Http(
                    HttpBuilder::new()
                        .scheme(HttpAuthScheme::Bearer)
                        .bearer_format("API token")
                        .build(),
                ),
            );
        }
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let _ = dotenvy::dotenv();

    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
        )
        .init();

    let require_api_token = env::var("MAILMAN_REQUIRE_API_TOKEN")
        .ok()
        .map(|value| parse_bool("MAILMAN_REQUIRE_API_TOKEN", &value))
        .transpose()?
        .unwrap_or(true);
    let token = if require_api_token {
        Some(
            env::var("MAILMAN_API_TOKEN")
                .ok()
                .filter(|s| !s.is_empty())
                .ok_or("MAILMAN_API_TOKEN must be set when MAILMAN_REQUIRE_API_TOKEN is true")?,
        )
    } else {
        tracing::warn!("API token authentication is disabled");
        None
    };

    let host = env::var("SMTP_HOST").map_err(|_| "SMTP_HOST must be set")?;
    let smtp_port: u16 = env::var("SMTP_PORT")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(587);
    let encryption = match env::var("SMTP_ENCRYPTION")
        .unwrap_or_else(|_| "starttls".to_string())
        .to_lowercase()
        .as_str()
    {
        "starttls" => Encryption::StartTls,
        "tls" | "ssl" | "implicit" => Encryption::Tls,
        "none" | "plain" => Encryption::None,
        other => return Err(format!("unknown SMTP_ENCRYPTION: {other}").into()),
    };

    let default_from = match env::var("SMTP_FROM").ok().filter(|s| !s.is_empty()) {
        Some(from) => Some(
            from.parse::<Mailbox>()
                .map_err(|e| format!("invalid SMTP_FROM ({from:?}): {e}"))?,
        ),
        None => {
            tracing::warn!(
                "SMTP_FROM unset — every /send request must supply its own \"from\" address"
            );
            None
        }
    };

    let mut builder = match encryption {
        Encryption::StartTls => AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&host)?,
        Encryption::Tls => AsyncSmtpTransport::<Tokio1Executor>::relay(&host)?,
        Encryption::None => AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(&host),
    }
    .port(smtp_port);

    // Only attach credentials when both are present; some local relays accept
    // unauthenticated mail.
    let username = env::var("SMTP_USERNAME").ok().filter(|s| !s.is_empty());
    let password = env::var("SMTP_PASSWORD").ok().filter(|s| !s.is_empty());
    if let (Some(username), Some(password)) = (username, password) {
        builder = builder.credentials(Credentials::new(username, password));
    } else {
        tracing::warn!("SMTP_USERNAME/SMTP_PASSWORD unset — sending without authentication");
    }

    let mailer = builder.build();

    let state = Arc::new(AppState {
        mailer,
        default_from,
        token,
    });

    let app = Router::new()
        .route(
            "/send",
            post(send).route_layer(middleware::from_fn_with_state(state.clone(), require_token)),
        )
        .route("/health", get(health))
        .merge(SwaggerUi::new("/swagger-ui").url("/api-docs/openapi.json", ApiDoc::openapi()))
        .layer(middleware::from_fn(log_requests))
        .with_state(state);

    let port: u16 = env::var("PORT")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(8080);
    let addr = SocketAddr::from((Ipv6Addr::UNSPECIFIED, port));
    tracing::info!("listening on {addr} (SMTP relay: {host}:{smtp_port})");

    let listener = tokio::net::TcpListener::bind(addr).await?;
    axum::serve(listener, app).await?;
    Ok(())
}

#[utoipa::path(
    get,
    path = "/health",
    tag = "mail",
    responses(
        (status = 200, description = "Service is running", body = String, content_type = "text/plain")
    )
)]
async fn health() -> &'static str {
    "ok"
}

fn parse_bool(name: &str, value: &str) -> Result<bool, String> {
    match value.trim().to_ascii_lowercase().as_str() {
        "true" | "1" | "yes" | "on" => Ok(true),
        "false" | "0" | "no" | "off" => Ok(false),
        _ => Err(format!(
            "{name} must be one of true, false, 1, 0, yes, no, on, or off"
        )),
    }
}

async fn log_requests(req: Request, next: Next) -> Response {
    let method = req.method().clone();
    let uri = req.uri().clone();
    let response = next.run(req).await;
    tracing::info!("{method} {uri} -> {}", response.status());
    response
}

/// When token authentication is enabled, rejects requests without an
/// `Authorization: Bearer <token>` header matching `MAILMAN_API_TOKEN`.
async fn require_token(
    State(state): State<Arc<AppState>>,
    req: Request,
    next: Next,
) -> Result<Response, ApiError> {
    let Some(expected) = state.token.as_deref() else {
        return Ok(next.run(req).await);
    };

    let provided = req
        .headers()
        .get(AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.strip_prefix("Bearer "));

    if provided != Some(expected) {
        return Err(ApiError::new(
            StatusCode::UNAUTHORIZED,
            "invalid or missing bearer token",
        ));
    }

    Ok(next.run(req).await)
}

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

    #[test]
    fn parses_boolean_environment_values() {
        for value in ["true", "TRUE", "1", "yes", "on"] {
            assert_eq!(parse_bool("FLAG", value), Ok(true));
        }
        for value in ["false", "FALSE", "0", "no", "off"] {
            assert_eq!(parse_bool("FLAG", value), Ok(false));
        }
        assert!(parse_bool("FLAG", "sometimes").is_err());
    }
}

#[utoipa::path(
    post,
    path = "/send",
    tag = "mail",
    request_body = SendEmailRequest,
    security(("bearer_auth" = [])),
    responses(
        (status = 200, description = "Email accepted and delivered by the SMTP relay", body = SendEmailResponse),
        (status = 400, description = "Invalid request or email data", body = ErrorResponse),
        (status = 401, description = "Missing or invalid bearer token", body = ErrorResponse),
        (status = 502, description = "SMTP relay rejected the message", body = ErrorResponse)
    )
)]
async fn send(
    State(state): State<Arc<AppState>>,
    Json(req): Json<SendEmailRequest>,
) -> Result<Json<SendEmailResponse>, ApiError> {
    if req.to.is_empty() {
        return Err(ApiError::new(
            StatusCode::BAD_REQUEST,
            "at least one \"to\" recipient is required",
        ));
    }

    // Resolve the From address: per-request override, else the server default.
    let from = match &req.from {
        Some(from) => from
            .parse::<Mailbox>()
            .map_err(|e| ApiError::new(StatusCode::BAD_REQUEST, format!("invalid from: {e}")))?,
        None => state.default_from.clone().ok_or_else(|| {
            ApiError::new(
                StatusCode::BAD_REQUEST,
                "no \"from\" address supplied and SMTP_FROM is not configured",
            )
        })?,
    };

    let mut builder = Message::builder().from(from).subject(req.subject.as_str());

    let total_recipients = req.to.len() + req.cc.len();
    for to in &req.to {
        let mailbox = to.parse::<Mailbox>().map_err(|e| {
            ApiError::new(StatusCode::BAD_REQUEST, format!("invalid to ({to}): {e}"))
        })?;
        builder = builder.to(mailbox);
    }
    for cc in &req.cc {
        let mailbox = cc.parse::<Mailbox>().map_err(|e| {
            ApiError::new(StatusCode::BAD_REQUEST, format!("invalid cc ({cc}): {e}"))
        })?;
        builder = builder.cc(mailbox);
    }

    // The body part is either plain text or HTML.
    let body_part = if req.html {
        SinglePart::html(req.body.clone())
    } else {
        SinglePart::plain(req.body.clone())
    };

    let email = if req.attachments.is_empty() {
        builder.singlepart(body_part)
    } else {
        let mut multipart = MultiPart::mixed().singlepart(body_part);
        for attachment in &req.attachments {
            let bytes = STANDARD
                .decode(attachment.content.as_bytes())
                .map_err(|e| {
                    ApiError::new(
                        StatusCode::BAD_REQUEST,
                        format!(
                            "attachment {} is not valid base64: {e}",
                            attachment.filename
                        ),
                    )
                })?;
            let content_type = ContentType::parse(&attachment.content_type).map_err(|e| {
                ApiError::new(
                    StatusCode::BAD_REQUEST,
                    format!(
                        "attachment {} has an invalid content_type ({}): {e}",
                        attachment.filename, attachment.content_type
                    ),
                )
            })?;
            multipart = multipart.singlepart(
                lettre::message::Attachment::new(attachment.filename.clone())
                    .body(bytes, content_type),
            );
        }
        builder.multipart(multipart)
    }
    .map_err(|e| {
        ApiError::new(
            StatusCode::BAD_REQUEST,
            format!("failed to build email: {e}"),
        )
    })?;

    state.mailer.send(email).await.map_err(|e| {
        tracing::error!("failed to send email: {e}");
        ApiError::new(
            StatusCode::BAD_GATEWAY,
            format!("failed to send email: {e}"),
        )
    })?;

    tracing::info!(
        "sent \"{}\" to {} recipient(s)",
        req.subject,
        total_recipients
    );

    Ok(Json(SendEmailResponse {
        status: "sent".to_string(),
        message: format!("delivered to {total_recipients} recipient(s)"),
    }))
}

/// An error that renders as `{"error": "..."}` with a status code, matching the
/// shape geodude's handlers return.
struct ApiError {
    status: StatusCode,
    message: String,
}

impl ApiError {
    fn new(status: StatusCode, message: impl Into<String>) -> Self {
        Self {
            status,
            message: message.into(),
        }
    }
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        (
            self.status,
            Json(ErrorResponse {
                error: self.message,
            }),
        )
            .into_response()
    }
}