forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

mod.rs252 lines, 8.8 KiBHistoryRawDownload
1//! Outbound mail: what each mail says, how it is queued, and how the queue is sent.
2//!
3//! A mail is queued with [`queue`]: its text is rendered in the recipient's language, then sealed under the
4//! instance key and stored in `mail_outbox` (architecture section 3). The worker in [`worker`] sends the
5//! queued rows with retries. Nothing in this module logs a body, a link or a recipient address.
6//!
7//! - [`message`] builds the lettre message from typed parts only. A name or address that is not valid is
8//! refused before any header is written, so no user text can add a header.
9//! - [`templates`] renders the text and HTML of each kind. Every value goes through HTML escaping.
10//! - [`transport`] builds the SMTP connection from the config, reading the password file each time.
11
12pub mod message;
13pub mod templates;
14pub mod transport;
15pub mod worker;
16
17use im_core::Result;
18use im_core::model::User;
19use im_core::secret;
20use im_core::store::Store;
21use im_core::store::mail::NewMail;
22use serde_json::json;
23
24use crate::i18n::Lang;
25pub use message::Recipient;
26
27/// The security notices sent to the account's own address. Each is kind `security`.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum Notice {
30 /// The password was changed on the security page.
31 PasswordChanged,
32 /// The password was set through a reset link.
33 PasswordReset,
34 /// Two-factor sign-in was turned on.
35 TwoFactorOn,
36 /// Two-factor sign-in was turned off.
37 TwoFactorOff,
38 /// The recovery codes were replaced.
39 RecoveryCodes,
40}
41
42/// One kind of mail, with the values its text needs. A link is already built by the caller.
43#[derive(Clone, Copy)]
44pub enum Mail<'a> {
45 /// An administrator invited the recipient to create an account.
46 Invite {
47 /// The invitation link.
48 link: &'a str,
49 /// Days the link lasts.
50 days: u32,
51 },
52 /// A password reset was asked for.
53 Reset {
54 /// The reset link.
55 link: &'a str,
56 /// Minutes the link lasts.
57 minutes: u32,
58 },
59 /// Sent to the current address of an email change, with the cancel-or-confirm link.
60 EmailOld {
61 /// The link of the old half.
62 link: &'a str,
63 /// The address the account would move to.
64 new_email: &'a str,
65 /// Hours the link lasts.
66 hours: u32,
67 },
68 /// Sent to the new address of an email change.
69 EmailNew {
70 /// The link of the new half.
71 link: &'a str,
72 /// Hours the link lasts.
73 hours: u32,
74 },
75 /// The change happened. Sent to both addresses.
76 EmailDone {
77 /// The address the account has now.
78 new_email: &'a str,
79 },
80 /// Sent to the owner of an address that someone tried to use for another account. Nothing changed.
81 EmailTaken {
82 /// The service's public origin, which names the account the attempt was for.
83 issuer: &'a str,
84 },
85 /// A security notice.
86 Security(Notice),
87 /// A message from an administrator. The subject and the body are the administrator's own words; they
88 /// are escaped like every other value, and the body is split into paragraphs at blank lines.
89 Notice {
90 /// The subject line. Single line, checked by the caller.
91 subject: &'a str,
92 /// The body, plain text.
93 body: &'a str,
94 },
95 /// A test mail sent from the administrator's mail page. Its text is fixed.
96 Test {
97 /// The subject.
98 subject: &'a str,
99 /// The body, paragraphs separated by a blank line.
100 body: &'a str,
101 },
102}
103
104/// Prints every value except the links, which print as `<redacted>`: each link carries a token.
105impl std::fmt::Debug for Mail<'_> {
106 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107 match self {
108 Mail::Invite { days, .. } => f
109 .debug_struct("Invite")
110 .field("link", &format_args!("<redacted>"))
111 .field("days", days)
112 .finish(),
113 Mail::Reset { minutes, .. } => f
114 .debug_struct("Reset")
115 .field("link", &format_args!("<redacted>"))
116 .field("minutes", minutes)
117 .finish(),
118 Mail::EmailOld {
119 new_email, hours, ..
120 } => f
121 .debug_struct("EmailOld")
122 .field("link", &format_args!("<redacted>"))
123 .field("new_email", new_email)
124 .field("hours", hours)
125 .finish(),
126 Mail::EmailNew { hours, .. } => f
127 .debug_struct("EmailNew")
128 .field("link", &format_args!("<redacted>"))
129 .field("hours", hours)
130 .finish(),
131 Mail::EmailDone { new_email } => f
132 .debug_struct("EmailDone")
133 .field("new_email", new_email)
134 .finish(),
135 Mail::EmailTaken { issuer } => f
136 .debug_struct("EmailTaken")
137 .field("issuer", issuer)
138 .finish(),
139 Mail::Security(notice) => f.debug_tuple("Security").field(notice).finish(),
140 Mail::Notice { subject, body } => f
141 .debug_struct("Notice")
142 .field("subject", subject)
143 .field("body", body)
144 .finish(),
145 Mail::Test { subject, body } => f
146 .debug_struct("Test")
147 .field("subject", subject)
148 .field("body", body)
149 .finish(),
150 }
151 }
152}
153
154impl Mail<'_> {
155 /// The stored kind, one of the values `mail_outbox.kind` allows.
156 pub fn kind(&self) -> &'static str {
157 match self {
158 Mail::Invite { .. } => "invite",
159 Mail::Reset { .. } => "reset",
160 Mail::EmailOld { .. } => "email_old",
161 Mail::EmailNew { .. } => "email_new",
162 Mail::EmailDone { .. } => "email_done",
163 Mail::EmailTaken { .. } => "security",
164 Mail::Security(_) => "security",
165 Mail::Notice { .. } => "notice",
166 Mail::Test { .. } => "test",
167 }
168 }
169}
170
171/// The language a mail to `user` is written in: the stored choice, unless the person chose the
172/// browser's language. Then the language of the request that triggered the mail.
173pub fn lang_for(user: &User, request: Lang) -> Lang {
174 if user.locale_auto {
175 request
176 } else {
177 Lang::from_code(&user.locale).unwrap_or(request)
178 }
179}
180
181/// A mail rendered and sealed, not yet in the outbox. Built before any link it carries is created, so the
182/// store can check its limits and create the links in one transaction (see `store::links`).
183pub struct Sealed {
184 kind: &'static str,
185 to_addr: String,
186 subject: String,
187 sealed_body: String,
188}
189
190impl Sealed {
191 /// The outbox row this mail becomes.
192 pub fn as_new(&self) -> NewMail<'_> {
193 NewMail {
194 kind: self.kind,
195 to_addr: &self.to_addr,
196 subject: &self.subject,
197 sealed_body: &self.sealed_body,
198 }
199 }
200}
201
202/// Renders `mail` for `to` in `lang` and seals it under the instance key. The subject is fixed text; the
203/// body (text and HTML, with the recipient's name) is sealed as one JSON document.
204pub fn seal(key: &[u8; 32], to: &Recipient, lang: Lang, mail: &Mail<'_>) -> Result<Sealed> {
205 let rendered = templates::render(lang, to.name(), mail);
206 let payload = json!({
207 "to_name": to.name(),
208 "text": rendered.text,
209 "html": rendered.html,
210 })
211 .to_string();
212 let sealed = secret::seal(key, secret::purpose::MAIL_BODY, payload.as_bytes())?;
213 Ok(Sealed {
214 kind: mail.kind(),
215 to_addr: to.email().to_string(),
216 subject: rendered.subject,
217 sealed_body: sealed,
218 })
219}
220
221/// Renders `mail` for `to` in `lang`, seals it, and adds it to the outbox. A mail that the store drops by
222/// its limits is not an error here: the caller answers the same either way.
223pub async fn queue(
224 store: &Store,
225 key: &[u8; 32],
226 to: &Recipient,
227 lang: Lang,
228 mail: &Mail<'_>,
229) -> Result<()> {
230 let sealed = seal(key, to, lang, mail)?;
231 store.enqueue_mail(&sealed.as_new()).await?;
232 Ok(())
233}
234
235/// Queues a security notice for the account's own address, in the person's language. A failure is
236/// logged and never reaches the caller: the change it reports has already been made.
237pub async fn notify(store: &Store, key: &[u8; 32], user: &User, request: Lang, notice: Notice) {
238 let to = match Recipient::new(Some(&user.name), &user.email) {
239 Ok(to) => to,
240 Err(error) => {
241 tracing::error!(
242 error,
243 "security notice not queued: stored address is not valid"
244 );
245 return;
246 }
247 };
248 let lang = lang_for(user, request);
249 if let Err(error) = queue(store, key, &to, lang, &Mail::Security(notice)).await {
250 tracing::error!(error = %error, "security notice not queued");
251 }
252}