structured-email-address 0.0.12

RFC 5321/5322/6531 email address parser, validator, and normalizer. Subaddress extraction, provider-aware normalization, PSL domain validation, anti-homoglyph protection.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use super::*;

// ── FromStr (default config) ──

#[test]
fn parse_simple() {
    let email: EmailAddress = "user@example.com".parse().unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(email.local_part(), "user");
    assert_eq!(email.domain(), "example.com");
    assert_eq!(email.tag(), None);
    assert_eq!(email.canonical(), "user@example.com");
}

#[test]
fn parse_with_tag() {
    let email: EmailAddress = "user+newsletter@example.com"
        .parse()
        .unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(email.local_part(), "user+newsletter");
    assert_eq!(email.tag(), Some("newsletter"));
}

#[test]
fn display_format() {
    let email: EmailAddress = "user@example.com".parse().unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(format!("{email}"), "user@example.com");
}

#[test]
fn display_name_escaping() {
    let config = Config::builder().allow_display_name().build();
    // Display name with quotes should be escaped
    let email = EmailAddress::parse_with("John \"Johnny\" Doe <user@example.com>", &config)
        .unwrap_or_else(|e| panic!("{e}"));
    let formatted = format!("{email}");
    assert!(
        formatted.contains("\\\"Johnny\\\""),
        "Expected escaped quotes in: {formatted}"
    );
}

#[test]
fn equality_by_canonical() {
    let a: EmailAddress = "user@example.com".parse().unwrap_or_else(|e| panic!("{e}"));
    let b: EmailAddress = "user@Example.COM".parse().unwrap_or_else(|e| panic!("{e}"));
    // Default config: domain-only lowercase, so local parts same case → equal
    assert_eq!(a, b);
}

#[test]
fn freemail_detection() {
    let email: EmailAddress = "user@gmail.com".parse().unwrap_or_else(|e| panic!("{e}"));
    assert!(email.is_freemail());

    let email: EmailAddress = "user@company.com".parse().unwrap_or_else(|e| panic!("{e}"));
    assert!(!email.is_freemail());
}

#[test]
fn freemail_via_custom_provider() {
    // A registered custom provider marked freemail is reported by is_freemail().
    use crate::ProviderRule;
    let config = Config::builder()
        .add_provider(ProviderRule::new(["freebie.example"]).freemail(true))
        .build();
    let email =
        EmailAddress::parse_with("user@freebie.example", &config).unwrap_or_else(|e| panic!("{e}"));
    assert!(email.is_freemail());
}

// ── Provider-aware normalization (#5) ──

#[test]
fn provider_aware_gmail_normalizes_by_rule() {
    // provider_aware applies Gmail's rule (strip dots, fold case, '+' tag)
    // without setting any global dot/case policy. strip_subaddress drops the
    // extracted tag from the canonical form.
    let config = Config::builder()
        .provider_aware()
        .strip_subaddress()
        .build();
    let email = EmailAddress::parse_with("A.Li.Ce+promo@Gmail.com", &config)
        .unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(email.local_part(), "alice");
    assert_eq!(email.tag(), Some("promo"));
    assert_eq!(email.domain(), "gmail.com");
}

#[test]
fn provider_aware_gmail_preserves_tag_by_default() {
    // Default subaddress policy keeps the tag in the canonical local part;
    // dots are still stripped and case folded by the Gmail rule.
    let config = Config::builder().provider_aware().build();
    let email = EmailAddress::parse_with("A.Li.Ce+promo@Gmail.com", &config)
        .unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(email.local_part(), "alice+promo");
    assert_eq!(email.tag(), Some("promo"));
}

#[test]
fn provider_aware_leaves_non_provider_domains_to_global_policy() {
    // A non-provider domain is untouched by provider rules: dots preserved,
    // local-part case preserved (global defaults).
    let config = Config::builder().provider_aware().build();
    let email = EmailAddress::parse_with("A.L.I.C.E@example.com", &config)
        .unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(email.local_part(), "A.L.I.C.E");
    assert_eq!(email.domain(), "example.com");
}

#[test]
fn provider_aware_quoted_local_preserves_case() {
    // A quoted local-part is literal: the provider rule's case folding
    // (Gmail) must NOT apply inside it, just as dots and the subaddress
    // separator don't. Without a global lowercase policy, case is preserved.
    let config = Config::builder().provider_aware().build();
    let email =
        EmailAddress::parse_with("\"A.B\"@gmail.com", &config).unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(email.local_part(), "A.B");

    // A global lowercase policy is not provider-specific, so it still folds
    // a quoted local-part — even when a provider rule matches (the rule's
    // own folding is skipped for quoted, but the global policy still applies).
    let config = Config::builder().provider_aware().lowercase_all().build();
    let email =
        EmailAddress::parse_with("\"A.B\"@gmail.com", &config).unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(email.local_part(), "a.b");
}

