slabs-mail 0.3.0

Low-level transactional mailer battery with SQLite dev/test outbox, Resend HTTP, and SMTP (lettre) transports
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! Transactional email delivery and SQLite outbox logging for Slabs applications.
//!
//! # Owned table and environment variables
//!
//! This crate logs every sent message to the `slabs_mail_outbox` table created by
//! `Db::init_system_tables`.
//! Each row stores `id` (`eml_<ulid>`), `from_addr`, `to_addr`, `subject`, `text_body`,
//! `html_body`, and `sent_at`.
//!
//! [`MailTransport::from_env`] selects a delivery backend in this order:
//!
//! - `SLABS_RESEND_API_KEY`: selects [`MailTransport::Resend`]. Set `SLABS_RESEND_URL` to
//!   override the default `https://api.resend.com/emails` endpoint.
//! - `SLABS_SMTP_URL`: selects [`MailTransport::Smtp`] via `lettre` (for example
//!   `smtps://user:pass@smtp.host`).
//! - Neither variable set: selects [`MailTransport::OutboxOnly`].
//!
//! # Agent invariants
//!
//! - [`Mailer::send`] validates `from`, `to`, and `subject` against header-injection control bytes
//!   (`\r`, `\n`, `\0`) before doing any network or database I/O.
//! - [`Mailer::send`] performs network I/O for Resend and SMTP transports before writing to
//!   `slabs_mail_outbox`. It does not participate in a SQLite transaction.
//! - For live transports ([`MailTransport::Resend`] and [`MailTransport::Smtp`]), the persisted
//!   outbox row stores `"[redacted]"` for `text_body` and `None` for `html_body` so production
//!   OTPs and password-reset links are never persisted in plaintext.
//! - To send email atomically with a domain write, enqueue a job via
//!   `ctx.jobs.enqueue_in_tx(&mut tx, ...)` and call [`Mailer::send`] inside the job handler.
//! - In development and tests, [`MailTransport::OutboxOnly`] makes no network calls and stores
//!   every message in `slabs_mail_outbox`. Inspect sent mail via [`Mailer::list_sent`],
//!   `TestApp::sent_emails` in tests, or `GET /_slabs/mail` in development.
//! - Leave [`Email::from`] empty to fall back to [`Mailer::default_from`].
//!
//! # Example
//!
//! ```rust,no_run
//! use slabs_db::Db;
//! use slabs_mail::{Email, MailTransport, Mailer};
//!
//! # async fn run() -> slabs_core::SlabResult<()> {
//! let db = Db::connect("sqlite::memory:").await?;
//! db.init_system_tables().await?;
//!
//! let mailer = Mailer::with_transport(db, "noreply@example.com", MailTransport::from_env());
//! mailer
//!     .send(Email {
//!         from: String::new(),
//!         to: "user@example.com".into(),
//!         subject: "Sign in to Slabs".into(),
//!         text_body: "Use this link to sign in.".into(),
//!         html_body: Some("<p>Use this link to sign in.</p>".into()),
//!     })
//!     .await?;
//!
//! let sent = mailer.list_sent(10).await?;
//! assert_eq!(sent.len(), 1);
//! # Ok(())
//! # }
//! ```

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);

/// Outgoing email message passed to [`Mailer::send`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Email {
    /// Sender address. Uses [`Mailer::default_from`] when empty.
    pub from: String,
    /// Recipient email address.
    pub to: String,
    /// Message subject line.
    pub subject: String,
    /// Plain-text message body.
    pub text_body: String,
    /// Optional HTML alternative body.
    pub html_body: Option<String>,
}

impl Email {
    /// Attach an HTML alternative body to this [`Email`] and return it.
    #[must_use]
    pub fn html_markup(mut self, html: impl Into<String>) -> Self {
        self.html_body = Some(html.into());
        self
    }
}

