forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

names.rs241 lines, 8.5 KiBHistoryRawDownload
1//! Email addresses: normalisation and the shape check.
2//!
3//! An address has one stored form: trimmed and lowercased. The same string is the `email` and the
4//! `email_folded` of a user, so lookups are case-insensitive by construction. The shape check
5//! accepts ASCII only. Look-alike characters from other scripts would otherwise let a second
6//! account look exactly like the first one.
7//!
8//! The check is a sanity check on the text, not proof that the address exists or receives mail.
9//!
10//! This module also checks display names ([`parse_display_name`]). A name is shown in the topbar,
11//! in mail and in other apps, so control characters and bidirectional overrides are refused: they
12//! can make one name read as another.
13
14use serde::Deserialize;
15
16use crate::error::{Error, Result};
17
18/// Longest display name, in characters. The schema has the same limit.
19pub const MAX_NAME_CHARS: usize = 100;
20
21/// Longest address accepted, in bytes (RFC 5321 path limit).
22pub const MAX_EMAIL_LEN: usize = 254;
23
24/// Longest local part (the part before `@`), in bytes (RFC 5321).
25pub const MAX_LOCAL_LEN: usize = 64;
26
27/// Longest domain label, in bytes (RFC 1035).
28const MAX_LABEL_LEN: usize = 63;
29
30/// The stored form of an address: surrounding ASCII whitespace removed, then ASCII lowercased.
31///
32/// Only ASCII is touched. Unicode trimming or case folding would turn look-alikes (a no-break space,
33/// the Kelvin sign) into an existing address; left alone, they fail the ASCII shape check instead.
34pub fn normalize_email(input: &str) -> String {
35 input.trim_ascii().to_ascii_lowercase()
36}
37
38/// Normalises `input` and checks its shape. Returns the stored form.
39///
40/// Rules: at most 254 bytes; exactly one `@`; a local part of 1 to 64 characters from the RFC 5322
41/// `atext` set (no leading, trailing or doubled dot); a domain of dot-separated labels, at least
42/// one dot, each label 1 to 63 letters, digits or hyphens without a leading or trailing hyphen.
43/// Anything else, including whitespace and control characters, is refused.
44pub fn parse_email(input: &str) -> Result<String> {
45 let email = normalize_email(input);
46 check_shape(&email)?;
47 Ok(email)
48}
49
50/// Checks a display name and returns its stored form.
51///
52/// Rules: surrounding whitespace is removed; what is left has 1 to [`MAX_NAME_CHARS`] characters;
53/// no character is a control character (this includes NUL, tab and line breaks); and no character
54/// is a bidirectional override or isolate (U+202A to U+202E, U+2066 to U+2069). Those last ones
55/// let a name display differently from the order its characters are stored in.
56pub fn parse_display_name(input: &str) -> Result<String> {
57 let name = input.trim();
58 let invalid = |why: &str| Error::Invalid(format!("the name {why}"));
59 if name.is_empty() {
60 return Err(invalid("must not be empty"));
61 }
62 if name.chars().count() > MAX_NAME_CHARS {
63 return Err(invalid("must be at most 100 characters"));
64 }
65 if name.chars().any(|c| c.is_control() || is_bidi_control(c)) {
66 return Err(invalid("must not contain control or direction characters"));
67 }
68 Ok(name.to_owned())
69}
70
71/// Removes the control characters from a single-line field: every C0 control (U+0000 to U+001F, so NUL,
72/// tab and line breaks too) and DEL (U+007F). Applied where form values are read, so a typed control
73/// character is never used or echoed back into a page.
74pub fn strip_line_controls(input: &str) -> String {
75 input.chars().filter(|&c| !is_c0_or_del(c)).collect()
76}
77
78/// Removes the control characters from a multi-line field, keeping line feed and tab. A carriage return
79/// is removed, so a browser's CRLF becomes LF.
80pub fn strip_text_controls(input: &str) -> String {
81 input
82 .chars()
83 .filter(|&c| c == '\n' || c == '\t' || !is_c0_or_del(c))
84 .collect()
85}
86
87/// Serde adapter for a single-line form field: see [`strip_line_controls`].
88pub fn single_line<'de, D: serde::Deserializer<'de>>(
89 de: D,
90) -> std::result::Result<String, D::Error> {
91 String::deserialize(de).map(|text| strip_line_controls(&text))
92}
93
94/// Serde adapter for a multi-line form field: see [`strip_text_controls`].
95pub fn multi_line<'de, D: serde::Deserializer<'de>>(
96 de: D,
97) -> std::result::Result<String, D::Error> {
98 String::deserialize(de).map(|text| strip_text_controls(&text))
99}
100
101fn is_c0_or_del(c: char) -> bool {
102 c.is_ascii_control()
103}
104
105/// The bidirectional embedding, override and isolate controls that [`parse_display_name`] refuses.
106fn is_bidi_control(c: char) -> bool {
107 matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
108}
109
110/// The shape rules of [`parse_email`], for text that is already normalised.
111fn check_shape(email: &str) -> Result<()> {
112 let invalid = || Error::Invalid("email address is not valid".into());
113 if email.len() > MAX_EMAIL_LEN {
114 return Err(invalid());
115 }
116 let (local, domain) = email.split_once('@').ok_or_else(invalid)?;
117 if local.is_empty()
118 || local.len() > MAX_LOCAL_LEN
119 || local.starts_with('.')
120 || local.ends_with('.')
121 || local.contains("..")
122 || !local.bytes().all(is_atext)
123 {
124 return Err(invalid());
125 }
126 if !domain.contains('.') {
127 return Err(invalid());
128 }
129 for label in domain.split('.') {
130 let well_formed = !label.is_empty()
131 && label.len() <= MAX_LABEL_LEN
132 && !label.starts_with('-')
133 && !label.ends_with('-')
134 && label
135 .bytes()
136 .all(|b| b.is_ascii_alphanumeric() || b == b'-');
137 if !well_formed {
138 return Err(invalid());
139 }
140 }
141 Ok(())
142}
143
144/// RFC 5322 `atext` restricted to ASCII. The dot is handled by the caller.
145fn is_atext(byte: u8) -> bool {
146 byte.is_ascii_alphanumeric() || b"!#$%&'*+-/=?^_`{|}~.".contains(&byte)
147}
148
149#[cfg(test)]
150mod tests {
151 use super::*;
152
153 #[test]
154 fn a_normal_address_is_trimmed_and_lowercased() {
155 assert_eq!(
156 parse_email(" Ada.Lovelace@Example.COM ").unwrap(),
157 "ada.lovelace@example.com"
158 );
159 }
160
161 #[test]
162 fn look_alikes_do_not_fold_into_an_address() {
163 assert_ne!(
164 normalize_email("\u{a0}admin@example.test"),
165 "admin@example.test"
166 );
167 assert_ne!(
168 normalize_email("\u{212a}elvin@example.test"),
169 "kelvin@example.test"
170 );
171 assert!(parse_email("\u{a0}admin@example.test").is_err());
172 assert!(parse_email("\u{212a}elvin@example.test").is_err());
173 }
174
175 #[test]
176 fn display_names_are_trimmed_and_checked() {
177 assert_eq!(
178 parse_display_name(" Ada Lovelace ").unwrap(),
179 "Ada Lovelace"
180 );
181 assert_eq!(parse_display_name("Ayşe Çelik").unwrap(), "Ayşe Çelik");
182 let hundred = "a".repeat(MAX_NAME_CHARS);
183 assert!(parse_display_name(&hundred).is_ok());
184 for bad in [
185 "",
186 " ",
187 "a\u{0}b",
188 "ada\nlovelace",
189 "ada\tlovelace",
190 "\u{7}bell",
191 "evil\u{202E}name",
192 "\u{202A}ltr",
193 "isolate\u{2066}x",
194 "\u{2069}",
195 &"a".repeat(MAX_NAME_CHARS + 1),
196 ] {
197 assert!(parse_display_name(bad).is_err(), "accepted {bad:?}");
198 }
199 }
200
201 #[test]
202 fn form_text_loses_controls_and_multi_line_keeps_line_feed_and_tab() {
203 assert_eq!(strip_line_controls("a\u{0}b\u{7f}c\td\ne"), "abcde");
204 assert_eq!(strip_text_controls("a\r\nb\tc\u{0}d"), "a\nb\tcd");
205 }
206
207 #[test]
208 fn attack_strings_are_refused() {
209 let long_local = format!("{}@example.com", "a".repeat(MAX_LOCAL_LEN + 1));
210 let long_total = format!("a@{}.com", "b".repeat(250));
211 for bad in [
212 "",
213 "ada",
214 "@example.com",
215 "ada@",
216 "ada@@example.com",
217 "ada@example",
218 "ada@.example.com",
219 "ada@example..com",
220 "ada@example.com.",
221 "ada@-example.com",
222 "ada@example-.com",
223 "a da@example.com",
224 "ada@exam\nple.com",
225 "ada\u{0}@example.com",
226 "ada\u{202e}@example.com",
227 "\u{ff41}da@example.com",
228 "ada@exam\u{430}le.com",
229 ".ada@example.com",
230 "ada.@example.com",
231 "ada..x@example.com",
232 "ada@example.c om",
233 "ada@example.com/",
234 "ada@ex\tample.com",
235 &long_local,
236 &long_total,
237 ] {
238 assert!(parse_email(bad).is_err(), "accepted {bad:?}");
239 }
240 }
241}