#[test]
fn provider_aware_off_does_not_strip_gmail_dots() {
    // Without provider_aware and without dots_gmail_only, gmail dots stay.
    let email: EmailAddress = "a.b.c@gmail.com".parse().unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(email.local_part(), "a.b.c");
}

#[test]
fn custom_provider_aware_rule_applies() {
    use crate::ProviderRule;
    // Custom provider: strips dots, '-' separator.
    let config = Config::builder()
        .provider_aware()
        .strip_subaddress()
        .add_provider(
            ProviderRule::new(["corp.example"])
                .strip_dots(true)
                .lowercase_local(true)
                .subaddress_separator(Some('-')),
        )
        .build();
    let email = EmailAddress::parse_with("John.Doe-tag@corp.example", &config)
        .unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(email.local_part(), "johndoe");
    assert_eq!(email.tag(), Some("tag"));
}

#[test]
fn idn_provider_rule_consistent_across_normalization_and_freemail() {
    use crate::ProviderRule;
    // A provider rule registered with the Unicode domain must apply to the
    // IDNA-encoded address for BOTH provider-aware normalization and
    // is_freemail() — the canonical domain is used at both call sites.
    let config = Config::builder()
        .provider_aware()
        .add_provider(
            ProviderRule::new(["münchen.de"])
                .strip_dots(true)
                .lowercase_local(true)
                .freemail(true),
        )
        .build();
    let email =
        EmailAddress::parse_with("A.B@münchen.de", &config).unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(email.domain(), "xn--mnchen-3ya.de");
    assert_eq!(
        email.local_part(),
        "ab",
        "provider rule strips dots + folds case"
    );
    assert!(email.is_freemail(), "same rule drives is_freemail");
}

#[test]
fn dots_gmail_only_ignores_custom_providers() {
    use crate::ProviderRule;
    // GmailOnly is a legacy mode tied to the built-in dot-stripping providers
    // (Gmail/Googlemail). Custom providers affect normalization ONLY under
    // provider_aware(); a custom strip_dots rule must NOT leak into GmailOnly
    // when provider_aware is off.
    let config = Config::builder()
        .dots_gmail_only()
        .add_provider(ProviderRule::new(["corp.example"]).strip_dots(true))
        .build();

    // The custom provider's strip_dots is ignored: dots are preserved.
    let email =
        EmailAddress::parse_with("a.b@corp.example", &config).unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(email.local_part(), "a.b");

    // Built-in Gmail still strips dots under GmailOnly.
    let email =
        EmailAddress::parse_with("a.b.c@gmail.com", &config).unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(email.local_part(), "abc");
}

// ── Configured parsing ──

#[test]
fn full_normalization_pipeline() {
    let config = Config::builder()
        .strip_subaddress()
        .dots_gmail_only()
        .lowercase_all()
        .check_confusables()
        .build();

    let email = EmailAddress::parse_with("A.L.I.C.E+promo@Gmail.COM", &config)
        .unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(email.canonical(), "alice@gmail.com");
    assert_eq!(email.tag(), Some("promo"));
    assert!(email.skeleton().is_some());
}

#[test]
fn display_name_parsing() {
    let config = Config::builder().allow_display_name().build();

    let email = EmailAddress::parse_with("John Doe <user@example.com>", &config)
        .unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(email.display_name(), Some("John Doe"));
    assert_eq!(email.local_part(), "user");
    assert_eq!(email.domain(), "example.com");
}

#[test]
fn leading_comment_full_pipeline() {
    // #40: a leading RFC 5322 comment before the local-part must parse
    // end-to-end, with the comment stripped from the canonical address.
    let config = Config::builder()
        .strictness(Strictness::Lax)
        .allow_display_name()
        .allow_domain_literal()
        .allow_single_label_domain()
        .lowercase_all()
        .build();

    for input in [
        "(comment)jane.smith@example.com",
        "jane(comment).smith@example.com",
        "jane.smith(comment)@example.com",
        "jane.smith@example.com",
    ] {
        let email = EmailAddress::parse_with(input, &config)
            .unwrap_or_else(|e| panic!("'{input}' must parse: {e}"));
        assert_eq!(email.canonical(), "jane.smith@example.com");
    }
}

#[test]
fn rejects_newline_in_address() {
    // Header-injection hardening: a trailing newline must not be silently
    // accepted (it previously survived an over-eager input.trim()).
    let config = Config::default();
    assert!("user@example.com\n".parse::<EmailAddress>().is_err());
    assert!(EmailAddress::parse_with("user@example.com\r\n", &config).is_err());
}

// ── Serde ──

#[cfg(feature = "serde")]
#[test]
fn serde_roundtrip() {
    let email: EmailAddress = "user@example.com".parse().unwrap_or_else(|e| panic!("{e}"));
    let json = serde_json::to_string(&email).unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(json, "\"user@example.com\"");

    let back: EmailAddress = serde_json::from_str(&json).unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(email, back);
}

// ── Validation errors ──

#[test]
fn rejects_empty() {
    let result: Result<EmailAddress, _> = "".parse();
    assert!(result.is_err());
}

