mailrs-dmarc 1.1.0

DMARC (RFC 7489) aggregate report generation: result recording, XML report builder, report-mail formatter, rua extraction. Pluggable store trait with a Postgres reference impl.
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
//! DMARC evaluation (RFC 7489 §6.6).
//!
//! Combines an SPF result, zero or more DKIM-Signature results, and a
//! published [`DmarcPolicy`] into a final DMARC outcome:
//!
//! ```text
//! aligned_spf_pass   = (SPF result == pass)  AND  spf_domain aligned with from_domain
//! aligned_dkim_pass  = any DKIM signature with (result == pass AND d= aligned with from_domain)
//! dmarc_pass         = aligned_spf_pass OR aligned_dkim_pass
//!
//! disposition = dmarc_pass ? None
//!                          : (subdomain? policy.subdomain_policy : policy.policy)
//!                            modulated by pct=
//! ```
//!
//! Notes:
//! * **`pct=` sampling** isn't done here — we surface the policy and let
//!   the caller's RNG decide. (Stateless eval keeps the function pure.)
//! * **No DNS lookup** here. Caller resolves the TXT record and hands
//!   the parsed [`DmarcPolicy`] in.
//! * **Subdomain detection** — if `from_domain != policy_domain`, we
//!   apply `subdomain_policy` instead of `policy`.

use crate::align::check as align_check;
use crate::policy::{DmarcPolicy, PolicyAction};

/// One DKIM signature's verification verdict + identifying domain.
#[derive(Debug, Clone)]
pub struct DkimSignatureResult {
    /// `d=` value from the DKIM-Signature header.
    pub d_domain: String,
    /// Whether this signature verified (RSA-SHA256 / Ed25519-SHA256).
    /// Per RFC 7489 §3.1.1, only `pass` results contribute to DMARC.
    pub pass: bool,
}

/// SPF verification context for DMARC.
#[derive(Debug, Clone)]
pub struct SpfResult {
    /// The MAIL FROM domain used in the SPF check (or HELO when MAIL FROM was empty).
    pub domain: String,
    /// Whether the SPF result was `pass`.
    pub pass: bool,
}

/// Input bundle for [`evaluate`]. All fields are owned because the
/// outcome's `reason` strings borrow from them in some implementations.
#[derive(Debug, Clone)]
pub struct DmarcInput {
    /// RFC 5322 `From:` header domain — the identity DMARC anchors on.
    pub from_domain: String,
    /// The domain whose `_dmarc.<domain>` TXT we used. Equal to `from_domain`
    /// when the From: domain has a policy directly; otherwise the org domain.
    pub policy_domain: String,
    /// SPF result (or absent if SPF wasn't checked / errored).
    pub spf: Option<SpfResult>,
    /// All DKIM signatures observed on the message.
    pub dkim: Vec<DkimSignatureResult>,
}

/// DMARC outcome including the per-authn alignment outcomes (used for
/// the `Authentication-Results` header + aggregate reports).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DmarcOutcome {
    /// `true` when SPF passed and its domain aligned with From.
    pub aligned_spf_pass: bool,
    /// `true` when at least one DKIM signature passed AND its d=
    /// aligned with From.
    pub aligned_dkim_pass: bool,
    /// The DMARC verdict — `pass` if either aligned-auth passed.
    pub dmarc_pass: bool,
    /// Disposition the policy specifies for this message.
    /// `pass` → always `None`; `fail` → the policy's `p=`/`sp=` choice.
    /// Caller should still apply `pct=` sampling before enforcing.
    pub disposition: PolicyAction,
    /// Human-readable reason fragment for the AuthResults header
    /// (`policy.dmarc=fail (p=reject, sp=quarantine, ...)`).
    pub reason: String,
    /// Echo of the policy's `pct=` value, so the caller can sample.
    pub pct: u8,
}

/// Per RFC 7489 §6.6.3, the disposition is determined by whether the
/// From: domain matches the organizational domain (`p=`) or is a
/// subdomain of it (`sp=`).
fn pick_disposition(input: &DmarcInput, policy: &DmarcPolicy) -> PolicyAction {
    let from = input.from_domain.trim().trim_end_matches('.').to_ascii_lowercase();
    let pol = input.policy_domain.trim().trim_end_matches('.').to_ascii_lowercase();
    if from == pol {
        policy.policy
    } else {
        policy.subdomain_policy
    }
}

