structured-email-address 0.0.19

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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
use super::*;
use alloc::format;

// ── 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_scope() accessor ──

#[test]
fn domain_scope_reads_the_address_that_parsed() {
    // The accessor over the whole pipeline, rather than over a domain string:
    // what it classifies is the canonical domain, so an IDN name and a literal
    // both arrive here in the form the parse settled on.
    let config = Config::builder()
        .allow_single_label_domain()
        .allow_address_literal_rfc5321()
        .build();
    let scope = |input: &str| {
        EmailAddress::parse_with(input, &config)
            .unwrap_or_else(|e| panic!("{input} must parse: {e}"))
            .domain_scope()
    };

    assert_eq!(scope("a@example.com"), DomainScope::Global);
    assert_eq!(scope("a@münchen.de"), DomainScope::Global);
    assert_eq!(scope("admin@printer"), DomainScope::Local);
    assert_eq!(scope("a@host.local"), DomainScope::Local);
    assert_eq!(
        scope("a@[192.168.1.5]"),
        DomainScope::Literal(LiteralScope::Ipv4(IpScope::Local))
    );
    assert_eq!(
        scope("a@[IPv6:fd00::1]"),
        DomainScope::Literal(LiteralScope::Ipv6(IpScope::Local))
    );
    assert_eq!(
        scope("a@[192.0.2.1]"),
        DomainScope::Literal(LiteralScope::Ipv4(IpScope::Global))
    );
    assert_eq!(
        scope("postmaster@[AS400:QSYS]"),
        DomainScope::Literal(LiteralScope::General)
    );
}

#[test]
fn domain_scope_does_not_call_a_bounded_address_global() {
    // Through the public API, because that is where a caller reading
    // `is_global()` would be misled: neither of these leaves the network it is
    // sent on, so reporting either as globally reachable is a false statement
    // about the address, whatever the caller then does with it.
    let config = Config::builder().allow_address_literal_rfc5321().build();
    let scope = |input: &str| {
        EmailAddress::parse_with(input, &config)
            .unwrap_or_else(|e| panic!("{input} must parse: {e}"))
            .domain_scope()
    };

    assert_eq!(
        scope("a@[255.255.255.255]"),
        DomainScope::Literal(LiteralScope::Ipv4(IpScope::Local))
    );
    assert_eq!(
        scope("a@[IPv6:ff02::1]"),
        DomainScope::Literal(LiteralScope::Ipv6(IpScope::Local))
    );
    assert!(!scope("a@[255.255.255.255]").is_global());
    assert!(!scope("a@[IPv6:ff02::1]").is_global());
}

#[test]
fn domain_scope_reads_the_canonical_case() {
    // The reserved names are matched literally, which is only sound because the
    // domain arrives lowercased. Pin it: an address shouted in capitals must
    // classify the same as the same address in lower case.
    let config = Config::builder().preserve_case().build();
    let shouted =
        EmailAddress::parse_with("A@FILES.LOCAL", &config).unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(shouted.domain_scope(), DomainScope::Local);
}

#[test]
fn domain_scope_changes_no_verdict() {
    // The classification is an accessor over an address that already parsed:
    // asking for it must not change what parses, and a name it calls Local must
    // still be refused by a config that refuses single labels.
    assert!("admin@printer".parse::<EmailAddress>().is_err());
    assert!("a@host.local".parse::<EmailAddress>().is_ok());
    assert!("a@[192.168.1.5]".parse::<EmailAddress>().is_err());
}

// ── 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"),
        }
    }
}