sofie-mail 0.2.0

Mail: messages rendered from templates, sent by a job over SMTP, to the log or to a test's outbox.
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
use std::fmt;

use serde::{Deserialize, Serialize};
use sofie_core::{Error, Result};
use sofie_values::Email;

const MAXIMUM_SUBJECT: usize = 255;
const MAXIMUM_NAME: usize = 255;
const MAXIMUM_LIST: usize = 64;
/// Each would end the address early in an SMTP command or split it in a header.
const REFUSED_IN_ADDRESS: &[char] = &['<', '>', '(', ')', ',', ';', ':', '"', '[', ']', '\\'];

/// Written into headers and SMTP commands as it is, so it holds nothing that could end either.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "AddressParts")]
pub struct Address {
    name: Option<String>,
    email: Email,
}

#[derive(Deserialize)]
struct AddressParts {
    name: Option<String>,
    email: Email,
}

impl TryFrom<AddressParts> for Address {
    type Error = Error;

    fn try_from(parts: AddressParts) -> Result<Self> {
        let address = Self::new(&parts.email)?;
        match parts.name {
            Some(name) => address.named(&name),
            None => Ok(address),
        }
    }
}

impl Address {
    /// One beyond ASCII is sent only through a server offering SMTPUTF8.
    pub fn new(email: &Email) -> Result<Self> {
        if email.as_str().contains(REFUSED_IN_ADDRESS) {
            return Err(Error::invalid(
                "email",
                "must not contain <>(),;:\"[]\\ to receive mail",
            ));
        }
        Ok(Self {
            name: None,
            email: email.clone(),
        })
    }

    pub fn named(self, name: &str) -> Result<Self> {
        if name.chars().count() > MAXIMUM_NAME || name.chars().any(sofie_core::misleads_display) {
            return Err(Error::invalid(
                "name",
                "must be at most 255 characters without control or invisible formatting characters",
            ));
        }
        Ok(Self {
            name: Some(name.to_owned()),
            ..self
        })
    }

    pub(crate) fn parse(text: &str) -> Result<Self> {
        let text = text.trim();
        let Some((name, rest)) = text.split_once('<') else {
            return Self::new(&Email::parse(text)?);
        };
        let email = rest
            .strip_suffix('>')
            .ok_or_else(|| Error::invalid("email", "must end with `>` after `<`"))?;
        let address = Self::new(&Email::parse(email)?)?;
        let name = unquoted(name.trim());
        if name.is_empty() {
            return Ok(address);
        }
        address.named(&name)
    }

    #[must_use]
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    #[must_use]
    pub fn email(&self) -> &Email {
        &self.email
    }

    pub(crate) fn domain(&self) -> &str {
        self.email
            .as_str()
            .rsplit_once('@')
            .map_or("localhost", |(_, domain)| domain)
    }
}

impl fmt::Debug for Address {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{:?}", self.email)
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Body {
    html: String,
    text: String,
}

impl Body {
    pub(crate) fn rendered(html: String) -> Self {
        let text = crate::text::from_html(&html);
        Self { html, text }
    }

    #[must_use]
    pub fn html(&self) -> &str {
        &self.html
    }

    #[must_use]
    pub fn text(&self) -> &str {
        &self.text
    }
}

#[derive(Clone, Serialize, Deserialize)]
#[serde(try_from = "MailParts")]
pub struct Mail {
    from: Option<Address>,
    to: Vec<Address>,
    reply_to: Option<Address>,
    subject: String,
    body: Body,
    list: Option<String>,
    /// Set when it is sent, as each recipient's link is its own.
    #[serde(skip)]
    unsubscribe: Option<String>,
}

#[derive(Deserialize)]
struct MailParts {
    from: Option<Address>,
    to: Vec<Address>,
    reply_to: Option<Address>,
    subject: String,
    body: Body,
    #[serde(default)]
    list: Option<String>,
}

impl TryFrom<MailParts> for Mail {
    type Error = Error;

