//! The lettre message, built from typed parts only. //! //! A [`Recipient`] and a [`Sender`] can exist only after their name and address have passed the same //! rules as the rest of `im`. A display name with a control character (a line break included) or a //! bidirectional override is refused here, so no header can be injected through a name. The message //! is then assembled by lettre's builder, which writes each header value itself. use im_core::config::SmtpConfig; use im_core::names::{parse_display_name, parse_email}; use lettre::Address; use lettre::message::{Mailbox, Message, MultiPart}; /// A recipient whose name and address have been checked. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Recipient { name: Option, email: String, } impl Recipient { /// Checks a recipient. The name is optional; when given it must pass [`parse_display_name`]. The /// address must pass [`parse_email`] and is stored in its normalised form. pub fn new(name: Option<&str>, email: &str) -> Result { let name = match name { Some(name) => { Some(parse_display_name(name).map_err(|_| "recipient name is not valid")?) } None => None, }; let email = parse_email(email).map_err(|_| "recipient address is not valid")?; Ok(Self { name, email }) } /// The checked display name, if any. pub fn name(&self) -> Option<&str> { self.name.as_deref() } /// The checked address. pub fn email(&self) -> &str { &self.email } fn mailbox(&self) -> Result { let address: Address = self .email .parse() .map_err(|_| "recipient address is not valid")?; Ok(Mailbox::new(self.name.clone(), address)) } } /// The sender of every mail, from the SMTP section of the config. #[derive(Debug, Clone)] pub struct Sender { mailbox: Mailbox, } impl Sender { /// The sender of the config. Fails when `from` or `from_name` is not valid; the config check rejects /// those at boot, so this only guards a config built in code. pub fn from_config(smtp: &SmtpConfig) -> Result { let email = parse_email(&smtp.from).map_err(|_| "sender address is not valid")?; let name = parse_display_name(&smtp.from_name).map_err(|_| "sender name is not valid")?; let address: Address = email.parse().map_err(|_| "sender address is not valid")?; Ok(Self { mailbox: Mailbox::new(Some(name), address), }) } } /// The subject as it goes on the wire: every control character, line breaks included, is removed, and the /// ends are trimmed, so no subject can end a header early. Enqueueing checks the same thing, but a row /// written by any other path still cannot break the header, so this runs again right before sending. pub fn clean_subject(subject: &str) -> String { subject .chars() .filter(|c| !c.is_control()) .collect::() .trim() .to_owned() } /// Builds a `multipart/alternative` message with a plain-text and an HTML part. The subject is cleaned by /// [`clean_subject`] first. pub fn build( sender: &Sender, to: &Recipient, subject: &str, text: String, html: String, ) -> Result { Message::builder() .from(sender.mailbox.clone()) .to(to.mailbox()?) .subject(clean_subject(subject)) .multipart(MultiPart::alternative_plain_html(text, html)) .map_err(|_| "message could not be built") } #[cfg(test)] mod tests { use super::*; fn sender() -> Sender { Sender::from_config(&SmtpConfig { host: "127.0.0.1".into(), from: "im@example.com".into(), ..SmtpConfig::default() }) .expect("sender") } #[test] fn a_name_with_a_line_break_cannot_add_a_header() { // The attack: a name that ends the To header and starts a Bcc header. let attack = Recipient::new(Some("Ada\r\nBcc: victim@example.com"), "ada@example.com"); assert!(attack.is_err()); assert!(Recipient::new(Some("Ada\nBcc: x@example.com"), "ada@example.com").is_err()); } #[test] fn a_hard_name_is_encoded_and_the_headers_stay_clean() { let to = Recipient::new(Some("Ada \"Lovelace\", Jr. Ayşe"), "ada@example.com") .expect("valid name"); let message = build( &sender(), &to, "Subject", "text".into(), "

html

".into(), ) .expect("message"); let raw = String::from_utf8_lossy(&message.formatted()).into_owned(); let headers = raw.split("\r\n\r\n").next().unwrap_or_default(); assert!(!headers.contains("Bcc:"), "{headers}"); let to_lines = headers .lines() .filter(|line| line.starts_with("To:")) .count(); assert_eq!(to_lines, 1, "{headers}"); assert_eq!( headers .lines() .filter(|l| l.starts_with("Subject:")) .count(), 1 ); } }