Skip to main content

mailrs_arf/
lib.rs

1#![doc = include_str!("../README.md")]
2#![deny(missing_docs)]
3#![deny(rustdoc::broken_intra_doc_links)]
4
5//! Internal layout: [`parse`] does the full one-shot extraction.
6//! Helpers (`is_arf`, header continuation handling) are private —
7//! the public surface is intentionally a single function returning
8//! a single struct.
9
10mod build;
11pub use build::{ReportSpec, build};
12
13/// Parsed RFC 5965 ARF feedback report.
14///
15/// All fields are owned `String` (not `&str`) — callers typically
16/// persist these into a suppression-list DB or fire a webhook, so
17/// borrow-from-input would be hostile to the typical use case. Cost
18/// is one short allocation per non-empty field.
19///
20/// Fields default to `None` (or `"abuse"` for `feedback_type`) when
21/// the report omits them. Per RFC 5965 §3.2 the only `MUST`-present
22/// field on the `message/feedback-report` part is `Feedback-Type`,
23/// `User-Agent`, and `Version` — everything else is `SHOULD` or
24/// optional, so be ready for `None`.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct Report {
27    /// Feedback-Type (§3.1) — `abuse`, `fraud`, `not-spam`,
28    /// `virus`, `other`, etc. Lowercase normalized. Defaults to
29    /// `"abuse"` if the header is absent (some FBL providers omit
30    /// it for the most common case).
31    pub feedback_type: String,
32    /// User-Agent (§3.1) — software / version that produced this
33    /// report.
34    pub user_agent: Option<String>,
35    /// Version (§3.1) — ARF version. RFC 5965 uses `"1"`.
36    pub version: Option<String>,
37    /// Original-Mail-From (§3.2) — envelope From of the complained-
38    /// about message. Angle brackets stripped. Lowercase normalized.
39    pub original_mail_from: Option<String>,
40    /// Original-Rcpt-To (§3.2) — envelope recipient who complained.
41    /// Angle brackets stripped. Lowercase normalized.
42    pub original_rcpt_to: Option<String>,
43    /// Arrival-Date (§3.2) — when the complained-about message
44    /// arrived at the FBL provider.
45    pub arrival_date: Option<String>,
46    /// Source-IP (§3.2) — the IP that delivered the complained-
47    /// about message to the FBL provider.
48    pub source_ip: Option<String>,
49    /// Reported-Domain (§3.2) — domain of the sender as the FBL
50    /// provider sees it. Lowercase normalized.
51    pub reported_domain: Option<String>,
52    /// Reported-URI (§3.2) — URI inside the complained-about
53    /// message body (typically `mailto:` or `http(s):` link). If
54    /// the report has multiple `Reported-URI:` headers, only the
55    /// first is kept; downstream callers needing all of them should
56    /// parse the raw multipart themselves.
57    pub reported_uri: Option<String>,
58    /// Authentication-Results (§3.2) — RFC 8601-formatted auth
59    /// verdict captured by the FBL provider at receipt time.
60    pub authentication_results: Option<String>,
61    /// Incidents (§3.2) — when the FBL provider aggregates multiple
62    /// reports, this counts how many distinct complaints this one
63    /// report represents.
64    pub incidents: Option<String>,
65}
66
67impl Report {
68    /// Convenience: the most actionable single fact in any ARF
69    /// report — who complained. Falls back to `original_mail_from`
70    /// when the report omits `Original-Rcpt-To` (older FBL formats
71    /// invert which one is present).
72    ///
73    /// Returns `None` if neither header is present, which means the
74    /// report is structurally invalid and should be logged + dropped.
75    #[must_use]
76    pub fn complainant(&self) -> Option<&str> {
77        self.original_rcpt_to
78            .as_deref()
79            .or(self.original_mail_from.as_deref())
80    }
81}
82
83/// Parse an RFC 5965 ARF feedback report from a full
84/// `multipart/report` message body.
85///
86/// Returns `None` if the input does not contain a
87/// `message/feedback-report` part marker (i.e. the input is not an
88/// ARF report at all). This is the fast cold-path early exit; the
89/// per-byte cost of the substring search is bounded by the message
90/// size.
91///
92/// On a positive identification, returns `Some(Report)` populated
93/// with every field that was present in the `message/feedback-report`
94/// part. Unknown / unparseable fields are silently skipped — the
95/// parser is tolerant of vendor-specific extensions and the
96/// pre-standard 0.x ARF format.
97///
98/// Does **not** attempt to validate the surrounding MIME boundary or
99/// verify the third (`message/rfc822`) part. If you need full MIME
100/// integrity, parse the input through `mailrs-mime` first and pass
101/// the `message/feedback-report` subpart's body to this function.
102///
103/// ```
104/// use mailrs_arf::parse;
105/// let report = parse(b"feedback-report\r\nFeedback-Type: abuse\r\n\
106///     Original-Rcpt-To: u@example.com\r\n");
107/// let r = report.unwrap();
108/// assert_eq!(r.feedback_type, "abuse");
109/// assert_eq!(r.original_rcpt_to.as_deref(), Some("u@example.com"));
110/// ```
111#[must_use]
112pub fn parse(message: &[u8]) -> Option<Report> {
113    if !is_arf(message) {
114        return None;
115    }
116
117    let mut feedback_type = "abuse".to_string();
118    let mut user_agent: Option<String> = None;
119    let mut version: Option<String> = None;
120    let mut original_mail_from: Option<String> = None;
121    let mut original_rcpt_to: Option<String> = None;
122    let mut arrival_date: Option<String> = None;
123    let mut source_ip: Option<String> = None;
124    let mut reported_domain: Option<String> = None;
125    let mut reported_uri: Option<String> = None;
126    let mut authentication_results: Option<String> = None;
127    let mut incidents: Option<String> = None;
128
129    for (key, value) in headers(message) {
130        let lower = key.to_ascii_lowercase();
131        match lower.as_str() {
132            "feedback-type" => feedback_type = value.to_ascii_lowercase(),
133            "user-agent" => user_agent = Some(value),
134            "version" => version = Some(value),
135            "original-mail-from" if original_mail_from.is_none() => {
136                original_mail_from = Some(strip_addr(&value));
137            }
138            "original-rcpt-to" if original_rcpt_to.is_none() => {
139                original_rcpt_to = Some(strip_addr(&value));
140            }
141            "arrival-date" if arrival_date.is_none() => arrival_date = Some(value),
142            "source-ip" if source_ip.is_none() => source_ip = Some(value),
143            "reported-domain" if reported_domain.is_none() => {
144                reported_domain = Some(value.to_ascii_lowercase());
145            }
146            "reported-uri" if reported_uri.is_none() => reported_uri = Some(value),
147            "authentication-results" if authentication_results.is_none() => {
148                authentication_results = Some(value);
149            }
150            "incidents" if incidents.is_none() => incidents = Some(value),
151            _ => {}
152        }
153    }
154
155    Some(Report {
156        feedback_type,
157        user_agent,
158        version,
159        original_mail_from,
160        original_rcpt_to,
161        arrival_date,
162        source_ip,
163        reported_domain,
164        reported_uri,
165        authentication_results,
166        incidents,
167    })
168}
169
170/// Fast cold-path: does this look like an ARF report at all?
171/// Identification rests on the literal `feedback-report` substring,
172/// which appears in every legitimate ARF report's
173/// `Content-Type: message/feedback-report` header. A 24-byte
174/// substring search across the whole input — fine for typical
175/// FBL message sizes (< 16 KB).
176fn is_arf(message: &[u8]) -> bool {
177    const MARKER: &[u8] = b"feedback-report";
178    memchr::memmem::find(message, MARKER).is_some()
179}
180
181/// Strip RFC 5322 `<addr>` angle brackets + lowercase. Used for
182/// the two envelope-address fields (`Original-Mail-From`,
183/// `Original-Rcpt-To`) so downstream suppression-list lookups can
184/// use the value as a key directly.
185fn strip_addr(value: &str) -> String {
186    value
187        .trim_start_matches('<')
188        .trim_end_matches('>')
189        .to_ascii_lowercase()
190}
191
192/// Walk every header-shaped line in the input, across MIME part
193/// boundaries. ARF reports are nested inside a `multipart/report`
194/// envelope — the feedback fields we care about live in the second
195/// part's headers, after a blank line + boundary line + another set
196/// of part headers. Rather than re-implement a full MIME parser,
197/// we treat the whole input as a flat stream of headers: blank lines
198/// and `--boundary` lines reset the per-header continuation state
199/// but don't end iteration.
200///
201/// Continuation lines (RFC 5322 §2.2.3) starting with whitespace
202/// fold into the preceding header. The first occurrence of each
203/// header name wins (RFC 5965 §3.2 — each field appears at most once
204/// per report).
205fn headers(message: &[u8]) -> impl Iterator<Item = (&str, String)> + '_ {
206    let text = std::str::from_utf8(message).unwrap_or("");
207    HeaderIter {
208        lines: text.lines(),
209        pending: None,
210    }
211}
212
213struct HeaderIter<'a> {
214    lines: std::str::Lines<'a>,
215    pending: Option<(&'a str, String)>,
216}
217
218impl<'a> Iterator for HeaderIter<'a> {
219    type Item = (&'a str, String);
220
221    fn next(&mut self) -> Option<Self::Item> {
222        loop {
223            let line = match self.lines.next() {
224                Some(l) => l,
225                None => return self.pending.take(),
226            };
227            // Blank line or MIME boundary line: flush pending header
228            // and reset (next non-blank line starts a fresh header
229            // context).
230            if line.trim().is_empty() || line.starts_with("--") {
231                if let Some(out) = self.pending.take() {
232                    return Some(out);
233                }
234                continue;
235            }
236            if line.starts_with(' ') || line.starts_with('\t') {
237                // Continuation: append to pending value (separated
238                // by a single space per RFC 5322 §2.2.3 unfolding).
239                if let Some((_, ref mut value)) = self.pending {
240                    value.push(' ');
241                    value.push_str(line.trim());
242                    continue;
243                }
244                // Stray continuation with no preceding header —
245                // ignore (malformed input).
246                continue;
247            }
248            // Start of a new header. Yield the pending one first,
249            // then stash this line as the new pending.
250            let new_pending = line.split_once(':').map(|(k, v)| (k, v.trim().to_string()));
251            let out = self.pending.take();
252            self.pending = new_pending;
253            if out.is_some() {
254                return out;
255            }
256        }
257    }
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263
264    #[test]
265    fn parse_basic_arf() {
266        let msg = b"Content-Type: multipart/report; report-type=feedback-report\r\n\
267            \r\n\
268            --boundary\r\n\
269            Content-Type: message/feedback-report\r\n\
270            \r\n\
271            Feedback-Type: abuse\r\n\
272            Original-Rcpt-To: user@example.com\r\n";
273        let r = parse(msg).expect("ARF report");
274        assert_eq!(r.feedback_type, "abuse");
275        assert_eq!(r.original_rcpt_to.as_deref(), Some("user@example.com"));
276    }
277
278    #[test]
279    fn parse_not_arf_returns_none() {
280        let msg = b"Subject: Hello\r\n\r\nJust a normal email";
281        assert!(parse(msg).is_none());
282    }
283
284    #[test]
285    fn parse_strips_angle_brackets() {
286        let msg = b"feedback-report\r\nOriginal-Rcpt-To: <user@test.com>\r\n";
287        let r = parse(msg).unwrap();
288        assert_eq!(r.original_rcpt_to.as_deref(), Some("user@test.com"));
289    }
290
291    #[test]
292    fn parse_mail_from_fallback() {
293        let msg = b"feedback-report\r\n\
294            Feedback-Type: complaint\r\n\
295            Original-Mail-From: sender@x.com\r\n";
296        let r = parse(msg).unwrap();
297        assert_eq!(r.feedback_type, "complaint");
298        assert_eq!(r.complainant(), Some("sender@x.com"));
299        assert_eq!(r.original_rcpt_to, None);
300    }
301
302    #[test]
303    fn parse_hotmail_style_report() {
304        let msg = b"From: staff@hotmail.com\r\n\
305            Subject: complaint\r\n\
306            Content-Type: multipart/report; report-type=feedback-report\r\n\
307            \r\n\
308            --b\r\n\
309            Content-Type: message/feedback-report\r\n\
310            \r\n\
311            Feedback-Type: abuse\r\n\
312            User-Agent: Hotmail FBL\r\n\
313            Version: 1\r\n\
314            Original-Mail-From: <bulk@example.com>\r\n\
315            Original-Rcpt-To: <victim@hotmail.com>\r\n\
316            Arrival-Date: Sun, 25 May 2026 10:00:00 +0000\r\n\
317            Source-IP: 192.0.2.42\r\n\
318            Reported-Domain: example.com\r\n\
319            \r\n\
320            --b--\r\n";
321        let r = parse(msg).unwrap();
322        assert_eq!(r.feedback_type, "abuse");
323        assert_eq!(r.user_agent.as_deref(), Some("Hotmail FBL"));
324        assert_eq!(r.version.as_deref(), Some("1"));
325        assert_eq!(r.original_mail_from.as_deref(), Some("bulk@example.com"));
326        assert_eq!(r.original_rcpt_to.as_deref(), Some("victim@hotmail.com"));
327        assert_eq!(r.source_ip.as_deref(), Some("192.0.2.42"));
328        assert_eq!(r.reported_domain.as_deref(), Some("example.com"));
329    }
330
331    #[test]
332    fn parse_lowercase_normalizes_feedback_type() {
333        let msg = b"feedback-report\r\nFeedback-Type: ABUSE\r\n";
334        assert_eq!(parse(msg).unwrap().feedback_type, "abuse");
335    }
336
337    #[test]
338    fn parse_lowercase_normalizes_addresses() {
339        let msg = b"feedback-report\r\n\
340            Original-Rcpt-To: <Victim@HotMail.COM>\r\n\
341            Original-Mail-From: <Sender@Example.COM>\r\n";
342        let r = parse(msg).unwrap();
343        assert_eq!(r.original_rcpt_to.as_deref(), Some("victim@hotmail.com"));
344        assert_eq!(r.original_mail_from.as_deref(), Some("sender@example.com"));
345    }
346
347    #[test]
348    fn parse_lowercase_normalizes_reported_domain() {
349        let msg = b"feedback-report\r\nReported-Domain: Example.COM\r\n";
350        assert_eq!(
351            parse(msg).unwrap().reported_domain.as_deref(),
352            Some("example.com")
353        );
354    }
355
356    #[test]
357    fn parse_default_feedback_type_is_abuse_when_omitted() {
358        let msg = b"feedback-report\r\nOriginal-Rcpt-To: u@e.com\r\n";
359        assert_eq!(parse(msg).unwrap().feedback_type, "abuse");
360    }
361
362    #[test]
363    fn parse_first_value_wins_for_duplicate_headers() {
364        let msg = b"feedback-report\r\n\
365            Original-Rcpt-To: first@e.com\r\n\
366            Original-Rcpt-To: second@e.com\r\n";
367        assert_eq!(
368            parse(msg).unwrap().original_rcpt_to.as_deref(),
369            Some("first@e.com")
370        );
371    }
372
373    #[test]
374    fn parse_header_continuation_lines() {
375        let msg = b"feedback-report\r\n\
376            Authentication-Results: example.com;\r\n\
377            \tspf=pass smtp.mailfrom=sender@example.com;\r\n\
378            \tdkim=pass header.d=example.com\r\n";
379        let ar = parse(msg).unwrap().authentication_results.unwrap();
380        assert!(ar.contains("spf=pass"));
381        assert!(ar.contains("dkim=pass"));
382    }
383
384    #[test]
385    fn parse_complainant_prefers_rcpt_to() {
386        let msg = b"feedback-report\r\n\
387            Original-Mail-From: a@x.com\r\n\
388            Original-Rcpt-To: b@y.com\r\n";
389        assert_eq!(parse(msg).unwrap().complainant(), Some("b@y.com"));
390    }
391
392    #[test]
393    fn parse_complainant_fallback_to_mail_from() {
394        let msg = b"feedback-report\r\nOriginal-Mail-From: a@x.com\r\n";
395        assert_eq!(parse(msg).unwrap().complainant(), Some("a@x.com"));
396    }
397
398    #[test]
399    fn parse_complainant_none_when_both_missing() {
400        let msg = b"feedback-report\r\nFeedback-Type: abuse\r\n";
401        assert_eq!(parse(msg).unwrap().complainant(), None);
402    }
403
404    #[test]
405    fn parse_empty_input_returns_none() {
406        assert!(parse(b"").is_none());
407    }
408
409    #[test]
410    fn parse_short_no_match_returns_none() {
411        assert!(parse(b"Hi").is_none());
412    }
413
414    #[test]
415    fn parse_non_utf8_falls_through_to_no_headers() {
416        // Has marker but binary garbage after — non-UTF-8 path
417        // returns Some with all defaults rather than panicking.
418        let mut msg = b"feedback-report\r\n".to_vec();
419        msg.extend_from_slice(&[0xff, 0xfe, 0xfd, 0xfc]);
420        let r = parse(&msg);
421        assert!(r.is_some());
422        assert_eq!(r.unwrap().feedback_type, "abuse");
423    }
424
425    #[test]
426    fn parse_all_fields_at_once() {
427        let msg = b"feedback-report\r\n\
428            Feedback-Type: fraud\r\n\
429            User-Agent: ACME FBL/1.0\r\n\
430            Version: 1\r\n\
431            Original-Mail-From: bad@x.com\r\n\
432            Original-Rcpt-To: target@y.com\r\n\
433            Arrival-Date: now\r\n\
434            Source-IP: 10.0.0.1\r\n\
435            Reported-Domain: x.com\r\n\
436            Reported-URI: https://evil.example/landing\r\n\
437            Authentication-Results: y.com; spf=fail\r\n\
438            Incidents: 5\r\n";
439        let r = parse(msg).unwrap();
440        assert_eq!(r.feedback_type, "fraud");
441        assert_eq!(r.user_agent.as_deref(), Some("ACME FBL/1.0"));
442        assert_eq!(r.version.as_deref(), Some("1"));
443        assert_eq!(r.original_mail_from.as_deref(), Some("bad@x.com"));
444        assert_eq!(r.original_rcpt_to.as_deref(), Some("target@y.com"));
445        assert_eq!(r.arrival_date.as_deref(), Some("now"));
446        assert_eq!(r.source_ip.as_deref(), Some("10.0.0.1"));
447        assert_eq!(r.reported_domain.as_deref(), Some("x.com"));
448        assert_eq!(
449            r.reported_uri.as_deref(),
450            Some("https://evil.example/landing")
451        );
452        assert_eq!(r.authentication_results.as_deref(), Some("y.com; spf=fail"));
453        assert_eq!(r.incidents.as_deref(), Some("5"));
454    }
455}