    fn try_from(parts: MailParts) -> Result<Self> {
        let [first, others @ ..] = parts.to.as_slice() else {
            return Err(Error::invalid("to", "names no recipient"));
        };
        let mail = Self::new(first.clone(), &parts.subject, parts.body)?;
        let mail = others.iter().cloned().fold(mail, Self::also_to);
        let mail = match parts.list {
            Some(list) => mail.bulk(&list)?,
            None => mail,
        };
        Self {
            from: parts.from,
            reply_to: parts.reply_to,
            ..mail
        }
        .checked()
    }
}

/// One outer pair of quotes removed and `\x` read as `x`, as RFC 5322 quotes a name.
fn unquoted(name: &str) -> String {
    let Some(inner) = name
        .strip_prefix('"')
        .and_then(|rest| rest.strip_suffix('"'))
    else {
        return name.to_owned();
    };
    let mut unquoted = String::with_capacity(inner.len());
    let mut characters = inner.chars();
    while let Some(character) = characters.next() {
        match character {
            '\\' => unquoted.extend(characters.next()),
            _ => unquoted.push(character),
        }
    }
    unquoted
}

impl Mail {
    /// The subject is one header line: no control or invisible formatting characters, at most 255 characters.
    pub fn new(to: Address, subject: &str, body: Body) -> Result<Self> {
        if subject.trim().is_empty()
            || subject.chars().count() > MAXIMUM_SUBJECT
            || subject.chars().any(sofie_core::misleads_display)
        {
            return Err(Error::invalid(
                "subject",
                "must be 1 to 255 characters without control or invisible formatting characters",
            ));
        }
        Ok(Self {
            from: None,
            to: vec![to],
            reply_to: None,
            subject: subject.to_owned(),
            body,
            list: None,
            unsubscribe: None,
        })
    }

    /// Sent with a one-click unsubscribe link (RFC 8058) to its one recipient, and not at all
    /// to an address that unsubscribed from `list` or complained of bulk mail.
    pub fn bulk(self, list: &str) -> Result<Self> {
        let named = !list.is_empty()
            && list.len() <= MAXIMUM_LIST
            && list
                .bytes()
                .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-');
        if !named {
            return Err(Error::invalid(
                "list",
                "is 1 to 64 lowercase letters, digits and `-`",
            ));
        }
        Ok(Self {
            list: Some(list.to_owned()),
            ..self
        })
    }

    pub(crate) fn checked(self) -> Result<Self> {
        if self.list.is_some() && self.to.len() > 1 {
            return Err(Error::invalid(
                "to",
                "names one recipient in a bulk mail, as its unsubscribe link is that recipient's own",
            ));
        }
        Ok(self)
    }

    #[must_use]
    pub fn list(&self) -> Option<&str> {
        self.list.as_deref()
    }

    #[must_use]
    pub fn unsubscribe(&self) -> Option<&str> {
        self.unsubscribe.as_deref()
    }

    pub(crate) fn sent_to(self, to: Vec<Address>, unsubscribe: Option<String>) -> Self {
        Self {
            to,
            unsubscribe,
            ..self
        }
    }

    #[must_use]
    pub fn also_to(mut self, address: Address) -> Self {
        self.to.push(address);
        self
    }

    #[must_use]
    pub fn replying_to(self, address: Address) -> Self {
        Self {
            reply_to: Some(address),
            ..self
        }
    }

    #[must_use]
    pub fn sent_from(self, address: Address) -> Self {
        Self {
            from: Some(address),
            ..self
        }
    }

    #[must_use]
    pub fn from(&self) -> Option<&Address> {
        self.from.as_ref()
    }

    #[must_use]
    pub fn to(&self) -> &[Address] {
        &self.to
    }

    #[must_use]
    pub fn reply_to(&self) -> Option<&Address> {
        self.reply_to.as_ref()
    }

    #[must_use]
    pub fn subject(&self) -> &str {
        &self.subject
    }