/// Evaluate DMARC for one message.
///
/// Pure function: no DNS, no clock, no RNG. Determinism in, determinism out.
///
/// # Example
///
/// ```
/// use mailrs_dmarc::eval::{evaluate, DkimSignatureResult, DmarcInput, SpfResult};
/// use mailrs_dmarc::policy::{DmarcPolicy, PolicyAction};
///
/// let policy = DmarcPolicy::parse("v=DMARC1; p=reject").unwrap();
/// let input = DmarcInput {
///     from_domain: "alice@example.com".rsplit('@').next().unwrap().to_string(),
///     policy_domain: "example.com".to_string(),
///     spf: Some(SpfResult { domain: "mail.example.com".into(), pass: true }),
///     dkim: vec![],
/// };
/// let outcome = evaluate(&policy, &input);
/// assert!(outcome.aligned_spf_pass);
/// assert!(outcome.dmarc_pass);
/// assert_eq!(outcome.disposition, PolicyAction::None);
/// ```
pub fn evaluate(policy: &DmarcPolicy, input: &DmarcInput) -> DmarcOutcome {
    // Aligned SPF: pass AND aligned under `aspf` mode.
    let aligned_spf_pass = match input.spf.as_ref() {
        Some(spf) if spf.pass => align_check(&spf.domain, &input.from_domain, policy.aspf).is_aligned(),
        _ => false,
    };

    // Aligned DKIM: any signature pass-and-aligned wins.
    let aligned_dkim_pass = input.dkim.iter().any(|sig| {
        sig.pass && align_check(&sig.d_domain, &input.from_domain, policy.adkim).is_aligned()
    });

    let dmarc_pass = aligned_spf_pass || aligned_dkim_pass;

    let disposition = if dmarc_pass {
        PolicyAction::None
    } else {
        pick_disposition(input, policy)
    };

    let reason = format_reason(policy, input, aligned_spf_pass, aligned_dkim_pass);

    DmarcOutcome {
        aligned_spf_pass,
        aligned_dkim_pass,
        dmarc_pass,
        disposition,
        reason,
        pct: policy.pct,
    }
}

