//! Builds the message of one outbox row with lettre's typed builders. It is the only place a mail //! header is written, and it never takes a header from text: every name and the subject go through //! `clean_text` first, so a CR or LF in a member's name or an actor's name cannot start a header line. //! //! The body is plain text, and an HTML alternative is made from it here with every character escaped. //! It is not a rendering of a page, so it never contains a link or script the text did not have. use iz_core::rules::clean_text; use iz_core::sender::Sender; use lettre::Address; use lettre::message::{Mailbox, Message, MultiPart}; /// Longest subject sent, in characters. Reason: the same cap as the subject field of a rule. pub const SUBJECT_MAX: usize = iz_core::limits::MAIL_SUBJECT_MAX; /// Longest display name of a mailbox, in characters. Reason: a name is a label, not a sentence. const NAME_MAX: usize = 100; /// Message-ID domain used when the base URL has no usable host. Reason: a fixed, valid fallback. const FALLBACK_DOMAIN: &str = "localhost"; /// What the builder needs besides the row: the sender's configuration and the recipient. pub struct Outgoing<'a> { /// The checked sender configuration (host, port, and the From address and name). pub sender: &'a Sender, /// The recipient's display name. pub to_name: &'a str, /// The recipient's address, as the directory has it. pub to_address: &'a str, /// The subject, plain text. pub subject: &'a str, /// The body, plain text. pub body: &'a str, /// The outbox row id. It makes the Message-ID unique. pub row_id: &'a str, /// The domain part of the Message-ID, taken from the base URL. pub domain: &'a str, } /// Builds the message. `Err` holds the reason as text; the caller stores it as the last error. pub fn build(m: &Outgoing<'_>) -> Result { let from_name = bounded(&m.sender.from_name, NAME_MAX); let from_address: Address = m .sender .from_address .parse() .map_err(|_| "the sender address is not valid".to_owned())?; let to_address: Address = m .to_address .parse() .map_err(|_| "the recipient address is not valid".to_owned())?; let from = Mailbox::new(non_empty(from_name), from_address); let to = Mailbox::new(non_empty(bounded(m.to_name, NAME_MAX)), to_address); let subject = bounded(m.subject, SUBJECT_MAX); let body = clean_body(m.body); let html = html_alternative(&body); Message::builder() .from(from) .to(to) .subject(subject) .message_id(Some(format!("<{}@{}>", m.row_id, safe_domain(m.domain)))) .date_now() .multipart(MultiPart::alternative_plain_html(body, html)) .map_err(|e| format!("cannot build the message: {e}")) } /// The text with control and invisible formatting characters removed, cut to `max` characters. fn bounded(text: &str, max: usize) -> String { clean_text(text).trim().chars().take(max).collect() } /// `None` for an empty name, so the mailbox has only the address. fn non_empty(name: String) -> Option { (!name.is_empty()).then_some(name) } /// The body with CRLF and CR turned into LF, and control characters other than tab and LF removed. fn clean_body(body: &str) -> String { let normalized = body.replace("\r\n", "\n").replace('\r', "\n"); normalized .chars() .filter(|c| *c == '\n' || *c == '\t' || !c.is_control()) .collect() } /// The HTML alternative: each line is one paragraph, every character escaped. Nothing else is emitted. fn html_alternative(text: &str) -> String { let mut out = String::from("\n\n"); for line in text.split('\n') { if line.is_empty() { out.push_str("
\n"); } else { out.push_str("

"); out.push_str(&escape(line)); out.push_str("

\n"); } } out.push_str("\n"); out } /// Escapes the five characters that are special in HTML text and attribute values. pub fn escape(text: &str) -> String { let mut out = String::with_capacity(text.len()); for c in text.chars() { match c { '&' => out.push_str("&"), '<' => out.push_str("<"), '>' => out.push_str(">"), '"' => out.push_str("""), '\'' => out.push_str("'"), other => out.push(other), } } out } /// The host of a base URL, reduced to letters, digits, dots and dashes. The fallback when it is empty. pub fn domain_of(base_url: &str) -> String { let host = reqwest::Url::parse(base_url) .ok() .and_then(|url| url.host_str().map(str::to_owned)) .unwrap_or_default(); safe_domain(&host).to_owned() } /// `domain` if it is made of letters, digits, dots and dashes; the fallback otherwise. fn safe_domain(domain: &str) -> &str { let usable = !domain.is_empty() && domain.len() <= 253 && domain .bytes() .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-'); if usable { domain } else { FALLBACK_DOMAIN } } #[cfg(test)] mod tests { use super::*; fn sender(from_name: &str) -> Sender { Sender { host: "mail.example.test".into(), port: 587, tls: iz_core::sender::TlsMode::StartTls, username: "u".into(), from_address: "iz@example.test".into(), from_name: from_name.into(), } } /// A CRLF in the from name, the actor's name or the subject must not produce a header line. #[test] fn crlf_and_bcc_injection_makes_no_extra_header() { let evil = sender("Board\r\nBcc: spy@evil.test"); let message = build(&Outgoing { sender: &evil, to_name: "Ada\r\nBcc: spy@evil.test", to_address: "ada@example.test", subject: "Task moved\r\nBcc: spy@evil.test\r\nX-Injected: 1", body: "Hello", row_id: "01HZ", domain: "iz.example.test", }) .expect("builds"); let text = String::from_utf8_lossy(&message.formatted()).into_owned(); let headers = text.split("\r\n\r\n").next().unwrap_or_default(); assert!( !headers.lines().any(|line| line.starts_with("Bcc:")), "{headers}" ); assert!( !headers.lines().any(|line| line.starts_with("X-Injected:")), "{headers}" ); } #[test] fn subject_is_cleaned_and_cut_to_the_limit() { let long = format!("{}\r\n{}", "a".repeat(300), "b"); let message = build(&Outgoing { sender: &sender("iz"), to_name: "", to_address: "ada@example.test", subject: &long, body: "x", row_id: "01HZ", domain: "iz.example.test", }) .expect("builds"); let text = String::from_utf8_lossy(&message.formatted()).into_owned(); let subject_line = text .lines() .find(|line| line.starts_with("Subject:")) .expect("has a subject"); assert!(subject_line.len() <= "Subject: ".len() + SUBJECT_MAX); } #[test] fn html_alternative_escapes_every_value() { let html = html_alternative(" & \"q\""); assert!(!html.contains("