/// Persisted record of a sent email in the `slabs_mail_outbox` table.
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct SentEmail {
    /// Unique email identifier (`eml_<ulid>`).
    pub id: String,
    /// Resolved sender email address.
    pub from_addr: String,
    /// Recipient email address.
    pub to_addr: String,
    /// Message subject line.
    pub subject: String,
    /// Plain-text message body (`"[redacted]"` for non-`OutboxOnly` transports).
    pub text_body: String,
    /// Optional HTML alternative body (`None` for non-`OutboxOnly` transports).
    pub html_body: Option<String>,
    /// RFC 3339 UTC timestamp when [`Mailer::send`] recorded the message.
    pub sent_at: String,
}

/// Delivery backend used by [`Mailer`].
#[derive(Clone)]
pub enum MailTransport {
    /// Development and test default. Persists rows to `slabs_mail_outbox` without network I/O.
    OutboxOnly,
    /// HTTP delivery through the Resend API (`SLABS_RESEND_API_KEY`).
    Resend {
        /// Bearer API key for the Resend API.
        api_key: String,
        /// Resend email submission endpoint URL.
        endpoint: String,
    },
    /// SMTP delivery through `lettre` (`SLABS_SMTP_URL`, for example `smtps://user:pass@smtp.host`).
    Smtp {
        /// SMTP connection URL parsed by `lettre`.
        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 {
    /// Detect the mail transport from `SLABS_RESEND_API_KEY` or `SLABS_SMTP_URL`.
    ///
    /// Checks `SLABS_RESEND_API_KEY` first, then `SLABS_SMTP_URL`, and defaults to
    /// [`MailTransport::OutboxOnly`].
    #[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
    }
}

/// Outbound email client backed by [`MailTransport`] and `slabs_mail_outbox`.
///
/// Delivers each message through the configured transport and records metadata in
/// `slabs_mail_outbox` (redacting message bodies for live network transports).
#[derive(Debug, Clone)]
pub struct Mailer {
    db: Db,
    default_from: String,
    transport: MailTransport,
    http: reqwest::Client,
    allow_insecure_transport: bool,
}

impl Mailer {
    /// Create a mailer using [`MailTransport::OutboxOnly`].
    #[must_use]
    pub fn new(db: Db, default_from: impl Into<String>) -> Self {
        Self::with_transport(db, default_from, MailTransport::OutboxOnly)
    }

    /// Create a mailer with an explicit [`MailTransport`] backend, no HTTP redirects, and a 10-second HTTP timeout.
    #[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,
        }
    }

    /// Configure whether insecure transports (`http://` Resend endpoints or plaintext `smtp://`)
    /// are allowed based on [`AppEnv::is_dev_or_test`].
    #[must_use]
    pub fn with_env(mut self, env: AppEnv) -> Self {
        self.allow_insecure_transport = env.is_dev_or_test();
        self
    }

    /// Explicitly enable or disable insecure transport URLs (`http://` Resend or plaintext `smtp://`).
    #[must_use]
    pub fn with_allow_insecure_transport(mut self, allow: bool) -> Self {
        self.allow_insecure_transport = allow;
        self
    }

    /// Return the default sender address used when [`Email::from`] is empty.
    pub fn default_from(&self) -> &str {
        &self.default_from
    }

    /// Return the configured [`MailTransport`] backend.
    pub fn transport(&self) -> &MailTransport {
        &self.transport
    }

    /// Deliver `email` via the active transport and insert a row into `slabs_mail_outbox`.
    ///
    /// Rejects `\r`, `\n`, and `\0` in `from`, `to`, and `subject` with HTTP 400.
    /// Returns an error without inserting into `slabs_mail_outbox` if Resend or SMTP delivery fails.
    /// For live transports (`Resend` and `Smtp`), stores `"[redacted]"` for `text_body` and `None`
    /// for `html_body` in `slabs_mail_outbox`.
    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)
    }

    /// Return up to `limit` (clamped to `1..=500`) rows from `slabs_mail_outbox` on the read pool,
    /// ordered from newest to oldest `sent_at`.
    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();

        // In production mode (allow_insecure_transport = false), http:// Resend endpoint is rejected.
        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());

        // With allow_insecure_transport enabled (dev/test), delivery succeeds and outbox redacts bodies.
        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>");

        // Persisted outbox row MUST redact text_body and clear html_body.
        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"));
        }

        // Valid production SMTP URLs pass URL validation.
        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>"));
    }
}