    #[must_use]
    pub fn body(&self) -> &Body {
        &self.body
    }

    pub(crate) fn with_default_sender(self, default: &Address) -> Self {
        Self {
            from: Some(self.from.unwrap_or_else(|| default.clone())),
            ..self
        }
    }
}

/// Addresses masked, subject and body left out: either may carry personal data.
impl fmt::Debug for Mail {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Mail")
            .field("to", &self.to)
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn email(text: &str) -> Email {
        Email::parse(text).unwrap()
    }

    fn body() -> Body {
        Body::rendered("<p>Hello</p>".to_owned())
    }

    #[test]
    fn an_address_that_could_end_a_command_or_header_is_refused() {
        for refused in ["a>b@example.com", "a,b@example.com"] {
            let address = Email::parse(refused).and_then(|email| Address::new(&email));
            assert!(address.is_err(), "{refused}");
        }
        assert!(Address::new(&email("çağrı@example.com")).is_ok());
        let named = Address::new(&email("ada@example.com")).unwrap();
        assert!(named.clone().named("Ada\r\nBcc: x").is_err());
        assert_eq!(
            named.named("Ada Lovelace").unwrap().name(),
            Some("Ada Lovelace")
        );
    }

    #[test]
    fn a_quoted_from_name_is_unescaped_once() {
        let named = Address::parse(r#""Shop \"Main\"" <shop@example.com>"#).unwrap();

        assert_eq!(named.name(), Some("Shop \"Main\""));
    }

    #[test]
    fn a_from_setting_is_read_with_or_without_a_name() {
        let bare = Address::parse("shop@example.com").unwrap();
        let named = Address::parse("\"Shop\" <Shop@Example.com>").unwrap();

        assert_eq!(
            (bare.name(), bare.email().as_str()),
            (None, "shop@example.com")
        );
        assert_eq!(
            (named.name(), named.email().as_str()),
            (Some("Shop"), "shop@example.com")
        );
        assert!(Address::parse("Shop <shop@example.com").is_err());
    }

    #[test]
    fn a_subject_is_one_short_line() {
        let to = Address::new(&email("ada@example.com")).unwrap();

        assert!(Mail::new(to.clone(), "Your receipt", body()).is_ok());
        for refused in ["", "  ", "Line\r\nBcc: x", &"x".repeat(256)] {
            assert!(
                Mail::new(to.clone(), refused, body()).is_err(),
                "{refused:?}"
            );
        }
    }

    #[test]
    fn a_stored_mail_is_checked_again_when_read() {
        let to = Address::new(&email("ada@example.com")).unwrap();
        let mail = Mail::new(to, "Your receipt", body()).unwrap();
        let mut stored = serde_json::to_value(&mail).unwrap();

        let read: Mail = serde_json::from_value(stored.clone()).unwrap();
        assert_eq!(read.subject(), "Your receipt");
        stored["subject"] = "Forged\r\nBcc: x".into();
        assert!(serde_json::from_value::<Mail>(stored.clone()).is_err());
        stored["subject"] = "Fine".into();
        stored["to"] = serde_json::json!([]);
        assert!(serde_json::from_value::<Mail>(stored).is_err());
    }

    #[test]
    fn a_stored_bulk_mail_to_two_recipients_is_refused() {
        let to = Address::new(&email("ada@example.com")).unwrap();
        let mail = Mail::new(to.clone(), "News", body()).unwrap();
        let mut stored = serde_json::to_value(mail.bulk("news").unwrap()).unwrap();

        stored["to"] = serde_json::to_value([&to, &to]).unwrap();

        assert!(serde_json::from_value::<Mail>(stored).is_err());
    }

    #[test]
    fn debug_shows_no_address_subject_or_body() {
        let to = Address::new(&email("ada@example.com")).unwrap();
        let mail = Mail::new(to, "Secret plans", body()).unwrap();

        let shown = format!("{mail:?}");
        assert_eq!(shown, "Mail { to: [a***@example.com], .. }");
    }
}