tablo_core/auth/mail/delivery.rs
1//! Where auth mail goes once it is written: [`AuthLetter`], the mail itself, and
2//! [`AuthMailDelivery`], the app's hand-off that takes it inside the transaction recording its
3//! token.
4
5use std::{future::Future, time::SystemTime};
6
7use jiff::Timestamp;
8use serde::{Deserialize, Serialize};
9use topcoat::{
10 context::Cx,
11 mail::{Mail, Mailbox},
12};
13
14use crate::BoxFuture;
15
16/// One mail a panel's auth sends: a plain-text mail to one address, carrying a live link or code
17/// for every [`kind`](Self::kind) but [`AuthLetterKind::TwoFactorAlert`].
18///
19/// It serializes, so an [`AuthMailDelivery`] can queue it, and [`mail`](Self::mail) rebuilds the
20/// same mail each time, with the same `Date` and `Message-ID`: a letter sent twice after a crash
21/// reads as one mail in a mail client. Its serialized form may change between releases, so a
22/// queue drains before an upgrade, or drops what no longer deserializes.
23///
24/// A queued letter holds the link or code in clear: seal it before it reaches a database, a log
25/// or a backup. Its `Debug` output leaves the subject and body out.
26#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct AuthLetter {
28 kind: AuthLetterKind,
29 from_name: Option<String>,
30 from: String,
31 to: String,
32 subject: String,
33 text: String,
34 date: Timestamp,
35 message_id: String,
36 expires_at: Option<Timestamp>,
37}
38
39impl AuthLetter {
40 /// What the letter is for.
41 #[must_use]
42 pub fn kind(&self) -> AuthLetterKind {
43 self.kind
44 }
45
46 /// The address the letter goes to.
47 #[must_use]
48 pub fn to(&self) -> &str {
49 &self.to
50 }
51
52 /// When the link or code the letter carries stops working, or `None` for a letter that
53 /// carries none. A letter sent after it reads as broken: a queue drops it instead.
54 #[must_use]
55 pub fn expires_at(&self) -> Option<Timestamp> {
56 self.expires_at
57 }
58
59 /// The letter as a mail to send through a [`Transport`](topcoat::mail::Transport).
60 ///
61 /// # Errors
62 ///
63 /// When an address no longer parses, which a letter from a later release may cause.
64 pub fn mail(&self) -> topcoat::Result<Mail> {
65 let from = match &self.from_name {
66 Some(name) => Mailbox::named(name, &self.from)?,
67 None => Mailbox::new(&self.from)?,
68 };
69 Ok(Mail::builder()
70 .from(from)
71 .to([Mailbox::new(&self.to)?])
72 .subject(self.subject.clone())
73 .text(self.text.clone())
74 .date(SystemTime::from(self.date))
75 .message_id(self.message_id.clone())
76 .build()?)
77 }
78
79 /// A letter of `kind` from `from` to `to`, whose link or code expires at `expires_at`.
80 pub(in crate::auth) fn new(
81 kind: AuthLetterKind,
82 from: &Mailbox,
83 to: &str,
84 subject: String,
85 text: String,
86 expires_at: Option<Timestamp>,
87 ) -> topcoat::Result<Self> {
88 // Built once to check the addresses and to fix the date and `Message-ID` it keeps.
89 let mail = Mail::builder()
90 .from(from.clone())
91 .to([Mailbox::new(to)?])
92 .subject(subject.clone())
93 .text(text.clone())
94 .build()?;
95 Ok(Self {
96 kind,
97 from_name: from.name().map(str::to_string),
98 from: from.address().to_string(),
99 to: to.to_string(),
100 subject,
101 text,
102 date: Timestamp::try_from(mail.date()).map_err(topcoat::Error::from)?,
103 message_id: mail.message_id().to_string(),
104 expires_at,
105 })
106 }
107}
108
109impl std::fmt::Debug for AuthLetter {
110 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111 f.debug_struct("AuthLetter")
112 .field("kind", &self.kind)
113 .field("to", &self.to)
114 .field("message_id", &self.message_id)
115 .field("expires_at", &self.expires_at)
116 .finish_non_exhaustive()
117 }
118}
119
120/// What an [`AuthLetter`] is for.
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
122#[serde(rename_all = "snake_case")]
123#[non_exhaustive]
124pub enum AuthLetterKind {
125 /// A link that sets a new password, from
126 /// [`Auth::password_reset`](super::super::Auth::password_reset).
127 PasswordReset,
128 /// A link that proves the account reads its address, from
129 /// [`Auth::email_verification`](super::super::Auth::email_verification).
130 EmailVerification,
131 /// A link to a new address that makes it the account's.
132 EmailChange,
133 /// A link to the old address that cancels a pending email change.
134 EmailChangeCancel,
135 /// A six-digit code that signs in as a second factor, or sets the factor up.
136 TwoFactorCode,
137 /// A notice that the password signed in and second-factor codes failed after it. It carries
138 /// no link or code.
139 TwoFactorAlert,
140}
141
142/// Takes each [`AuthLetter`] a panel's auth sends, installed with
143/// [`AuthMail::delivery`](super::AuthMail::delivery), so a durable queue sends it in place of the
144/// router's [`Mailer`](topcoat::mail::Mailer).
145///
146/// Without one, a panel sends each letter through the `Mailer` once the token it carries
147/// commits: a crash or a mail-server outage then loses it. A delivery writes the letter to a
148/// queue through `ex`, the transaction that records its token, so the letter and the token
149/// commit together or not at all, and a worker sends it later.
150///
151/// ```rust
152/// use tablo_core::{AuthLetter, AuthMailDelivery};
153/// use topcoat::context::Cx;
154///
155/// #[derive(Debug, toasty::Model)]
156/// struct QueuedMail {
157/// #[key]
158/// #[auto]
159/// id: u64,
160/// #[column(type = text)]
161/// sealed: String,
162/// }
163///
164/// struct Outbox;
165///
166/// impl AuthMailDelivery for Outbox {
167/// async fn deliver(
168/// &self,
169/// _cx: &Cx,
170/// ex: &mut dyn toasty::Executor,
171/// letter: AuthLetter,
172/// ) -> topcoat::Result<()> {
173/// let json = serde_json::to_string(&letter)?;
174/// toasty::create!(QueuedMail {
175/// sealed: seal(&json)
176/// })
177/// .exec(ex)
178/// .await?;
179/// Ok(())
180/// }
181/// }
182/// # fn seal(json: &str) -> String { json.to_string() }
183/// ```
184///
185/// - `deliver` runs inside the transaction recording the letter's token, through `ex`. An
186/// [`AuthLetterKind::TwoFactorAlert`] records no token: `ex` is then the database itself.
187/// - An error rolls the transaction back: no token is recorded and no letter goes out. A
188/// password-reset or verification link is mailed after the response, so its failure is logged; a
189/// two-factor code's answers the request with the outage; an email change's fails the save.
190/// - It may run more than once for one letter when the database aborts the transaction for a
191/// concurrent one, so it writes only through `ex`: a mail sent from inside it goes out once per
192/// run, and before the token commits.
193/// - The letter carries a live link or code. Seal it before writing it, and drop a letter past its
194/// [`expires_at`](AuthLetter::expires_at) rather than send it late.
195pub trait AuthMailDelivery: Send + Sync + 'static {
196 /// Takes `letter` for sending, writing through `ex`.
197 fn deliver(
198 &self,
199 cx: &Cx,
200 ex: &mut dyn toasty::Executor,
201 letter: AuthLetter,
202 ) -> impl Future<Output = topcoat::Result<()>> + Send;
203}
204
205/// [`AuthMailDelivery`] made dyn-compatible.
206pub(super) trait DynDelivery: Send + Sync {
207 fn deliver<'a>(
208 &'a self,
209 cx: &'a Cx,
210 ex: &'a mut dyn toasty::Executor,
211 letter: AuthLetter,
212 ) -> BoxFuture<'a, topcoat::Result<()>>;
213}
214
215impl<D: AuthMailDelivery> DynDelivery for D {
216 fn deliver<'a>(
217 &'a self,
218 cx: &'a Cx,
219 ex: &'a mut dyn toasty::Executor,
220 letter: AuthLetter,
221 ) -> BoxFuture<'a, topcoat::Result<()>> {
222 Box::pin(AuthMailDelivery::deliver(self, cx, ex, letter))
223 }
224}
225
226/// Sends `letter` through the router's [`Mailer`](topcoat::mail::Mailer).
227pub(in crate::auth) async fn send(cx: &Cx, letter: AuthLetter) -> topcoat::Result<()> {
228 topcoat::mail::send(cx, letter.mail()?).await?;
229 Ok(())
230}
231
232#[cfg(test)]
233mod tests;