1use chrono::{SecondsFormat, Utc};
62use lettre::{
63 message::{header::ContentType, MultiPart},
64 AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor,
65};
66use serde::{Deserialize, Serialize};
67use serde_json::json;
68use slabs_core::{id, AppEnv, SlabError, SlabResult};
69use slabs_db::Db;
70use std::fmt;
71use std::time::Duration;
72
73const MAX_RESEND_ERROR_BYTES: usize = 4 * 1024;
74const SMTP_TIMEOUT: Duration = Duration::from_secs(15);
75
76#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct Email {
79 pub from: String,
81 pub to: String,
83 pub subject: String,
85 pub text_body: String,
87 pub html_body: Option<String>,
89}
90
91impl Email {
92 #[must_use]
94 pub fn html_markup(mut self, html: impl Into<String>) -> Self {
95 self.html_body = Some(html.into());
96 self
97 }
98}
99
100#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
102pub struct SentEmail {
103 pub id: String,
105 pub from_addr: String,
107 pub to_addr: String,
109 pub subject: String,
111 pub text_body: String,
113 pub html_body: Option<String>,
115 pub sent_at: String,
117}
118
119#[derive(Clone)]
121pub enum MailTransport {
122 OutboxOnly,
124 Resend {
126 api_key: String,
128 endpoint: String,
130 },
131 Smtp {
133 url: String,
135 },
136}
137
138impl fmt::Debug for MailTransport {
139 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140 match self {
141 Self::OutboxOnly => f.write_str("OutboxOnly"),
142 Self::Resend { endpoint, .. } => f
143 .debug_struct("Resend")
144 .field("api_key", &"<redacted>")
145 .field("endpoint", endpoint)
146 .finish(),
147 Self::Smtp { .. } => f.debug_struct("Smtp").field("url", &"<redacted>").finish(),
148 }
149 }
150}
151
152impl MailTransport {
153 #[must_use]
158 pub fn from_env() -> Self {
159 if let Ok(api_key) = std::env::var("SLABS_RESEND_API_KEY") {
160 if !api_key.trim().is_empty() {
161 let endpoint = std::env::var("SLABS_RESEND_URL")
162 .unwrap_or_else(|_| "https://api.resend.com/emails".to_string());
163 return Self::Resend { api_key, endpoint };
164 }
165 }
166 if let Ok(url) = std::env::var("SLABS_SMTP_URL") {
167 if !url.trim().is_empty() {
168 return Self::Smtp { url };
169 }
170 }
171 Self::OutboxOnly
172 }
173}
174
175#[derive(Debug, Clone)]
180pub struct Mailer {
181 db: Db,
182 default_from: String,
183 transport: MailTransport,
184 http: reqwest::Client,
185 allow_insecure_transport: bool,
186}
187
188impl Mailer {
189 #[must_use]
191 pub fn new(db: Db, default_from: impl Into<String>) -> Self {
192 Self::with_transport(db, default_from, MailTransport::OutboxOnly)
193 }
194
195 #[must_use]
197 pub fn with_transport(
198 db: Db,
199 default_from: impl Into<String>,
200 transport: MailTransport,
201 ) -> Self {
202 let http = reqwest::Client::builder()
203 .redirect(reqwest::redirect::Policy::none())
204 .timeout(Duration::from_secs(10))
205 .build()
206 .expect("failed to build reqwest client");
207 Self {
208 db,
209 default_from: default_from.into(),
210 transport,
211 http,
212 allow_insecure_transport: false,
213 }
214 }
215
216 #[must_use]
219 pub fn with_env(mut self, env: AppEnv) -> Self {
220 self.allow_insecure_transport = env.is_dev_or_test();
221 self
222 }
223
224 #[must_use]
226 pub fn with_allow_insecure_transport(mut self, allow: bool) -> Self {
227 self.allow_insecure_transport = allow;
228 self
229 }
230
231 pub fn default_from(&self) -> &str {
233 &self.default_from
234 }
235
236 pub fn transport(&self) -> &MailTransport {
238 &self.transport
239 }
240
241 pub async fn send(&self, email: Email) -> SlabResult<SentEmail> {
248 let from_addr = if email.from.is_empty() {
249 self.default_from.clone()
250 } else {
251 email.from
252 };
253
254 reject_header_injection("from", &from_addr)?;
255 reject_header_injection("to", &email.to)?;
256 reject_header_injection("subject", &email.subject)?;
257
258 let mail_id = id::new("eml");
259 let sent_at = Utc::now().to_rfc3339_opts(SecondsFormat::Micros, true);
260
261 match &self.transport {
262 MailTransport::OutboxOnly => {}
263 MailTransport::Resend { api_key, endpoint } => {
264 validate_resend_endpoint(endpoint, self.allow_insecure_transport)?;
265
266 let mut payload = json!({
267 "from": &from_addr,
268 "to": [&email.to],
269 "subject": &email.subject,
270 "text": &email.text_body,
271 });
272 if let Some(html) = &email.html_body {
273 payload["html"] = json!(html);
274 }
275
276 let resp = self
277 .http
278 .post(endpoint)
279 .bearer_auth(api_key)
280 .json(&payload)
281 .send()
282 .await
283 .map_err(|e| SlabError::internal(format!("resend request failed: {e}")))?;
284
285 if !resp.status().is_success() {
286 let status = resp.status();
287 let body = read_body_capped(resp, MAX_RESEND_ERROR_BYTES).await;
288 return Err(SlabError::internal(format!(
289 "resend API error {status}: {body}"
290 )));
291 }
292 }
293 MailTransport::Smtp { url } => {
294 validate_smtp_url(url, self.allow_insecure_transport)?;
295
296 let mailer = AsyncSmtpTransport::<Tokio1Executor>::from_url(url)
297 .map_err(|_| SlabError::internal("invalid SLABS_SMTP_URL configuration"))?
298 .timeout(Some(SMTP_TIMEOUT))
299 .build();
300
301 let builder =
302 Message::builder()
303 .from(from_addr.parse().map_err(|e| {
304 SlabError::bad_request(format!("invalid from addr: {e}"))
305 })?)
306 .to(email
307 .to
308 .parse()
309 .map_err(|e| SlabError::bad_request(format!("invalid to addr: {e}")))?)
310 .subject(&email.subject);
311
312 let msg = if let Some(html) = &email.html_body {
313 builder
314 .multipart(MultiPart::alternative_plain_html(
315 email.text_body.clone(),
316 html.clone(),
317 ))
318 .map_err(|e| SlabError::internal(format!("smtp build failed: {e}")))?
319 } else {
320 builder
321 .header(ContentType::TEXT_PLAIN)
322 .body(email.text_body.clone())
323 .map_err(|e| SlabError::internal(format!("smtp build failed: {e}")))?
324 };
325
326 mailer
327 .send(msg)
328 .await
329 .map_err(|e| SlabError::internal(format!("smtp send failed: {e}")))?;
330 }
331 }
332
333 let (stored_text, stored_html) = if matches!(self.transport, MailTransport::OutboxOnly) {
334 (email.text_body, email.html_body)
335 } else {
336 ("[redacted]".to_string(), None)
337 };
338
339 let record = SentEmail {
340 id: mail_id,
341 from_addr,
342 to_addr: email.to,
343 subject: email.subject,
344 text_body: stored_text,
345 html_body: stored_html,
346 sent_at,
347 };
348
349 sqlx::query(
350 "INSERT INTO slabs_mail_outbox (id, from_addr, to_addr, subject, text_body, html_body, sent_at)
351 VALUES (?, ?, ?, ?, ?, ?, ?)",
352 )
353 .bind(&record.id)
354 .bind(&record.from_addr)
355 .bind(&record.to_addr)
356 .bind(&record.subject)
357 .bind(&record.text_body)
358 .bind(&record.html_body)
359 .bind(&record.sent_at)
360 .execute(self.db.pool())
361 .await?;
362
363 let recipient_domain = recipient_domain(&record.to_addr);
364 tracing::info!(
365 mail_id = %record.id,
366 to_domain = %recipient_domain,
367 "email delivered"
368 );
369
370 Ok(record)
371 }
372
373 pub async fn list_sent(&self, limit: i64) -> SlabResult<Vec<SentEmail>> {
376 let clamped_limit = limit.clamp(1, 500);
377 let rows: Vec<SentEmail> = sqlx::query_as(
378 "SELECT id, from_addr, to_addr, subject, text_body, html_body, sent_at
379 FROM slabs_mail_outbox
380 ORDER BY sent_at DESC
381 LIMIT ?",
382 )
383 .bind(clamped_limit)
384 .fetch_all(self.db.reader())
385 .await?;
386 Ok(rows)
387 }
388}
389
390fn reject_header_injection(field: &str, value: &str) -> SlabResult<()> {
391 if value.bytes().any(|b| b == b'\r' || b == b'\n' || b == 0) {
392 return Err(SlabError::bad_request(format!(
393 "invalid control character in email {field}"
394 )));
395 }
396 Ok(())
397}
398
399fn validate_resend_endpoint(endpoint: &str, allow_insecure: bool) -> SlabResult<()> {
400 let trimmed = endpoint.trim();
401 if trimmed.starts_with("https://") {
402 return Ok(());
403 }
404 if allow_insecure && trimmed.starts_with("http://") {
405 return Ok(());
406 }
407 Err(SlabError::internal(
408 "Resend endpoint must use https:// in production environments",
409 ))
410}
411
412fn validate_smtp_url(url: &str, allow_insecure: bool) -> SlabResult<()> {
413 let trimmed = url.trim();
414 let lower = trimmed.to_ascii_lowercase();
415 let query = lower.split_once('?').map(|(_, q)| q);
416 let has_tls_none = query.is_some_and(|q| q.split('&').any(|p| p == "tls=none"));
417 let has_tls_required = query.is_some_and(|q| q.split('&').any(|p| p == "tls=required"));
418
419 if lower.starts_with("smtps://") {
420 if has_tls_none && !allow_insecure {
421 return Err(SlabError::internal(
422 "SMTP configuration error: tls=none is not permitted",
423 ));
424 }
425 return Ok(());
426 }
427 if lower.starts_with("smtp://") {
428 if allow_insecure {
429 return Ok(());
430 }
431 if has_tls_required && !has_tls_none {
432 return Ok(());
433 }
434 return Err(SlabError::internal(
435 "SMTP configuration error: production SMTP requires smtps:// or tls=required",
436 ));
437 }
438 Err(SlabError::internal(
439 "SMTP configuration error: unsupported URL scheme",
440 ))
441}
442
443fn recipient_domain(addr: &str) -> &str {
444 let trimmed = addr.trim().trim_end_matches('>');
445 trimmed
446 .rsplit_once('@')
447 .map_or("<unknown>", |(_, domain)| domain)
448}
449
450async fn read_body_capped(mut resp: reqwest::Response, max_bytes: usize) -> String {
451 let mut buf = Vec::new();
452 while let Ok(Some(chunk)) = resp.chunk().await {
453 let remaining = max_bytes.saturating_sub(buf.len());
454 if remaining == 0 {
455 break;
456 }
457 let take = chunk.len().min(remaining);
458 buf.extend_from_slice(&chunk[..take]);
459 if buf.len() >= max_bytes {
460 break;
461 }
462 }
463 String::from_utf8_lossy(&buf).into_owned()
464}
465
466#[cfg(test)]
467mod tests {
468 use super::*;
469 use axum::{extract::State, http::HeaderMap, routing::post, Json, Router};
470 use std::sync::{Arc, Mutex};
471
472 type CapturedRequest = Arc<Mutex<Option<(String, serde_json::Value)>>>;
473
474 #[tokio::test]
475 async fn resend_transport_sends_bearer_auth_json_body_and_redacts_outbox() {
476 let captured: CapturedRequest = Arc::new(Mutex::new(None));
477 let cap_clone = captured.clone();
478
479 let app = Router::new()
480 .route(
481 "/emails",
482 post(
483 |State(cap): State<CapturedRequest>,
484 headers: HeaderMap,
485 Json(body): Json<serde_json::Value>| async move {
486 let auth = headers
487 .get("authorization")
488 .and_then(|v| v.to_str().ok())
489 .unwrap_or("")
490 .to_string();
491 *cap.lock().unwrap() = Some((auth, body));
492 Json(json!({ "id": "re_123" }))
493 },
494 ),
495 )
496 .with_state(cap_clone);
497
498 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
499 let addr = listener.local_addr().unwrap();
500 tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
501
502 let db = Db::connect("sqlite::memory:").await.unwrap();
503 db.init_system_tables().await.unwrap();
504
505 let strict_mailer = Mailer::with_transport(
507 db.clone(),
508 "noreply@slabs.dev",
509 MailTransport::Resend {
510 api_key: "re_test_key".into(),
511 endpoint: format!("http://{addr}/emails"),
512 },
513 );
514 assert!(strict_mailer
515 .send(Email {
516 from: String::new(),
517 to: "dhh@37signals.com".into(),
518 subject: "Blocked".into(),
519 text_body: "Secret OTP 123456".into(),
520 html_body: None,
521 })
522 .await
523 .is_err());
524
525 let mailer = strict_mailer.with_allow_insecure_transport(true);
527 let sent = mailer
528 .send(
529 Email {
530 from: String::new(),
531 to: "dhh@37signals.com".into(),
532 subject: "Hello Resend".into(),
533 text_body: "Secret OTP 999888".into(),
534 html_body: None,
535 }
536 .html_markup("<p>Secret OTP 999888</p>"),
537 )
538 .await
539 .unwrap();
540
541 let (auth, body) = captured.lock().unwrap().clone().expect("request captured");
542 assert_eq!(auth, "Bearer re_test_key");
543 assert_eq!(body["to"][0], "dhh@37signals.com");
544 assert_eq!(body["subject"], "Hello Resend");
545 assert_eq!(body["html"], "<p>Secret OTP 999888</p>");
546
547 assert_eq!(sent.text_body, "[redacted]");
549 assert_eq!(sent.html_body, None);
550 let stored = mailer.list_sent(10).await.unwrap();
551 assert_eq!(stored.len(), 1);
552 assert_eq!(stored[0].text_body, "[redacted]");
553 assert_eq!(stored[0].html_body, None);
554 }
555
556 #[tokio::test]
557 async fn header_injection_is_rejected_for_from_to_and_subject() {
558 let db = Db::connect("sqlite::memory:").await.unwrap();
559 db.init_system_tables().await.unwrap();
560 let mailer = Mailer::new(db, "noreply@example.com");
561
562 for bad_email in [
563 Email {
564 from: "sender@example.com\r\nBcc: attacker@evil.com".into(),
565 to: "user@example.com".into(),
566 subject: "Hi".into(),
567 text_body: "Body".into(),
568 html_body: None,
569 },
570 Email {
571 from: String::new(),
572 to: "user@example.com\nCc: attacker@evil.com".into(),
573 subject: "Hi".into(),
574 text_body: "Body".into(),
575 html_body: None,
576 },
577 Email {
578 from: String::new(),
579 to: "user@example.com".into(),
580 subject: "Hi\0Injected".into(),
581 text_body: "Body".into(),
582 html_body: None,
583 },
584 ] {
585 let err = mailer.send(bad_email).await.unwrap_err();
586 assert_eq!(err.status_code(), axum::http::StatusCode::BAD_REQUEST);
587 }
588 assert!(mailer.list_sent(10).await.unwrap().is_empty());
589 }
590
591 #[tokio::test]
592 async fn smtp_rejects_insecure_urls_and_never_leaks_credentials() {
593 let db = Db::connect("sqlite::memory:").await.unwrap();
594 db.init_system_tables().await.unwrap();
595
596 for bad_url in [
597 "smtp://user:supersecretpw@smtp.example.com:25",
598 "smtp://user:supersecretpw@smtp.example.com:587?tls=none",
599 "smtps://user:supersecretpw@smtp.example.com:465?tls=none",
600 "ftp://user:supersecretpw@smtp.example.com",
601 ] {
602 let mailer = Mailer::with_transport(
603 db.clone(),
604 "noreply@example.com",
605 MailTransport::Smtp {
606 url: bad_url.into(),
607 },
608 );
609 let err = mailer
610 .send(Email {
611 from: String::new(),
612 to: "user@example.com".into(),
613 subject: "Test".into(),
614 text_body: "Hello".into(),
615 html_body: None,
616 })
617 .await
618 .unwrap_err();
619 assert!(!err.to_string().contains("supersecretpw"));
620 }
621
622 assert!(validate_smtp_url("smtps://user:pw@smtp.example.com:465", false).is_ok());
624 assert!(
625 validate_smtp_url("smtp://user:pw@smtp.example.com:587?tls=required", false).is_ok()
626 );
627 }
628
629 #[test]
630 fn mail_transport_debug_redacts_credentials() {
631 let resend = MailTransport::Resend {
632 api_key: "re_live_secret".into(),
633 endpoint: "https://api.resend.com/emails".into(),
634 };
635 let resend_dbg = format!("{resend:?}");
636 assert!(!resend_dbg.contains("re_live_secret"));
637 assert!(resend_dbg.contains("<redacted>"));
638 assert!(resend_dbg.contains("https://api.resend.com/emails"));
639
640 let smtp = MailTransport::Smtp {
641 url: "smtps://user:hunter2@smtp.example.com".into(),
642 };
643 let smtp_dbg = format!("{smtp:?}");
644 assert!(!smtp_dbg.contains("hunter2"));
645 assert!(smtp_dbg.contains("<redacted>"));
646 }
647}