Skip to main content

fastauth_core/
mail.rs

1//! Auth emails. A `Mailer` turns each typed email into a message.
2
3use std::any::TypeId;
4use std::fmt;
5use std::future::Future;
6use std::pin::Pin;
7use std::sync::atomic::{AtomicUsize, Ordering};
8use std::sync::{Arc, Mutex};
9use std::time::Duration;
10
11use tokio::sync::Semaphore;
12
13/// What `Debug` prints instead of a link, token or code.
14const REDACTED: &str = "[redacted]";
15
16/// Debug output never shows the link or the token.
17#[derive(Clone, PartialEq, Eq)]
18pub struct VerifyEmail {
19    pub to: String,
20    pub name: String,
21    pub url: String,
22    pub token: String,
23}
24
25impl fmt::Debug for VerifyEmail {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        f.debug_struct("VerifyEmail")
28            .field("to", &self.to)
29            .field("name", &self.name)
30            .field("url", &REDACTED)
31            .field("token", &REDACTED)
32            .finish()
33    }
34}
35
36/// Debug output never shows the link or the token.
37#[derive(Clone, PartialEq, Eq)]
38pub struct ResetPassword {
39    pub to: String,
40    pub name: String,
41    pub url: String,
42    pub token: String,
43}
44
45impl fmt::Debug for ResetPassword {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        f.debug_struct("ResetPassword")
48            .field("to", &self.to)
49            .field("name", &self.name)
50            .field("url", &REDACTED)
51            .field("token", &REDACTED)
52            .finish()
53    }
54}
55
56/// An email from a plugin (OTP codes, magic links, invitations). Debug output never shows
57/// the body, the link or the code.
58#[derive(Clone, PartialEq, Eq)]
59pub struct PluginEmail {
60    pub kind: &'static str,
61    pub to: String,
62    pub subject: String,
63    pub text: String,
64    pub url: Option<String>,
65    pub code: Option<String>,
66}
67
68impl fmt::Debug for PluginEmail {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        f.debug_struct("PluginEmail")
71            .field("kind", &self.kind)
72            .field("to", &self.to)
73            .field("subject", &self.subject)
74            .field("text", &REDACTED)
75            .field("url", &self.url.as_ref().map(|_| REDACTED))
76            .field("code", &self.code.as_ref().map(|_| REDACTED))
77            .finish()
78    }
79}
80
81#[derive(Clone, Debug, PartialEq, Eq)]
82#[non_exhaustive]
83pub enum AuthEmail {
84    VerifyEmail(VerifyEmail),
85    ResetPassword(ResetPassword),
86    Plugin(PluginEmail),
87}
88
89impl AuthEmail {
90    pub fn to(&self) -> &str {
91        match self {
92            AuthEmail::VerifyEmail(e) => &e.to,
93            AuthEmail::ResetPassword(e) => &e.to,
94            AuthEmail::Plugin(e) => &e.to,
95        }
96    }
97
98    /// A plain-text subject and body, for mailers without templates.
99    pub fn default_text(&self, app_name: &str) -> (String, String) {
100        match self {
101            AuthEmail::VerifyEmail(e) => (
102                format!("Verify your email for {app_name}"),
103                format!("Hi {},\n\nConfirm your email address: {}\n", e.name, e.url),
104            ),
105            AuthEmail::ResetPassword(e) => (
106                format!("Reset your {app_name} password"),
107                format!(
108                    "Hi {},\n\nReset your password: {}\n\nIgnore this email if you didn't ask.\n",
109                    e.name, e.url
110                ),
111            ),
112            AuthEmail::Plugin(e) => (e.subject.clone(), e.text.clone()),
113        }
114    }
115}
116
117#[derive(Debug, thiserror::Error)]
118#[error("sending email failed: {0}")]
119pub struct MailError(pub String);
120
121pub trait Mailer: Send + Sync + 'static {
122    fn send(&self, email: AuthEmail) -> impl Future<Output = Result<(), MailError>> + Send;
123}
124
125pub(crate) trait DynMailer: Send + Sync {
126    fn send(
127        &self,
128        email: AuthEmail,
129    ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + '_>>;
130
131    /// Whether this is one of the built-in mailers that do no I/O (`MemoryMailer`,
132    /// `LogMailer`), so sending inline costs nothing and reveals nothing.
133    fn in_process(&self) -> bool;
134}
135
136impl<M: Mailer> DynMailer for M {
137    fn send(
138        &self,
139        email: AuthEmail,
140    ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + '_>> {
141        Box::pin(Mailer::send(self, email))
142    }
143
144    fn in_process(&self) -> bool {
145        let id = TypeId::of::<M>();
146        id == TypeId::of::<MemoryMailer>() || id == TypeId::of::<LogMailer>()
147    }
148}
149
150/// Background sends that run at once. Each holds a thread of tokio's blocking pool while the
151/// mailer works, so a slow mailer can't take the threads password hashing needs.
152const MAX_CONCURRENT_SENDS: usize = 8;
153/// Background sends allowed to wait for a slot; beyond that an email is dropped and logged.
154const MAX_QUEUED_SENDS: usize = 10_000;
155/// How long one send may take before it is abandoned and logged.
156const SEND_TIMEOUT: Duration = Duration::from_secs(60);
157
158static SENDING: Semaphore = Semaphore::const_new(MAX_CONCURRENT_SENDS);
159static QUEUED: AtomicUsize = AtomicUsize::new(0);
160
161/// Sends `email` without making the request wait for the mailer, so a route answers in the
162/// same time whether or not it sent anything. A failed, dropped or timed-out send is logged,
163/// since there's no request left to answer.
164///
165/// Sends run on tokio's blocking pool, which keeps a mailer that blocks off the async workers,
166/// at most `MAX_CONCURRENT_SENDS` at a time per process, each cut off after `SEND_TIMEOUT`
167/// when its future yields. Up to `MAX_QUEUED_SENDS` more wait in line; past that, emails
168/// are dropped rather than queued without bound.
169///
170/// `MemoryMailer` and `LogMailer` send inline: they take no time, and tests can read
171/// `MemoryMailer` as soon as the response arrives.
172pub(crate) async fn send_in_background(mailer: Arc<dyn DynMailer>, email: AuthEmail) {
173    let kind = match &email {
174        AuthEmail::VerifyEmail(_) => "verify-email",
175        AuthEmail::ResetPassword(_) => "reset-password",
176        AuthEmail::Plugin(e) => e.kind,
177    };
178    if mailer.in_process() {
179        if let Err(err) = mailer.send(email).await {
180            tracing::error!(kind, error = %err, "fastauth could not send an email");
181        }
182        return;
183    }
184    if QUEUED.fetch_add(1, Ordering::SeqCst) >= MAX_QUEUED_SENDS {
185        QUEUED.fetch_sub(1, Ordering::SeqCst);
186        tracing::error!(
187            kind,
188            "fastauth dropped an email: {MAX_QUEUED_SENDS} are already waiting for the mailer"
189        );
190        return;
191    }
192    let runtime = tokio::runtime::Handle::current();
193    tokio::spawn(async move {
194        let permit = SENDING.acquire().await.expect("never closed");
195        let sent = tokio::task::spawn_blocking(move || {
196            runtime.block_on(tokio::time::timeout(SEND_TIMEOUT, mailer.send(email)))
197        })
198        .await;
199        drop(permit);
200        QUEUED.fetch_sub(1, Ordering::SeqCst);
201        match sent {
202            Ok(Ok(Ok(()))) => {}
203            Ok(Ok(Err(err))) => {
204                tracing::error!(kind, error = %err, "fastauth could not send an email");
205            }
206            Ok(Err(_)) => tracing::error!(
207                kind,
208                "fastauth gave up on an email: the mailer took longer than {SEND_TIMEOUT:?}"
209            ),
210            Err(err) => tracing::error!(kind, error = %err, "the mailer panicked"),
211        }
212    });
213}
214
215/// Logs emails instead of sending them. For development.
216#[derive(Clone, Debug, Default)]
217pub struct LogMailer;
218
219impl Mailer for LogMailer {
220    async fn send(&self, email: AuthEmail) -> Result<(), MailError> {
221        let (subject, body) = email.default_text("fastauth");
222        tracing::info!(to = email.to(), %subject, %body, "fastauth email (LogMailer, not sent)");
223        Ok(())
224    }
225}
226
227/// Keeps every email in memory. For tests.
228#[derive(Clone, Default)]
229pub struct MemoryMailer {
230    sent: Arc<Mutex<Vec<AuthEmail>>>,
231}
232
233impl fmt::Debug for MemoryMailer {
234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235        write!(f, "MemoryMailer({} sent)", self.sent.lock().unwrap().len())
236    }
237}
238
239impl MemoryMailer {
240    pub fn new() -> Self {
241        Self::default()
242    }
243
244    pub fn sent(&self) -> Vec<AuthEmail> {
245        self.sent.lock().unwrap().clone()
246    }
247
248    pub fn last(&self) -> Option<AuthEmail> {
249        self.sent.lock().unwrap().last().cloned()
250    }
251}
252
253impl Mailer for MemoryMailer {
254    async fn send(&self, email: AuthEmail) -> Result<(), MailError> {
255        self.sent.lock().unwrap().push(email);
256        Ok(())
257    }
258}