forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

message.rs150 lines, 5.1 KiBHistoryRawDownload
1//! The lettre message, built from typed parts only.
2//!
3//! A [`Recipient`] and a [`Sender`] can exist only after their name and address have passed the same
4//! rules as the rest of `im`. A display name with a control character (a line break included) or a
5//! bidirectional override is refused here, so no header can be injected through a name. The message
6//! is then assembled by lettre's builder, which writes each header value itself.
7
8use im_core::config::SmtpConfig;
9use im_core::names::{parse_display_name, parse_email};
10use lettre::Address;
11use lettre::message::{Mailbox, Message, MultiPart};
12
13/// A recipient whose name and address have been checked.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct Recipient {
16 name: Option<String>,
17 email: String,
18}
19
20impl Recipient {
21 /// Checks a recipient. The name is optional; when given it must pass [`parse_display_name`]. The
22 /// address must pass [`parse_email`] and is stored in its normalised form.
23 pub fn new(name: Option<&str>, email: &str) -> Result<Self, &'static str> {
24 let name = match name {
25 Some(name) => {
26 Some(parse_display_name(name).map_err(|_| "recipient name is not valid")?)
27 }
28 None => None,
29 };
30 let email = parse_email(email).map_err(|_| "recipient address is not valid")?;
31 Ok(Self { name, email })
32 }
33
34 /// The checked display name, if any.
35 pub fn name(&self) -> Option<&str> {
36 self.name.as_deref()
37 }
38
39 /// The checked address.
40 pub fn email(&self) -> &str {
41 &self.email
42 }
43
44 fn mailbox(&self) -> Result<Mailbox, &'static str> {
45 let address: Address = self
46 .email
47 .parse()
48 .map_err(|_| "recipient address is not valid")?;
49 Ok(Mailbox::new(self.name.clone(), address))
50 }
51}
52
53/// The sender of every mail, from the SMTP section of the config.
54#[derive(Debug, Clone)]
55pub struct Sender {
56 mailbox: Mailbox,
57}
58
59impl Sender {
60 /// The sender of the config. Fails when `from` or `from_name` is not valid; the config check rejects
61 /// those at boot, so this only guards a config built in code.
62 pub fn from_config(smtp: &SmtpConfig) -> Result<Self, &'static str> {
63 let email = parse_email(&smtp.from).map_err(|_| "sender address is not valid")?;
64 let name = parse_display_name(&smtp.from_name).map_err(|_| "sender name is not valid")?;
65 let address: Address = email.parse().map_err(|_| "sender address is not valid")?;
66 Ok(Self {
67 mailbox: Mailbox::new(Some(name), address),
68 })
69 }
70}
71
72/// The subject as it goes on the wire: every control character, line breaks included, is removed, and the
73/// ends are trimmed, so no subject can end a header early. Enqueueing checks the same thing, but a row
74/// written by any other path still cannot break the header, so this runs again right before sending.
75pub fn clean_subject(subject: &str) -> String {
76 subject
77 .chars()
78 .filter(|c| !c.is_control())
79 .collect::<String>()
80 .trim()
81 .to_owned()
82}
83
84/// Builds a `multipart/alternative` message with a plain-text and an HTML part. The subject is cleaned by
85/// [`clean_subject`] first.
86pub fn build(
87 sender: &Sender,
88 to: &Recipient,
89 subject: &str,
90 text: String,
91 html: String,
92) -> Result<Message, &'static str> {
93 Message::builder()
94 .from(sender.mailbox.clone())
95 .to(to.mailbox()?)
96 .subject(clean_subject(subject))
97 .multipart(MultiPart::alternative_plain_html(text, html))
98 .map_err(|_| "message could not be built")
99}
100
101#[cfg(test)]
102mod tests {
103 use super::*;
104
105 fn sender() -> Sender {
106 Sender::from_config(&SmtpConfig {
107 host: "127.0.0.1".into(),
108 from: "im@example.com".into(),
109 ..SmtpConfig::default()
110 })
111 .expect("sender")
112 }
113
114 #[test]
115 fn a_name_with_a_line_break_cannot_add_a_header() {
116 // The attack: a name that ends the To header and starts a Bcc header.
117 let attack = Recipient::new(Some("Ada\r\nBcc: victim@example.com"), "ada@example.com");
118 assert!(attack.is_err());
119 assert!(Recipient::new(Some("Ada\nBcc: x@example.com"), "ada@example.com").is_err());
120 }
121
122 #[test]
123 fn a_hard_name_is_encoded_and_the_headers_stay_clean() {
124 let to = Recipient::new(Some("Ada \"Lovelace\", Jr. Ayşe"), "ada@example.com")
125 .expect("valid name");
126 let message = build(
127 &sender(),
128 &to,
129 "Subject",
130 "text".into(),
131 "<p>html</p>".into(),
132 )
133 .expect("message");
134 let raw = String::from_utf8_lossy(&message.formatted()).into_owned();
135 let headers = raw.split("\r\n\r\n").next().unwrap_or_default();
136 assert!(!headers.contains("Bcc:"), "{headers}");
137 let to_lines = headers
138 .lines()
139 .filter(|line| line.starts_with("To:"))
140 .count();
141 assert_eq!(to_lines, 1, "{headers}");
142 assert_eq!(
143 headers
144 .lines()
145 .filter(|l| l.starts_with("Subject:"))
146 .count(),
147 1
148 );
149 }
150}