//! Email addresses: normalisation and the shape check. //! //! An address has one stored form: trimmed and lowercased. The same string is the `email` and the //! `email_folded` of a user, so lookups are case-insensitive by construction. The shape check //! accepts ASCII only. Look-alike characters from other scripts would otherwise let a second //! account look exactly like the first one. //! //! The check is a sanity check on the text, not proof that the address exists or receives mail. //! //! This module also checks display names ([`parse_display_name`]). A name is shown in the topbar, //! in mail and in other apps, so control characters and bidirectional overrides are refused: they //! can make one name read as another. use serde::Deserialize; use crate::error::{Error, Result}; /// Longest display name, in characters. The schema has the same limit. pub const MAX_NAME_CHARS: usize = 100; /// Longest address accepted, in bytes (RFC 5321 path limit). pub const MAX_EMAIL_LEN: usize = 254; /// Longest local part (the part before `@`), in bytes (RFC 5321). pub const MAX_LOCAL_LEN: usize = 64; /// Longest domain label, in bytes (RFC 1035). const MAX_LABEL_LEN: usize = 63; /// The stored form of an address: surrounding ASCII whitespace removed, then ASCII lowercased. /// /// Only ASCII is touched. Unicode trimming or case folding would turn look-alikes (a no-break space, /// the Kelvin sign) into an existing address; left alone, they fail the ASCII shape check instead. pub fn normalize_email(input: &str) -> String { input.trim_ascii().to_ascii_lowercase() } /// Normalises `input` and checks its shape. Returns the stored form. /// /// Rules: at most 254 bytes; exactly one `@`; a local part of 1 to 64 characters from the RFC 5322 /// `atext` set (no leading, trailing or doubled dot); a domain of dot-separated labels, at least /// one dot, each label 1 to 63 letters, digits or hyphens without a leading or trailing hyphen. /// Anything else, including whitespace and control characters, is refused. pub fn parse_email(input: &str) -> Result { let email = normalize_email(input); check_shape(&email)?; Ok(email) } /// Checks a display name and returns its stored form. /// /// Rules: surrounding whitespace is removed; what is left has 1 to [`MAX_NAME_CHARS`] characters; /// no character is a control character (this includes NUL, tab and line breaks); and no character /// is a bidirectional override or isolate (U+202A to U+202E, U+2066 to U+2069). Those last ones /// let a name display differently from the order its characters are stored in. pub fn parse_display_name(input: &str) -> Result { let name = input.trim(); let invalid = |why: &str| Error::Invalid(format!("the name {why}")); if name.is_empty() { return Err(invalid("must not be empty")); } if name.chars().count() > MAX_NAME_CHARS { return Err(invalid("must be at most 100 characters")); } if name.chars().any(|c| c.is_control() || is_bidi_control(c)) { return Err(invalid("must not contain control or direction characters")); } Ok(name.to_owned()) } /// Removes the control characters from a single-line field: every C0 control (U+0000 to U+001F, so NUL, /// tab and line breaks too) and DEL (U+007F). Applied where form values are read, so a typed control /// character is never used or echoed back into a page. pub fn strip_line_controls(input: &str) -> String { input.chars().filter(|&c| !is_c0_or_del(c)).collect() } /// Removes the control characters from a multi-line field, keeping line feed and tab. A carriage return /// is removed, so a browser's CRLF becomes LF. pub fn strip_text_controls(input: &str) -> String { input .chars() .filter(|&c| c == '\n' || c == '\t' || !is_c0_or_del(c)) .collect() } /// Serde adapter for a single-line form field: see [`strip_line_controls`]. pub fn single_line<'de, D: serde::Deserializer<'de>>( de: D, ) -> std::result::Result { String::deserialize(de).map(|text| strip_line_controls(&text)) } /// Serde adapter for a multi-line form field: see [`strip_text_controls`]. pub fn multi_line<'de, D: serde::Deserializer<'de>>( de: D, ) -> std::result::Result { String::deserialize(de).map(|text| strip_text_controls(&text)) } fn is_c0_or_del(c: char) -> bool { c.is_ascii_control() } /// The bidirectional embedding, override and isolate controls that [`parse_display_name`] refuses. fn is_bidi_control(c: char) -> bool { matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}') } /// The shape rules of [`parse_email`], for text that is already normalised. fn check_shape(email: &str) -> Result<()> { let invalid = || Error::Invalid("email address is not valid".into()); if email.len() > MAX_EMAIL_LEN { return Err(invalid()); } let (local, domain) = email.split_once('@').ok_or_else(invalid)?; if local.is_empty() || local.len() > MAX_LOCAL_LEN || local.starts_with('.') || local.ends_with('.') || local.contains("..") || !local.bytes().all(is_atext) { return Err(invalid()); } if !domain.contains('.') { return Err(invalid()); } for label in domain.split('.') { let well_formed = !label.is_empty() && label.len() <= MAX_LABEL_LEN && !label.starts_with('-') && !label.ends_with('-') && label .bytes() .all(|b| b.is_ascii_alphanumeric() || b == b'-'); if !well_formed { return Err(invalid()); } } Ok(()) } /// RFC 5322 `atext` restricted to ASCII. The dot is handled by the caller. fn is_atext(byte: u8) -> bool { byte.is_ascii_alphanumeric() || b"!#$%&'*+-/=?^_`{|}~.".contains(&byte) } #[cfg(test)] mod tests { use super::*; #[test] fn a_normal_address_is_trimmed_and_lowercased() { assert_eq!( parse_email(" Ada.Lovelace@Example.COM ").unwrap(), "ada.lovelace@example.com" ); } #[test] fn look_alikes_do_not_fold_into_an_address() { assert_ne!( normalize_email("\u{a0}admin@example.test"), "admin@example.test" ); assert_ne!( normalize_email("\u{212a}elvin@example.test"), "kelvin@example.test" ); assert!(parse_email("\u{a0}admin@example.test").is_err()); assert!(parse_email("\u{212a}elvin@example.test").is_err()); } #[test] fn display_names_are_trimmed_and_checked() { assert_eq!( parse_display_name(" Ada Lovelace ").unwrap(), "Ada Lovelace" ); assert_eq!(parse_display_name("Ayşe Çelik").unwrap(), "Ayşe Çelik"); let hundred = "a".repeat(MAX_NAME_CHARS); assert!(parse_display_name(&hundred).is_ok()); for bad in [ "", " ", "a\u{0}b", "ada\nlovelace", "ada\tlovelace", "\u{7}bell", "evil\u{202E}name", "\u{202A}ltr", "isolate\u{2066}x", "\u{2069}", &"a".repeat(MAX_NAME_CHARS + 1), ] { assert!(parse_display_name(bad).is_err(), "accepted {bad:?}"); } } #[test] fn form_text_loses_controls_and_multi_line_keeps_line_feed_and_tab() { assert_eq!(strip_line_controls("a\u{0}b\u{7f}c\td\ne"), "abcde"); assert_eq!(strip_text_controls("a\r\nb\tc\u{0}d"), "a\nb\tcd"); } #[test] fn attack_strings_are_refused() { let long_local = format!("{}@example.com", "a".repeat(MAX_LOCAL_LEN + 1)); let long_total = format!("a@{}.com", "b".repeat(250)); for bad in [ "", "ada", "@example.com", "ada@", "ada@@example.com", "ada@example", "ada@.example.com", "ada@example..com", "ada@example.com.", "ada@-example.com", "ada@example-.com", "a da@example.com", "ada@exam\nple.com", "ada\u{0}@example.com", "ada\u{202e}@example.com", "\u{ff41}da@example.com", "ada@exam\u{430}le.com", ".ada@example.com", "ada.@example.com", "ada..x@example.com", "ada@example.c om", "ada@example.com/", "ada@ex\tample.com", &long_local, &long_total, ] { assert!(parse_email(bad).is_err(), "accepted {bad:?}"); } } }