fn format_reason(
    policy: &DmarcPolicy,
    input: &DmarcInput,
    spf_pass: bool,
    dkim_pass: bool,
) -> String {
    let mut s = String::with_capacity(64);
    if spf_pass {
        s.push_str("aligned-spf=pass");
    } else if let Some(spf) = input.spf.as_ref() {
        s.push_str(if spf.pass {
            "aligned-spf=misaligned"
        } else {
            "aligned-spf=fail"
        });
    } else {
        s.push_str("aligned-spf=absent");
    }
    s.push_str("; ");
    if dkim_pass {
        s.push_str("aligned-dkim=pass");
    } else if input.dkim.iter().any(|d| d.pass) {
        s.push_str("aligned-dkim=misaligned");
    } else if input.dkim.is_empty() {
        s.push_str("aligned-dkim=absent");
    } else {
        s.push_str("aligned-dkim=fail");
    }
    s.push_str(&format!(
        "; p={}, sp={}, adkim={}, aspf={}, pct={}",
        policy.policy, policy.subdomain_policy, policy.adkim, policy.aspf, policy.pct
    ));
    s
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::policy::Alignment;

    fn policy_with(p: PolicyAction) -> DmarcPolicy {
        DmarcPolicy {
            policy: p,
            subdomain_policy: p,
            ..DmarcPolicy::default()
        }
    }

    fn input_from(from: &str, policy_domain: &str) -> DmarcInput {
        DmarcInput {
            from_domain: from.into(),
            policy_domain: policy_domain.into(),
            spf: None,
            dkim: vec![],
        }
    }

    #[test]
    fn pass_via_aligned_spf_only() {
        let mut input = input_from("example.com", "example.com");
        input.spf = Some(SpfResult {
            domain: "example.com".into(),
            pass: true,
        });
        let out = evaluate(&policy_with(PolicyAction::Reject), &input);
        assert!(out.aligned_spf_pass);
        assert!(!out.aligned_dkim_pass);
        assert!(out.dmarc_pass);
        assert_eq!(out.disposition, PolicyAction::None);
    }

    #[test]
    fn pass_via_aligned_dkim_only() {
        let mut input = input_from("example.com", "example.com");
        input.dkim = vec![DkimSignatureResult {
            d_domain: "example.com".into(),
            pass: true,
        }];
        let out = evaluate(&policy_with(PolicyAction::Reject), &input);
        assert!(!out.aligned_spf_pass);
        assert!(out.aligned_dkim_pass);
        assert!(out.dmarc_pass);
    }

    #[test]
    fn fail_when_spf_misaligned() {
        let mut input = input_from("example.com", "example.com");
        input.spf = Some(SpfResult {
            domain: "different.com".into(),
            pass: true,
        });
        let out = evaluate(&policy_with(PolicyAction::Reject), &input);
        assert!(!out.aligned_spf_pass);
        assert!(!out.dmarc_pass);
        assert_eq!(out.disposition, PolicyAction::Reject);
    }

    #[test]
    fn fail_when_dkim_misaligned() {
        let mut input = input_from("example.com", "example.com");
        input.dkim = vec![DkimSignatureResult {
            d_domain: "attacker.com".into(),
            pass: true,
        }];
        let out = evaluate(&policy_with(PolicyAction::Quarantine), &input);
        assert!(!out.aligned_dkim_pass);
        assert!(!out.dmarc_pass);
        assert_eq!(out.disposition, PolicyAction::Quarantine);
    }

    #[test]
    fn fail_when_spf_fail_but_aligned() {
        let mut input = input_from("example.com", "example.com");
        input.spf = Some(SpfResult {
            domain: "example.com".into(),
            pass: false,
        });
        let out = evaluate(&policy_with(PolicyAction::Reject), &input);
        assert!(!out.aligned_spf_pass);
        assert!(!out.dmarc_pass);
    }

    #[test]
    fn relaxed_alignment_subdomain_passes() {
        let mut input = input_from("example.com", "example.com");
        input.spf = Some(SpfResult {
            domain: "mail.example.com".into(),
            pass: true,
        });
        let out = evaluate(&policy_with(PolicyAction::Reject), &input);
        assert!(out.aligned_spf_pass);
    }

    #[test]
    fn strict_alignment_subdomain_fails() {
        let p = DmarcPolicy {
            policy: PolicyAction::Reject,
            subdomain_policy: PolicyAction::Reject,
            aspf: Alignment::Strict,
            adkim: Alignment::Strict,
            ..DmarcPolicy::default()
        };
        let mut input = input_from("example.com", "example.com");
        input.spf = Some(SpfResult {
            domain: "mail.example.com".into(),
            pass: true,
        });
        let out = evaluate(&p, &input);
        assert!(!out.aligned_spf_pass);
        assert_eq!(out.disposition, PolicyAction::Reject);
    }

    #[test]
    fn subdomain_uses_sp_policy() {
        let p = DmarcPolicy {
            policy: PolicyAction::Reject,
            subdomain_policy: PolicyAction::Quarantine,
            ..DmarcPolicy::default()
        };
        let input = input_from("sub.example.com", "example.com");
        let out = evaluate(&p, &input);
        assert!(!out.dmarc_pass);
        assert_eq!(out.disposition, PolicyAction::Quarantine);
    }

    #[test]
    fn dkim_pass_wins_even_when_spf_fails() {
        let mut input = input_from("example.com", "example.com");
        input.spf = Some(SpfResult {
            domain: "wrong.com".into(),
            pass: true,
        });
        input.dkim = vec![DkimSignatureResult {
            d_domain: "mail.example.com".into(),
            pass: true,
        }];
        let out = evaluate(&policy_with(PolicyAction::Reject), &input);
        assert!(!out.aligned_spf_pass);
        assert!(out.aligned_dkim_pass);
        assert!(out.dmarc_pass);
    }

    #[test]
    fn first_passing_aligned_dkim_signature_wins() {
        let mut input = input_from("example.com", "example.com");
        input.dkim = vec![
            // First sig: wrong domain
            DkimSignatureResult {
                d_domain: "attacker.com".into(),
                pass: true,
            },
            // Second sig: correct domain, passes
            DkimSignatureResult {
                d_domain: "example.com".into(),
                pass: true,
            },
        ];
        let out = evaluate(&policy_with(PolicyAction::Reject), &input);
        assert!(out.aligned_dkim_pass);
    }

    #[test]
    fn dkim_signatures_that_dont_pass_dont_count() {
        let mut input = input_from("example.com", "example.com");
        input.dkim = vec![DkimSignatureResult {
            d_domain: "example.com".into(),
            pass: false,
        }];
        let out = evaluate(&policy_with(PolicyAction::Reject), &input);
        assert!(!out.aligned_dkim_pass);
    }

    #[test]
    fn no_auth_data_fails_dmarc() {
        let input = input_from("example.com", "example.com");
        let out = evaluate(&policy_with(PolicyAction::Reject), &input);
        assert!(!out.dmarc_pass);
        assert_eq!(out.disposition, PolicyAction::Reject);
    }

    #[test]
    fn reason_string_captures_state() {
        let mut input = input_from("example.com", "example.com");
        input.spf = Some(SpfResult {
            domain: "example.com".into(),
            pass: true,
        });
        let out = evaluate(&policy_with(PolicyAction::Reject), &input);
        assert!(out.reason.contains("aligned-spf=pass"));
        assert!(out.reason.contains("aligned-dkim=absent"));
        assert!(out.reason.contains("p=reject"));
    }

    #[test]
    fn pct_passes_through() {
        let p = DmarcPolicy {
            policy: PolicyAction::Reject,
            pct: 25,
            ..DmarcPolicy::default()
        };
        let input = input_from("example.com", "example.com");
        let out = evaluate(&p, &input);
        assert_eq!(out.pct, 25);
    }

    #[test]
    fn relaxed_default_co_uk_subdomain_aligns() {
        // From: news@example.co.uk
        // SPF MAIL FROM: bounces@mail.example.co.uk
        let mut input = input_from("example.co.uk", "example.co.uk");
        input.spf = Some(SpfResult {
            domain: "mail.example.co.uk".into(),
            pass: true,
        });
        let out = evaluate(&policy_with(PolicyAction::Reject), &input);
        assert!(out.aligned_spf_pass);
    }
}