use chrono::{SecondsFormat, Utc};
use lettre::{
message::{header::ContentType, MultiPart},
AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor,
};
use serde::{Deserialize, Serialize};
use serde_json::json;
use slabs_core::{id, AppEnv, SlabError, SlabResult};
use slabs_db::Db;
use std::fmt;
use std::time::Duration;
const MAX_RESEND_ERROR_BYTES: usize = 4 * 1024;
const SMTP_TIMEOUT: Duration = Duration::from_secs(15);
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Email {
pub from: String,
pub to: String,
pub subject: String,
pub text_body: String,
pub html_body: Option<String>,
}
impl Email {
#[must_use]
pub fn html_markup(mut self, html: impl Into<String>) -> Self {
self.html_body = Some(html.into());
self
}
}
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct SentEmail {
pub id: String,
pub from_addr: String,
pub to_addr: String,
pub subject: String,
pub text_body: String,
pub html_body: Option<String>,
pub sent_at: String,
}
#[derive(Clone)]
pub enum MailTransport {
OutboxOnly,
Resend {
api_key: String,
endpoint: String,
},
Smtp {
url: String,
},
}
impl fmt::Debug for MailTransport {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::OutboxOnly => f.write_str("OutboxOnly"),
Self::Resend { endpoint, .. } => f
.debug_struct("Resend")
.field("api_key", &"<redacted>")
.field("endpoint", endpoint)
.finish(),
Self::Smtp { .. } => f.debug_struct("Smtp").field("url", &"<redacted>").finish(),
}
}
}
impl MailTransport {
#[must_use]
pub fn from_env() -> Self {
if let Ok(api_key) = std::env::var("SLABS_RESEND_API_KEY") {
if !api_key.trim().is_empty() {
let endpoint = std::env::var("SLABS_RESEND_URL")
.unwrap_or_else(|_| "https://api.resend.com/emails".to_string());
return Self::Resend { api_key, endpoint };
}
}
if let Ok(url) = std::env::var("SLABS_SMTP_URL") {
if !url.trim().is_empty() {
return Self::Smtp { url };
}
}
Self::OutboxOnly
}
}
#[derive(Debug, Clone)]
pub struct Mailer {
db: Db,
default_from: String,
transport: MailTransport,
http: reqwest::Client,
allow_insecure_transport: bool,
}
impl Mailer {
#[must_use]
pub fn new(db: Db, default_from: impl Into<String>) -> Self {
Self::with_transport(db, default_from, MailTransport::OutboxOnly)
}
#[must_use]
pub fn with_transport(
db: Db,
default_from: impl Into<String>,
transport: MailTransport,
) -> Self {
let http = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.timeout(Duration::from_secs(10))
.build()
.expect("failed to build reqwest client");
Self {
db,
default_from: default_from.into(),
transport,
http,
allow_insecure_transport: false,
}
}
#[must_use]
pub fn with_env(mut self, env: AppEnv) -> Self {
self.allow_insecure_transport = env.is_dev_or_test();
self
}
#[must_use]
pub fn with_allow_insecure_transport(mut self, allow: bool) -> Self {
self.allow_insecure_transport = allow;
self
}
pub fn default_from(&self) -> &str {
&self.default_from
}
pub fn transport(&self) -> &MailTransport {
&self.transport
}
pub async fn send(&self, email: Email) -> SlabResult<SentEmail> {
let from_addr = if email.from.is_empty() {
self.default_from.clone()
} else {
email.from
};
reject_header_injection("from", &from_addr)?;
reject_header_injection("to", &email.to)?;
reject_header_injection("subject", &email.subject)?;
let mail_id = id::new("eml");
let sent_at = Utc::now().to_rfc3339_opts(SecondsFormat::Micros, true);
match &self.transport {
MailTransport::OutboxOnly => {}
MailTransport::Resend { api_key, endpoint } => {
validate_resend_endpoint(endpoint, self.allow_insecure_transport)?;
let mut payload = json!({
"from": &from_addr,
"to": [&email.to],
"subject": &email.subject,
"text": &email.text_body,
});
if let Some(html) = &email.html_body {
payload["html"] = json!(html);
}
let resp = self
.http
.post(endpoint)
.bearer_auth(api_key)
.json(&payload)
.send()
.await
.map_err(|e| SlabError::internal(format!("resend request failed: {e}")))?;
if !resp.status().is_success() {
let status = resp.status();
let body = read_body_capped(resp, MAX_RESEND_ERROR_BYTES).await;
return Err(SlabError::internal(format!(
"resend API error {status}: {body}"
)));
}
}
MailTransport::Smtp { url } => {
validate_smtp_url(url, self.allow_insecure_transport)?;
let mailer = AsyncSmtpTransport::<Tokio1Executor>::from_url(url)
.map_err(|_| SlabError::internal("invalid SLABS_SMTP_URL configuration"))?
.timeout(Some(SMTP_TIMEOUT))
.build();
let builder =
Message::builder()
.from(from_addr.parse().map_err(|e| {
SlabError::bad_request(format!("invalid from addr: {e}"))
})?)
.to(email
.to
.parse()
.map_err(|e| SlabError::bad_request(format!("invalid to addr: {e}")))?)
.subject(&email.subject);
let msg = if let Some(html) = &email.html_body {
builder
.multipart(MultiPart::alternative_plain_html(
email.text_body.clone(),
html.clone(),
))
.map_err(|e| SlabError::internal(format!("smtp build failed: {e}")))?
} else {
builder
.header(ContentType::TEXT_PLAIN)
.body(email.text_body.clone())
.map_err(|e| SlabError::internal(format!("smtp build failed: {e}")))?
};
mailer
.send(msg)
.await
.map_err(|e| SlabError::internal(format!("smtp send failed: {e}")))?;
}
}
let (stored_text, stored_html) = if matches!(self.transport, MailTransport::OutboxOnly) {
(email.text_body, email.html_body)
} else {
("[redacted]".to_string(), None)
};
let record = SentEmail {
id: mail_id,
from_addr,
to_addr: email.to,
subject: email.subject,
text_body: stored_text,
html_body: stored_html,
sent_at,
};
sqlx::query(
"INSERT INTO slabs_mail_outbox (id, from_addr, to_addr, subject, text_body, html_body, sent_at)
VALUES (?, ?, ?, ?, ?, ?, ?)",
)
.bind(&record.id)
.bind(&record.from_addr)
.bind(&record.to_addr)
.bind(&record.subject)
.bind(&record.text_body)
.bind(&record.html_body)
.bind(&record.sent_at)
.execute(self.db.pool())
.await?;
let recipient_domain = recipient_domain(&record.to_addr);
tracing::info!(
mail_id = %record.id,
to_domain = %recipient_domain,
"email delivered"
);
Ok(record)
}
pub async fn list_sent(&self, limit: i64) -> SlabResult<Vec<SentEmail>> {
let clamped_limit = limit.clamp(1, 500);
let rows: Vec<SentEmail> = sqlx::query_as(
"SELECT id, from_addr, to_addr, subject, text_body, html_body, sent_at
FROM slabs_mail_outbox
ORDER BY sent_at DESC
LIMIT ?",
)
.bind(clamped_limit)
.fetch_all(self.db.reader())
.await?;
Ok(rows)
}
}
fn reject_header_injection(field: &str, value: &str) -> SlabResult<()> {
if value.bytes().any(|b| b == b'\r' || b == b'\n' || b == 0) {
return Err(SlabError::bad_request(format!(
"invalid control character in email {field}"
)));
}
Ok(())
}
fn validate_resend_endpoint(endpoint: &str, allow_insecure: bool) -> SlabResult<()> {
let trimmed = endpoint.trim();
if trimmed.starts_with("https://") {
return Ok(());
}
if allow_insecure && trimmed.starts_with("http://") {
return Ok(());
}
Err(SlabError::internal(
"Resend endpoint must use https:// in production environments",
))
}
fn validate_smtp_url(url: &str, allow_insecure: bool) -> SlabResult<()> {
let trimmed = url.trim();
let lower = trimmed.to_ascii_lowercase();
let query = lower.split_once('?').map(|(_, q)| q);
let has_tls_none = query.is_some_and(|q| q.split('&').any(|p| p == "tls=none"));
let has_tls_required = query.is_some_and(|q| q.split('&').any(|p| p == "tls=required"));
if lower.starts_with("smtps://") {
if has_tls_none && !allow_insecure {
return Err(SlabError::internal(
"SMTP configuration error: tls=none is not permitted",
));
}
return Ok(());
}
if lower.starts_with("smtp://") {
if allow_insecure {
return Ok(());
}
if has_tls_required && !has_tls_none {
return Ok(());
}
return Err(SlabError::internal(
"SMTP configuration error: production SMTP requires smtps:// or tls=required",
));
}
Err(SlabError::internal(
"SMTP configuration error: unsupported URL scheme",
))
}
fn recipient_domain(addr: &str) -> &str {
let trimmed = addr.trim().trim_end_matches('>');
trimmed
.rsplit_once('@')
.map_or("<unknown>", |(_, domain)| domain)
}
async fn read_body_capped(mut resp: reqwest::Response, max_bytes: usize) -> String {
let mut buf = Vec::new();
while let Ok(Some(chunk)) = resp.chunk().await {
let remaining = max_bytes.saturating_sub(buf.len());
if remaining == 0 {
break;
}
let take = chunk.len().min(remaining);
buf.extend_from_slice(&chunk[..take]);
if buf.len() >= max_bytes {
break;
}
}
String::from_utf8_lossy(&buf).into_owned()
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{extract::State, http::HeaderMap, routing::post, Json, Router};
use std::sync::{Arc, Mutex};
type CapturedRequest = Arc<Mutex<Option<(String, serde_json::Value)>>>;
#[tokio::test]
async fn resend_transport_sends_bearer_auth_json_body_and_redacts_outbox() {
let captured: CapturedRequest = Arc::new(Mutex::new(None));
let cap_clone = captured.clone();
let app = Router::new()
.route(
"/emails",
post(
|State(cap): State<CapturedRequest>,
headers: HeaderMap,
Json(body): Json<serde_json::Value>| async move {
let auth = headers
.get("authorization")
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_string();
*cap.lock().unwrap() = Some((auth, body));
Json(json!({ "id": "re_123" }))
},
),
)
.with_state(cap_clone);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let db = Db::connect("sqlite::memory:").await.unwrap();
db.init_system_tables().await.unwrap();
let strict_mailer = Mailer::with_transport(
db.clone(),
"noreply@slabs.dev",
MailTransport::Resend {
api_key: "re_test_key".into(),
endpoint: format!("http://{addr}/emails"),
},
);
assert!(strict_mailer
.send(Email {
from: String::new(),
to: "dhh@37signals.com".into(),
subject: "Blocked".into(),
text_body: "Secret OTP 123456".into(),
html_body: None,
})
.await
.is_err());
let mailer = strict_mailer.with_allow_insecure_transport(true);
let sent = mailer
.send(
Email {
from: String::new(),
to: "dhh@37signals.com".into(),
subject: "Hello Resend".into(),
text_body: "Secret OTP 999888".into(),
html_body: None,
}
.html_markup("<p>Secret OTP 999888</p>"),
)
.await
.unwrap();
let (auth, body) = captured.lock().unwrap().clone().expect("request captured");
assert_eq!(auth, "Bearer re_test_key");
assert_eq!(body["to"][0], "dhh@37signals.com");
assert_eq!(body["subject"], "Hello Resend");
assert_eq!(body["html"], "<p>Secret OTP 999888</p>");
assert_eq!(sent.text_body, "[redacted]");
assert_eq!(sent.html_body, None);
let stored = mailer.list_sent(10).await.unwrap();
assert_eq!(stored.len(), 1);
assert_eq!(stored[0].text_body, "[redacted]");
assert_eq!(stored[0].html_body, None);
}
#[tokio::test]
async fn header_injection_is_rejected_for_from_to_and_subject() {
let db = Db::connect("sqlite::memory:").await.unwrap();
db.init_system_tables().await.unwrap();
let mailer = Mailer::new(db, "noreply@example.com");
for bad_email in [
Email {
from: "sender@example.com\r\nBcc: attacker@evil.com".into(),
to: "user@example.com".into(),
subject: "Hi".into(),
text_body: "Body".into(),
html_body: None,
},
Email {
from: String::new(),
to: "user@example.com\nCc: attacker@evil.com".into(),
subject: "Hi".into(),
text_body: "Body".into(),
html_body: None,
},
Email {
from: String::new(),
to: "user@example.com".into(),
subject: "Hi\0Injected".into(),
text_body: "Body".into(),
html_body: None,
},
] {
let err = mailer.send(bad_email).await.unwrap_err();
assert_eq!(err.status_code(), axum::http::StatusCode::BAD_REQUEST);
}
assert!(mailer.list_sent(10).await.unwrap().is_empty());
}
#[tokio::test]
async fn smtp_rejects_insecure_urls_and_never_leaks_credentials() {
let db = Db::connect("sqlite::memory:").await.unwrap();
db.init_system_tables().await.unwrap();
for bad_url in [
"smtp://user:supersecretpw@smtp.example.com:25",
"smtp://user:supersecretpw@smtp.example.com:587?tls=none",
"smtps://user:supersecretpw@smtp.example.com:465?tls=none",
"ftp://user:supersecretpw@smtp.example.com",
] {
let mailer = Mailer::with_transport(
db.clone(),
"noreply@example.com",
MailTransport::Smtp {
url: bad_url.into(),
},
);
let err = mailer
.send(Email {
from: String::new(),
to: "user@example.com".into(),
subject: "Test".into(),
text_body: "Hello".into(),
html_body: None,
})
.await
.unwrap_err();
assert!(!err.to_string().contains("supersecretpw"));
}
assert!(validate_smtp_url("smtps://user:pw@smtp.example.com:465", false).is_ok());
assert!(
validate_smtp_url("smtp://user:pw@smtp.example.com:587?tls=required", false).is_ok()
);
}
#[test]
fn mail_transport_debug_redacts_credentials() {
let resend = MailTransport::Resend {
api_key: "re_live_secret".into(),
endpoint: "https://api.resend.com/emails".into(),
};
let resend_dbg = format!("{resend:?}");
assert!(!resend_dbg.contains("re_live_secret"));
assert!(resend_dbg.contains("<redacted>"));
assert!(resend_dbg.contains("https://api.resend.com/emails"));
let smtp = MailTransport::Smtp {
url: "smtps://user:hunter2@smtp.example.com".into(),
};
let smtp_dbg = format!("{smtp:?}");
assert!(!smtp_dbg.contains("hunter2"));
assert!(smtp_dbg.contains("<redacted>"));
}
}