Skip to main content

cratefield_core/ports/
mailer.rs

1//! The `Mailer` port (architecture section 5). The Resend adapter is the
2//! reference implementation (issue #6).
3
4use async_trait::async_trait;
5use std::time::Duration;
6
7/// An outbound mail. `text` is always sent alongside `html`.
8///
9/// `#[non_exhaustive]`: build one with [`Message::new`] and the builder
10/// methods rather than a struct literal. A channel that has to set a
11/// header — RFC 8058 one-click unsubscribe, say — should not be a
12/// breaking change for every other caller, and before this it was.
13#[derive(Debug, Clone)]
14#[non_exhaustive]
15pub struct Message {
16    pub to: String,
17    pub from: String,
18    pub reply_to: Option<String>,
19    pub subject: String,
20    pub html: String,
21    pub text: String,
22    /// Passed through as an `Idempotency-Key` where the provider supports it.
23    pub idempotency_key: Option<String>,
24    pub tags: Vec<String>,
25    /// Extra RFC 5322 headers, in order.
26    ///
27    /// For headers the shape of `Message` does not name and should not:
28    /// `List-Unsubscribe` and `List-Unsubscribe-Post` are the reason this
29    /// exists, because Gmail and Yahoo have required one-click
30    /// unsubscribe of bulk senders since 2024. An adapter that cannot
31    /// send custom headers must say so rather than drop them silently.
32    pub headers: Vec<(String, String)>,
33}
34
35impl Message {
36    /// The five parts every mail has. Everything else is a builder method.
37    #[must_use]
38    pub fn new(
39        to: impl Into<String>,
40        from: impl Into<String>,
41        subject: impl Into<String>,
42        text: impl Into<String>,
43        html: impl Into<String>,
44    ) -> Self {
45        Self {
46            to: to.into(),
47            from: from.into(),
48            reply_to: None,
49            subject: subject.into(),
50            html: html.into(),
51            text: text.into(),
52            idempotency_key: None,
53            tags: Vec::new(),
54            headers: Vec::new(),
55        }
56    }
57
58    /// Where a reply goes, when it is not `from`.
59    #[must_use]
60    pub fn reply_to(mut self, address: impl Into<String>) -> Self {
61        self.reply_to = Some(address.into());
62        self
63    }
64
65    /// The key a provider that supports it uses to collapse a retry.
66    #[must_use]
67    pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
68        self.idempotency_key = Some(key.into());
69        self
70    }
71
72    /// Labels for the provider's own reporting.
73    #[must_use]
74    pub fn tags<I, T>(mut self, tags: I) -> Self
75    where
76        I: IntoIterator<Item = T>,
77        T: Into<String>,
78    {
79        self.tags = tags.into_iter().map(Into::into).collect();
80        self
81    }
82
83    /// One extra RFC 5322 header. Repeatable; order is preserved.
84    #[must_use]
85    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
86        self.headers.push((name.into(), value.into()));
87        self
88    }
89}
90
91/// Result of a send attempt.
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub enum SendOutcome {
94    /// Sent; carries the provider message id.
95    Sent { id: String },
96    /// The adapter is not configured (no API key / unverified sending
97    /// domain). The endpoint reports `503 mail-not-configured` so forms can
98    /// degrade instead of breaking.
99    NotConfigured,
100}
101
102/// Mailer failures, mapped by the adapter from provider responses.
103///
104/// Every variant that carries provider text is sanitized in `Display`,
105/// the same way [`DbError`](crate::DbError)'s is (issue #235). "Never
106/// includes the API key" was too weak a promise: the text an adapter
107/// wraps is the provider's own response, and a `422` from Resend quotes
108/// the field it objected to — which for a send is the **recipient
109/// address**. `Display` therefore runs it through
110/// [`crate::logging::scrub_text`], so every `tracing` field, problem
111/// detail, report line and `format!` that renders a `MailError` gets the
112/// sanitized text rather than each call site remembering to. `Debug`
113/// still shows the raw string for tests; the logging formatters scrub
114/// `{:?}` output too.
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub enum MailError {
117    /// The API key is missing, wrong or revoked.
118    Unauthorized,
119    /// The sending domain is not verified with the provider, so nothing
120    /// from it will be accepted until somebody adds the DNS records.
121    DomainNotVerified { domain: String },
122    /// The provider refused the message itself. `detail` is **its**
123    /// wording, so it can quote the recipient — see the type docs.
124    Invalid { detail: String },
125    /// Too many sends; retry no earlier than `retry_after` when the
126    /// provider named one.
127    RateLimited { retry_after: Option<Duration> },
128    /// The provider failed on its side (a `5xx`, an unparseable body).
129    Upstream(String),
130    /// The request never got an answer: a socket, a DNS failure, a
131    /// timeout.
132    Transport(String),
133}
134
135impl std::fmt::Display for MailError {
136    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
137        let scrub = crate::logging::scrub_text;
138        match self {
139            Self::Unauthorized => {
140                f.write_str("mailer rejected the request as unauthorized (check the API key)")
141            }
142            Self::DomainNotVerified { domain } => write!(
143                f,
144                "sending domain {:?} is not verified with the mailer",
145                scrub(domain)
146            ),
147            Self::Invalid { detail } => {
148                write!(
149                    f,
150                    "mailer rejected the message as invalid: {}",
151                    scrub(detail)
152                )
153            }
154            Self::RateLimited { retry_after } => write!(
155                f,
156                "mailer rate limited the request; retry after {retry_after:?}"
157            ),
158            Self::Upstream(message) => write!(f, "mailer upstream error: {}", scrub(message)),
159            Self::Transport(message) => write!(f, "mailer transport error: {}", scrub(message)),
160        }
161    }
162}
163
164impl std::error::Error for MailError {}
165
166#[async_trait]
167pub trait Mailer: Send + Sync {
168    async fn send(&self, message: Message) -> Result<SendOutcome, MailError>;
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    #[test]
176    fn display_sanitizes_the_provider_text() {
177        // The finding (issue #235): `Invalid { detail }` is set from the
178        // provider's own response — and Resend's 422 quotes the field it
179        // objected to, which for a send is the recipient address. The
180        // adapter's fallback is `body.to_string()`, the whole body.
181        let error = MailError::Invalid {
182            detail: "validation_error: `to` must be a valid address: alice@example.test".to_owned(),
183        };
184        let text = error.to_string();
185        assert!(!text.contains('@'), "{text}");
186        assert!(!text.contains("alice"), "{text}");
187        assert!(text.contains("[subject_hash:"), "{text}");
188
189        // An upstream body echoing the request URL must not disclose the
190        // query it carried.
191        let error = MailError::Upstream(
192            "POST https://api.resend.com/emails?key=live-abcdef failed".to_owned(),
193        );
194        let text = error.to_string();
195        assert!(!text.contains("live-abcdef"), "{text}");
196        assert!(text.contains("?[redacted]"), "{text}");
197
198        // The variants with nothing to hide read exactly as before.
199        assert_eq!(
200            MailError::Unauthorized.to_string(),
201            "mailer rejected the request as unauthorized (check the API key)"
202        );
203        assert_eq!(
204            MailError::RateLimited { retry_after: None }.to_string(),
205            "mailer rate limited the request; retry after None"
206        );
207
208        // `Debug` still shows the raw string, which is what a failing
209        // test needs to be readable; the log formatters scrub `{:?}` too.
210        assert!(format!("{error:?}").contains("live-abcdef"));
211    }
212
213    #[test]
214    fn a_domain_that_is_an_address_is_still_scrubbed() {
215        // `DomainNotVerified` looks safe — a sending domain is not
216        // personal data — but adapters set it from whatever the provider
217        // named, and Resend names the whole `from` when it objects.
218        let error = MailError::DomainNotVerified {
219            domain: "no-reply@send.example.test".to_owned(),
220        };
221        let text = error.to_string();
222        assert!(!text.contains('@'), "{text}");
223        assert!(text.contains("[subject_hash:"), "{text}");
224    }
225}