forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

compose.rs210 lines, 7.7 KiBHistoryRawDownload
1//! Builds the message of one outbox row with lettre's typed builders. It is the only place a mail
2//! header is written, and it never takes a header from text: every name and the subject go through
3//! `clean_text` first, so a CR or LF in a member's name or an actor's name cannot start a header line.
4//!
5//! The body is plain text, and an HTML alternative is made from it here with every character escaped.
6//! It is not a rendering of a page, so it never contains a link or script the text did not have.
7
8use iz_core::rules::clean_text;
9use iz_core::sender::Sender;
10use lettre::Address;
11use lettre::message::{Mailbox, Message, MultiPart};
12
13/// Longest subject sent, in characters. Reason: the same cap as the subject field of a rule.
14pub const SUBJECT_MAX: usize = iz_core::limits::MAIL_SUBJECT_MAX;
15/// Longest display name of a mailbox, in characters. Reason: a name is a label, not a sentence.
16const NAME_MAX: usize = 100;
17/// Message-ID domain used when the base URL has no usable host. Reason: a fixed, valid fallback.
18const FALLBACK_DOMAIN: &str = "localhost";
19
20/// What the builder needs besides the row: the sender's configuration and the recipient.
21pub struct Outgoing<'a> {
22 /// The checked sender configuration (host, port, and the From address and name).
23 pub sender: &'a Sender,
24 /// The recipient's display name.
25 pub to_name: &'a str,
26 /// The recipient's address, as the directory has it.
27 pub to_address: &'a str,
28 /// The subject, plain text.
29 pub subject: &'a str,
30 /// The body, plain text.
31 pub body: &'a str,
32 /// The outbox row id. It makes the Message-ID unique.
33 pub row_id: &'a str,
34 /// The domain part of the Message-ID, taken from the base URL.
35 pub domain: &'a str,
36}
37
38/// Builds the message. `Err` holds the reason as text; the caller stores it as the last error.
39pub fn build(m: &Outgoing<'_>) -> Result<Message, String> {
40 let from_name = bounded(&m.sender.from_name, NAME_MAX);
41 let from_address: Address = m
42 .sender
43 .from_address
44 .parse()
45 .map_err(|_| "the sender address is not valid".to_owned())?;
46 let to_address: Address = m
47 .to_address
48 .parse()
49 .map_err(|_| "the recipient address is not valid".to_owned())?;
50 let from = Mailbox::new(non_empty(from_name), from_address);
51 let to = Mailbox::new(non_empty(bounded(m.to_name, NAME_MAX)), to_address);
52 let subject = bounded(m.subject, SUBJECT_MAX);
53 let body = clean_body(m.body);
54 let html = html_alternative(&body);
55 Message::builder()
56 .from(from)
57 .to(to)
58 .subject(subject)
59 .message_id(Some(format!("<{}@{}>", m.row_id, safe_domain(m.domain))))
60 .date_now()
61 .multipart(MultiPart::alternative_plain_html(body, html))
62 .map_err(|e| format!("cannot build the message: {e}"))
63}
64
65/// The text with control and invisible formatting characters removed, cut to `max` characters.
66fn bounded(text: &str, max: usize) -> String {
67 clean_text(text).trim().chars().take(max).collect()
68}
69
70/// `None` for an empty name, so the mailbox has only the address.
71fn non_empty(name: String) -> Option<String> {
72 (!name.is_empty()).then_some(name)
73}
74
75/// The body with CRLF and CR turned into LF, and control characters other than tab and LF removed.
76fn clean_body(body: &str) -> String {
77 let normalized = body.replace("\r\n", "\n").replace('\r', "\n");
78 normalized
79 .chars()
80 .filter(|c| *c == '\n' || *c == '\t' || !c.is_control())
81 .collect()
82}
83
84/// The HTML alternative: each line is one paragraph, every character escaped. Nothing else is emitted.
85fn html_alternative(text: &str) -> String {
86 let mut out = String::from("<!DOCTYPE html>\n<html><body>\n");
87 for line in text.split('\n') {
88 if line.is_empty() {
89 out.push_str("<br>\n");
90 } else {
91 out.push_str("<p>");
92 out.push_str(&escape(line));
93 out.push_str("</p>\n");
94 }
95 }
96 out.push_str("</body></html>\n");
97 out
98}
99
100/// Escapes the five characters that are special in HTML text and attribute values.
101pub fn escape(text: &str) -> String {
102 let mut out = String::with_capacity(text.len());
103 for c in text.chars() {
104 match c {
105 '&' => out.push_str("&amp;"),
106 '<' => out.push_str("&lt;"),
107 '>' => out.push_str("&gt;"),
108 '"' => out.push_str("&quot;"),
109 '\'' => out.push_str("&#39;"),
110 other => out.push(other),
111 }
112 }
113 out
114}
115
116/// The host of a base URL, reduced to letters, digits, dots and dashes. The fallback when it is empty.
117pub fn domain_of(base_url: &str) -> String {
118 let host = reqwest::Url::parse(base_url)
119 .ok()
120 .and_then(|url| url.host_str().map(str::to_owned))
121 .unwrap_or_default();
122 safe_domain(&host).to_owned()
123}
124
125/// `domain` if it is made of letters, digits, dots and dashes; the fallback otherwise.
126fn safe_domain(domain: &str) -> &str {
127 let usable = !domain.is_empty()
128 && domain.len() <= 253
129 && domain
130 .bytes()
131 .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-');
132 if usable { domain } else { FALLBACK_DOMAIN }
133}
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138
139 fn sender(from_name: &str) -> Sender {
140 Sender {
141 host: "mail.example.test".into(),
142 port: 587,
143 tls: iz_core::sender::TlsMode::StartTls,
144 username: "u".into(),
145 from_address: "iz@example.test".into(),
146 from_name: from_name.into(),
147 }
148 }
149
150 /// A CRLF in the from name, the actor's name or the subject must not produce a header line.
151 #[test]
152 fn crlf_and_bcc_injection_makes_no_extra_header() {
153 let evil = sender("Board\r\nBcc: spy@evil.test");
154 let message = build(&Outgoing {
155 sender: &evil,
156 to_name: "Ada\r\nBcc: spy@evil.test",
157 to_address: "ada@example.test",
158 subject: "Task moved\r\nBcc: spy@evil.test\r\nX-Injected: 1",
159 body: "Hello",
160 row_id: "01HZ",
161 domain: "iz.example.test",
162 })
163 .expect("builds");
164 let text = String::from_utf8_lossy(&message.formatted()).into_owned();
165 let headers = text.split("\r\n\r\n").next().unwrap_or_default();
166 assert!(
167 !headers.lines().any(|line| line.starts_with("Bcc:")),
168 "{headers}"
169 );
170 assert!(
171 !headers.lines().any(|line| line.starts_with("X-Injected:")),
172 "{headers}"
173 );
174 }
175
176 #[test]
177 fn subject_is_cleaned_and_cut_to_the_limit() {
178 let long = format!("{}\r\n{}", "a".repeat(300), "b");
179 let message = build(&Outgoing {
180 sender: &sender("iz"),
181 to_name: "",
182 to_address: "ada@example.test",
183 subject: &long,
184 body: "x",
185 row_id: "01HZ",
186 domain: "iz.example.test",
187 })
188 .expect("builds");
189 let text = String::from_utf8_lossy(&message.formatted()).into_owned();
190 let subject_line = text
191 .lines()
192 .find(|line| line.starts_with("Subject:"))
193 .expect("has a subject");
194 assert!(subject_line.len() <= "Subject: ".len() + SUBJECT_MAX);
195 }
196
197 #[test]
198 fn html_alternative_escapes_every_value() {
199 let html = html_alternative("<script>alert(1)</script> & \"q\"");
200 assert!(!html.contains("<script>"));
201 assert!(html.contains("&lt;script&gt;alert(1)&lt;/script&gt; &amp; &quot;q&quot;"));
202 }
203
204 #[test]
205 fn a_bad_domain_falls_back() {
206 assert_eq!(domain_of("https://iz.example.test/x"), "iz.example.test");
207 assert_eq!(domain_of("not a url"), FALLBACK_DOMAIN);
208 assert_eq!(safe_domain("a b>c"), FALLBACK_DOMAIN);
209 }
210}