#[test]
fn rejects_no_domain_dot() {
    let result: Result<EmailAddress, _> = "user@localhost".parse();
    assert!(result.is_err());
    assert!(matches!(result.unwrap_err().kind(), ErrorKind::DomainNoDot));
}

#[test]
fn allows_single_label_when_configured() {
    let config = Config::builder().allow_single_label_domain().build();
    let email =
        EmailAddress::parse_with("user@localhost", &config).unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(email.domain(), "localhost");
}

// ── Batch parsing ──

#[test]
fn batch_parse_mixed_results() {
    // Verifies that parse_batch returns Ok for valid and Err for invalid
    // inputs, preserving input order.
    let config = Config::default();
    let results = EmailAddress::parse_batch(
        &["alice@example.com", "invalid", "bob@example.org"],
        &config,
    );
    assert_eq!(results.len(), 3);
    assert!(results[0].is_ok());
    assert!(results[1].is_err());
    assert!(results[2].is_ok());
    assert_eq!(results[0].as_ref().map(|e| e.domain()), Ok("example.com"));
    assert_eq!(results[2].as_ref().map(|e| e.domain()), Ok("example.org"));
}

#[test]
fn batch_parse_empty_input() {
    // Empty slice returns empty vec.
    let config = Config::default();
    let results = EmailAddress::parse_batch(&[], &config);
    assert!(results.is_empty());
}

#[test]
fn batch_parse_all_valid() {
    // Batch of valid addresses all succeed.
    let config = Config::default();
    let inputs = &["a@b.com", "x@y.org", "test+tag@example.com"];
    let results = EmailAddress::parse_batch(inputs, &config);
    assert!(results.iter().all(|r| r.is_ok()));
}

#[test]
fn batch_parse_all_invalid() {
    // Batch of invalid addresses all fail.
    let config = Config::default();
    let results = EmailAddress::parse_batch(&["", "noatsign", "@missing-local.com"], &config);
    assert!(results.iter().all(|r| r.is_err()));
}

#[test]
fn batch_parse_with_config() {
    // Batch parsing respects config (e.g., subaddress stripping).
    let config = Config::builder()
        .strip_subaddress()
        .dots_gmail_only()
        .lowercase_all()
        .build();
    let results =
        EmailAddress::parse_batch(&["A.L.I.C.E+promo@Gmail.COM", "BOB@example.com"], &config);
    assert_eq!(results.len(), 2);
    assert_eq!(
        results[0].as_ref().map(|e| e.canonical()),
        Ok("alice@gmail.com".to_string())
    );
    assert_eq!(
        results[1].as_ref().map(|e| e.canonical()),
        Ok("bob@example.com".to_string())
    );
}

// ── domain_unicode() accessor ──

#[test]
fn domain_unicode_roundtrip() {
    // IDN domain: input Unicode → domain() punycode → domain_unicode() back to Unicode.
    let email: EmailAddress = "user@münchen.de".parse().unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(email.domain(), "xn--mnchen-3ya.de");
    assert_eq!(email.domain_unicode(), "münchen.de");
}

#[test]
fn domain_unicode_ascii_fallback() {
    // ASCII domain: domain_unicode() returns same as domain().
    let email: EmailAddress = "user@example.com".parse().unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(email.domain_unicode(), "example.com");
    assert_eq!(email.domain_unicode(), email.domain());
}

#[test]
fn domain_unicode_mixed_labels() {
    // Domain with one IDN label and one ASCII label.
    let email: EmailAddress = "user@über.example.com"
        .parse()
        .unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(email.domain(), "xn--ber-goa.example.com");
    assert_eq!(email.domain_unicode(), "über.example.com");
}

#[test]
fn domain_unicode_japanese() {
    // Japanese domain roundtrip.
    let email: EmailAddress = "user@例え.jp".parse().unwrap_or_else(|e| panic!("{e}"));
    assert!(email.domain().contains("xn--"));
    assert_eq!(email.domain_unicode(), "例え.jp");
}

#[cfg(feature = "rayon")]
#[test]
fn batch_par_matches_sequential() {
    // Parallel variant produces identical results to sequential.
    let config = Config::builder().strip_subaddress().lowercase_all().build();
    let inputs = &[
        "alice@example.com",
        "invalid",
        "BOB+tag@Example.ORG",
        "",
        "user@test.com",
    ];
    let seq = EmailAddress::parse_batch(inputs, &config);
    let par = EmailAddress::parse_batch_par(inputs, &config);
    assert_eq!(seq.len(), par.len());
    for (i, (s, p)) in seq.iter().zip(par.iter()).enumerate() {
        match (s, p) {
            (Ok(a), Ok(b)) => assert_eq!(a, b, "result {i} diverges"),
            (Err(a), Err(b)) => assert_eq!(a, b, "error {i} diverges: {a} vs {b}"),
            _ => panic!("result {i}: one Ok, one Err"),
        }
    }
}