Skip to main content

kumo_log_types/
rfc3464.rs

1//! This module parses out RFC3464 delivery status reports
2//! from an email message
3use crate::rfc5965::{
4    extract_headers, extract_single, extract_single_conv, extract_single_req, DateTimeRfc2822,
5};
6use crate::{JsonLogRecord, RecordType};
7use anyhow::{anyhow, Context};
8use bstr::{BStr, BString, ByteSlice};
9use chrono::Utc;
10use kumo_chrono_helper::DateTime;
11use mailparsing::{format_rfc2822_date, BStringUtf8, MimePart};
12use rfc5321::parser::EnvelopeAddress;
13use serde::{Deserialize, Serialize};
14use serde_with::serde_as;
15use std::collections::BTreeMap;
16use std::str::FromStr;
17
18#[derive(Debug, Serialize, Deserialize, Copy, Clone, Eq, PartialEq)]
19#[serde(rename_all = "lowercase")]
20pub enum ReportAction {
21    Failed,
22    Delayed,
23    Delivered,
24    Relayed,
25    Expanded,
26}
27
28impl std::fmt::Display for ReportAction {
29    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
30        let label = match self {
31            Self::Failed => "failed",
32            Self::Delayed => "delayed",
33            Self::Delivered => "delivered",
34            Self::Relayed => "relayed",
35            Self::Expanded => "expanded",
36        };
37        write!(fmt, "{label}")
38    }
39}
40
41impl FromStr for ReportAction {
42    type Err = anyhow::Error;
43    fn from_str(input: &str) -> anyhow::Result<Self> {
44        Ok(match input {
45            "failed" => Self::Failed,
46            "delayed" => Self::Delayed,
47            "delivered" => Self::Delivered,
48            "relayed" => Self::Relayed,
49            "expanded" => Self::Expanded,
50            _ => anyhow::bail!("invalid action type {input}"),
51        })
52    }
53}
54
55#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
56pub struct ReportStatus {
57    pub class: u8,
58    pub subject: u16,
59    pub detail: u16,
60    pub comment: Option<String>,
61}
62
63impl std::fmt::Display for ReportStatus {
64    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
65        write!(fmt, "{}.{}.{}", self.class, self.subject, self.detail)?;
66        if let Some(comment) = &self.comment {
67            write!(fmt, " {comment}")?;
68        }
69        Ok(())
70    }
71}
72
73impl From<&rfc5321::Response> for ReportStatus {
74    fn from(response: &rfc5321::Response) -> ReportStatus {
75        let (class, subject, detail) = match &response.enhanced_code {
76            Some(enh) => (enh.class, enh.subject, enh.detail),
77            None => {
78                if response.code >= 500 {
79                    (5, 0, 0)
80                } else if response.code >= 400 {
81                    (4, 0, 0)
82                } else if response.code >= 200 && response.code < 300 {
83                    (2, 0, 0)
84                } else {
85                    (4, 0, 0)
86                }
87            }
88        };
89        ReportStatus {
90            class,
91            subject,
92            detail,
93            comment: Some(response.content.clone()),
94        }
95    }
96}
97
98impl FromStr for ReportStatus {
99    type Err = anyhow::Error;
100    fn from_str(input: &str) -> anyhow::Result<Self> {
101        let mut parts: Vec<_> = input.split(' ').collect();
102
103        let mut status = parts[0].split('.');
104        let class = status
105            .next()
106            .ok_or_else(|| anyhow!("invalid Status: {input}"))?
107            .parse()
108            .context("parsing status.class")?;
109        let subject = status
110            .next()
111            .ok_or_else(|| anyhow!("invalid Status: {input}"))?
112            .parse()
113            .context("parsing status.subject")?;
114        let detail = status
115            .next()
116            .ok_or_else(|| anyhow!("invalid Status: {input}"))?
117            .parse()
118            .context("parsing status.detail")?;
119
120        parts.remove(0);
121        let comment = if parts.is_empty() {
122            None
123        } else {
124            Some(parts.join(" "))
125        };
126
127        Ok(Self {
128            class,
129            subject,
130            detail,
131            comment,
132        })
133    }
134}
135
136#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
137pub struct RemoteMta {
138    pub mta_type: String,
139    pub name: String,
140}
141
142impl std::fmt::Display for RemoteMta {
143    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
144        write!(fmt, "{}; {}", self.mta_type, self.name)
145    }
146}
147
148impl FromStr for RemoteMta {
149    type Err = anyhow::Error;
150
151    fn from_str(input: &str) -> anyhow::Result<Self> {
152        let (mta_type, name) = input
153            .split_once(";")
154            .ok_or_else(|| anyhow!("expected 'name-type; name', got {input}"))?;
155        Ok(Self {
156            mta_type: mta_type.trim().to_string(),
157            name: name.trim().to_string(),
158        })
159    }
160}
161
162/// A recipient address from an `Original-Recipient` or `Final-Recipient` DSN
163/// field. Per RFC 3464 section 2.1.2 the type is matched case-insensitively;
164/// an `rfc822` recipient is normalized to a bare SMTP envelope address, while
165/// any other type is preserved verbatim.
166#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
167pub struct Recipient {
168    pub recipient_type: String,
169    pub recipient: String,
170}
171
172impl std::fmt::Display for Recipient {
173    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
174        write!(fmt, "{};{}", self.recipient_type, self.recipient)
175    }
176}
177
178impl FromStr for Recipient {
179    type Err = anyhow::Error;
180    fn from_str(input: &str) -> anyhow::Result<Self> {
181        let (recipient_type, recipient) = input
182            .split_once(";")
183            .ok_or_else(|| anyhow!("expected 'recipient-type; recipient', got {input}"))?;
184        let recipient_type = recipient_type.trim();
185        let recipient = recipient.trim();
186
187        let (recipient_type, recipient) = if recipient_type.eq_ignore_ascii_case("rfc822") {
188            (
189                "rfc822",
190                recipient
191                    .parse::<EnvelopeAddress>()
192                    .map_err(|err| anyhow!("{err}"))?
193                    .to_string(),
194            )
195        } else {
196            (recipient_type, recipient.to_string())
197        };
198
199        Ok(Self {
200            recipient_type: recipient_type.to_string(),
201            recipient,
202        })
203    }
204}
205
206#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
207pub struct DiagnosticCode {
208    pub diagnostic_type: String,
209    pub diagnostic: String,
210}
211
212impl std::fmt::Display for DiagnosticCode {
213    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
214        write!(fmt, "{}; {}", self.diagnostic_type, self.diagnostic)
215    }
216}
217
218impl FromStr for DiagnosticCode {
219    type Err = anyhow::Error;
220    fn from_str(input: &str) -> anyhow::Result<Self> {
221        let (diagnostic_type, diagnostic) = input
222            .split_once(";")
223            .ok_or_else(|| anyhow!("expected 'diagnostic-type; diagnostic', got {input}"))?;
224        Ok(Self {
225            diagnostic_type: diagnostic_type.trim().to_string(),
226            diagnostic: diagnostic.trim().to_string(),
227        })
228    }
229}
230
231#[serde_as]
232#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
233pub struct PerRecipientReportEntry {
234    pub final_recipient: Recipient,
235    pub action: ReportAction,
236    pub status: ReportStatus,
237    pub original_recipient: Option<Recipient>,
238    pub remote_mta: Option<RemoteMta>,
239    pub diagnostic_code: Option<DiagnosticCode>,
240    pub last_attempt_date: Option<DateTime<Utc>>,
241    pub final_log_id: Option<String>,
242    pub will_retry_until: Option<DateTime<Utc>>,
243    #[serde_as(as = "BTreeMap<_, Vec<BStringUtf8>>")]
244    pub extensions: BTreeMap<String, Vec<BString>>,
245}
246
247impl std::fmt::Display for PerRecipientReportEntry {
248    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
249        if let Some(orig) = &self.original_recipient {
250            write!(fmt, "Original-Recipient: {orig}\r\n")?;
251        }
252        write!(fmt, "Final-Recipient: {}\r\n", self.final_recipient)?;
253        write!(fmt, "Action: {}\r\n", self.action)?;
254        write!(fmt, "Status: {}\r\n", self.status)?;
255        if let Some(mta) = &self.remote_mta {
256            write!(fmt, "Remote-MTA: {mta}\r\n")?;
257        }
258        if let Some(code) = &self.diagnostic_code {
259            write!(fmt, "Diagnostic-Code: {code}\r\n")?;
260        }
261        if let Some(when) = &self.last_attempt_date {
262            write!(fmt, "Last-Attempt-Date: {}\r\n", format_rfc2822_date(*when))?;
263        }
264        if let Some(id) = &self.final_log_id {
265            write!(fmt, "Final-Log-Id: {id}\r\n")?;
266        }
267        if let Some(when) = &self.will_retry_until {
268            write!(fmt, "Will-Retry-Until: {}\r\n", format_rfc2822_date(*when))?;
269        }
270        for (k, vlist) in &self.extensions {
271            for v in vlist {
272                write!(fmt, "{k}: {v}\r\n")?;
273            }
274        }
275        Ok(())
276    }
277}
278
279impl PerRecipientReportEntry {
280    fn parse(part: &str) -> anyhow::Result<Self> {
281        let mut extensions = extract_headers(part.as_bytes())?;
282
283        let original_recipient = extract_single("original-recipient", &mut extensions)?;
284        let final_recipient = extract_single_req("final-recipient", &mut extensions)?;
285        let remote_mta = extract_single("remote-mta", &mut extensions)?;
286
287        let last_attempt_date = extract_single_conv::<DateTimeRfc2822, DateTime<Utc>>(
288            "last-attempt-date",
289            &mut extensions,
290        )?;
291        let will_retry_until = extract_single_conv::<DateTimeRfc2822, DateTime<Utc>>(
292            "will-retry-until",
293            &mut extensions,
294        )?;
295        let final_log_id = extract_single("final-log-id", &mut extensions)?;
296
297        let action = extract_single_req("action", &mut extensions)?;
298        let status = extract_single_req("status", &mut extensions)?;
299        let diagnostic_code = extract_single("diagnostic-code", &mut extensions)?;
300
301        Ok(Self {
302            final_recipient,
303            action,
304            status,
305            diagnostic_code,
306            original_recipient,
307            remote_mta,
308            last_attempt_date,
309            final_log_id,
310            will_retry_until,
311            extensions,
312        })
313    }
314}
315
316#[serde_as]
317#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
318pub struct PerMessageReportEntry {
319    pub original_envelope_id: Option<String>,
320    pub reporting_mta: RemoteMta,
321    pub dsn_gateway: Option<RemoteMta>,
322    pub received_from_mta: Option<RemoteMta>,
323    pub arrival_date: Option<DateTime<Utc>>,
324    #[serde_as(as = "BTreeMap<_, Vec<BStringUtf8>>")]
325    pub extensions: BTreeMap<String, Vec<BString>>,
326}
327
328impl std::fmt::Display for PerMessageReportEntry {
329    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
330        write!(fmt, "Reporting-MTA: {}\r\n", self.reporting_mta)?;
331        if let Some(id) = &self.original_envelope_id {
332            write!(fmt, "Original-Envelope-Id: {id}\r\n")?;
333        }
334        if let Some(dsn_gateway) = &self.dsn_gateway {
335            write!(fmt, "DSN-Gateway: {dsn_gateway}\r\n")?;
336        }
337        if let Some(mta) = &self.received_from_mta {
338            write!(fmt, "Received-From-MTA: {mta}\r\n")?;
339        }
340        if let Some(when) = &self.arrival_date {
341            write!(fmt, "Arrival-Date: {}\r\n", format_rfc2822_date(*when))?;
342        }
343        for (k, vlist) in &self.extensions {
344            for v in vlist {
345                write!(fmt, "{k}: {v}\r\n")?;
346            }
347        }
348
349        Ok(())
350    }
351}
352
353impl PerMessageReportEntry {
354    fn parse(part: &str) -> anyhow::Result<Self> {
355        let mut extensions = extract_headers(part.as_bytes())?;
356
357        let reporting_mta = extract_single_req("reporting-mta", &mut extensions)?;
358        let original_envelope_id = extract_single("original-envelope-id", &mut extensions)?;
359        let dsn_gateway = extract_single("dsn-gateway", &mut extensions)?;
360        let received_from_mta = extract_single("received-from-mta", &mut extensions)?;
361
362        let arrival_date =
363            extract_single_conv::<DateTimeRfc2822, DateTime<Utc>>("arrival-date", &mut extensions)?;
364
365        Ok(Self {
366            original_envelope_id,
367            reporting_mta,
368            dsn_gateway,
369            received_from_mta,
370            arrival_date,
371            extensions,
372        })
373    }
374}
375
376#[serde_as]
377#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
378pub struct Report {
379    pub per_message: PerMessageReportEntry,
380    pub per_recipient: Vec<PerRecipientReportEntry>,
381    #[serde_as(as = "Option<BStringUtf8>")]
382    pub original_message: Option<BString>,
383}
384
385pub(crate) fn content_type(part: &MimePart) -> Option<BString> {
386    let ct = part.headers().content_type().ok()??;
387    Some(ct.value)
388}
389
390/// Extracts the returned original message from a report's returned-content
391/// part, undoing any transfer encoding that the part's content type permits.
392/// Returns None when `ct` is not a returned-content type this recognizes, or
393/// when the part cannot be decoded, because encoded bytes are not a usable
394/// original message and are better left out than presented as if decoded.
395/// Content type comparison is case insensitive, as media types require.
396pub(crate) fn decode_returned_content(part: &MimePart, ct: Option<&BStr>) -> Option<Vec<u8>> {
397    let ct = ct?;
398    if ct.eq_ignore_ascii_case(b"message/rfc822") {
399        // Its body already holds the original octets because message/rfc822
400        // must use an identity transfer encoding (7bit, 8bit, or binary) per
401        // RFC 2046.
402        Some(part.raw_body().as_bytes().to_vec())
403    } else if ct.eq_ignore_ascii_case(b"text/rfc822-headers")
404        || ct.eq_ignore_ascii_case(b"message/global")
405        || ct.eq_ignore_ascii_case(b"message/global-headers")
406    {
407        // text/rfc822-headers (RFC 6522), message/global (RFC 6532), and
408        // message/global-headers (RFC 6533) may be quoted-printable or base64
409        // encoded. Undo that without charset decoding to keep the returned
410        // octets as they were.
411        part.transfer_decoded_body().ok()
412    } else {
413        None
414    }
415}
416
417/// Builds the part of a report that echoes the failed message back to its
418/// sender. Content that cannot be represented in a conforming, 7-bit clean form
419/// is omitted instead of failing the whole report. Returns the full message
420/// when it is requested and representable; otherwise returns only the original
421/// headers.
422fn returned_content_part(
423    mode: IncludeOriginalMessage,
424    msg: &MimePart,
425) -> Option<MimePart<'static>> {
426    match mode {
427        IncludeOriginalMessage::No => None,
428        IncludeOriginalMessage::HeadersOnly => returned_headers_part(msg),
429        IncludeOriginalMessage::FullContent => {
430            let mut data = vec![];
431            match msg.write_message(&mut data) {
432                // message/rfc822 permits only an identity transfer encoding.
433                // This guard requires the written bytes to already be 7-bit
434                // clean before using that content type.
435                Ok(()) if data.is_ascii() => {
436                    MimePart::new_no_transfer_encoding("message/rfc822", &data).ok()
437                }
438                // write_message returned Err, or its output is not 7-bit
439                // clean. Discard the full message and return only the headers.
440                _ => returned_headers_part(msg),
441            }
442        }
443    }
444}
445
446/// Builds a text/rfc822-headers part holding the headers of `msg`, or None
447/// when it cannot be built. The result is always 7-bit clean, and the headers
448/// are preserved byte for byte even when they contain 8-bit octets.
449fn returned_headers_part(msg: &MimePart) -> Option<MimePart<'static>> {
450    let mut data = vec![];
451    for hdr in msg.headers().iter() {
452        hdr.write_header(&mut data).ok();
453    }
454    if data.is_ascii() {
455        MimePart::new_no_transfer_encoding("text/rfc822-headers", &data).ok()
456    } else {
457        // Unlike message/rfc822, text/rfc822-headers permits a transfer
458        // encoding. base64 preserves the 8-bit octets while keeping this part
459        // 7-bit clean.
460        MimePart::new_binary("text/rfc822-headers", &data, None).ok()
461    }
462}
463
464impl Report {
465    pub fn parse(input: &[u8]) -> anyhow::Result<Option<Self>> {
466        // The chained MimePart::parse error states the parse-failure reason.
467        // This closure runs on every failed parse, including callers that then
468        // discard the error, and the input can be a whole received message.
469        // Record its size rather than building an escaped, message-sized copy
470        // each time.
471        let mail = MimePart::parse(input)
472            .with_context(|| format!("Report::parse top; input is {} bytes", input.len()))?;
473
474        if content_type(&mail).as_ref().map(|b| b.as_bstr()) != Some(BStr::new("multipart/report"))
475        {
476            return Ok(None);
477        }
478
479        let mut original_message = None;
480
481        for part in mail.child_parts() {
482            let ct = content_type(part);
483            let ct = ct.as_ref().map(|b| b.as_bstr());
484            // Assign only on a successful decode, to avoid a later part that
485            // fails to decode erasing an earlier one that succeeded.
486            if let Some(decoded) = decode_returned_content(part, ct) {
487                original_message = Some(BString::new(decoded.replace(b"\r\n", b"\n")));
488            }
489        }
490
491        for part in mail.child_parts() {
492            let ct = content_type(part);
493            let ct = ct.as_ref().map(|b| b.as_bstr());
494            if ct == Some(BStr::new("message/delivery-status"))
495                || ct == Some(BStr::new("message/global-delivery-status"))
496            {
497                return Ok(Some(Self::parse_inner(part, original_message)?));
498            }
499        }
500
501        anyhow::bail!("delivery-status part missing");
502    }
503
504    fn parse_inner(part: &MimePart, original_message: Option<BString>) -> anyhow::Result<Self> {
505        let body = part.body()?.to_string_lossy().replace("\r\n", "\n");
506        let mut parts = body.trim().split("\n\n");
507
508        let per_message = parts
509            .next()
510            .ok_or_else(|| anyhow!("missing per-message section"))?;
511        let per_message = PerMessageReportEntry::parse(per_message)?;
512        let mut per_recipient = vec![];
513        for part in parts {
514            let part = PerRecipientReportEntry::parse(part)?;
515            per_recipient.push(part);
516        }
517
518        Ok(Self {
519            per_message,
520            per_recipient,
521            original_message,
522        })
523    }
524
525    /// msg: the message that experienced an issue
526    /// log: the corresponding log record from the issue
527    pub fn generate(
528        params: &ReportGenerationParams,
529        msg: Option<&MimePart<'_>>,
530        log: &JsonLogRecord,
531    ) -> anyhow::Result<Option<MimePart<'static>>> {
532        if log.sender.is_empty() {
533            // Cannot send a bounce back to the null sender
534            return Ok(None);
535        }
536
537        let action = match &log.kind {
538            RecordType::Bounce
539                if params.enable_bounce && log.delivery_protocol.as_deref() == Some("ESMTP") =>
540            {
541                ReportAction::Failed
542            }
543            RecordType::Expiration if params.enable_expiration => ReportAction::Failed,
544            _ => return Ok(None),
545        };
546
547        let created = format_rfc2822_date(log.created);
548
549        let arrival_date = Some(log.created);
550
551        let per_message = PerMessageReportEntry {
552            arrival_date,
553            dsn_gateway: None,
554            extensions: Default::default(),
555            original_envelope_id: None,
556            received_from_mta: None,
557            reporting_mta: params.reporting_mta.clone(),
558        };
559
560        let mut per_recipient = vec![];
561        let recip_list = log.recipient.join(", ");
562
563        for recip in &log.recipient {
564            per_recipient.push(PerRecipientReportEntry {
565                action,
566                extensions: Default::default(),
567                status: (&log.response).into(),
568                diagnostic_code: Some(DiagnosticCode {
569                    diagnostic_type: "smtp".into(),
570                    diagnostic: log.response.to_single_line(),
571                }),
572                final_log_id: None,
573                original_recipient: None,
574                final_recipient: Recipient {
575                    recipient_type: "rfc822".to_string(),
576                    recipient: recip.to_string(),
577                },
578                remote_mta: log.peer_address.as_ref().map(|addr| RemoteMta {
579                    mta_type: "dns".to_string(),
580                    name: addr.name.to_string(),
581                }),
582                last_attempt_date: Some(log.timestamp),
583                will_retry_until: None,
584            });
585        }
586
587        let mut parts = vec![];
588
589        let exposition = match &log.kind {
590            RecordType::Bounce => {
591                let mut data = format!(
592                    "The message was received at {created}\r\n\
593                    from {sender} and addressed to {recip_list}.\r\n\
594                    ",
595                    sender = log.sender,
596                );
597                if let Some(peer) = &log.peer_address {
598                    data.push_str(&format!(
599                        "While communicating with {host} ({ip}):\r\n\
600                        Response: {resp}\r\n",
601                        host = peer.name,
602                        ip = peer.addr,
603                        resp = log.response.to_single_line(),
604                    ));
605                } else {
606                    data.push_str(&format!("Status: {}\r\n", log.response.to_single_line()));
607                }
608
609                data.push_str(
610                    "\r\nThe message will be deleted from the queue.\r\n\
611                    No further attempts will be made to deliver it.\r\n",
612                );
613
614                data
615            }
616            RecordType::Expiration => {
617                format!(
618                    "The message was received at {created}\r\n\
619                    from {sender} and addressed to {recip_list}.\r\n\
620                    Status: {status}\r\n\
621                    The message will be deleted from the queue.\r\n\
622                    No further attempts will be made to deliver it.\r\n\
623                    ",
624                    sender = log.sender,
625                    status = log.response.to_single_line()
626                )
627            }
628            _ => unreachable!(),
629        };
630
631        parts.push(MimePart::new_text_plain(&*exposition).context("new_text_plain")?);
632
633        let mut status_text = format!("{per_message}\r\n");
634        for per_recip in per_recipient {
635            status_text.push_str(&format!("{per_recip}\r\n"));
636        }
637        parts.push(
638            MimePart::new_text("message/delivery-status", &*status_text).context("new_text")?,
639        );
640
641        if let Some(msg) = msg {
642            if let Some(part) = returned_content_part(params.include_original_message, msg) {
643                parts.push(part);
644            }
645        }
646
647        let mut report_msg = MimePart::new_multipart(
648            "multipart/report",
649            parts,
650            if params.stable_content {
651                Some(b"report-boundary")
652            } else {
653                None
654            },
655        )?;
656
657        let mut ct = report_msg
658            .headers()
659            .content_type()
660            .context("get content_type")?
661            .expect("assigned during construction");
662        ct.set("report-type", "delivery-status");
663        report_msg
664            .headers_mut()
665            .set_content_type(ct)
666            .context("set_content_type")?;
667        report_msg
668            .headers_mut()
669            .set_subject("Returned mail")
670            .context("set_subject")?;
671        report_msg
672            .headers_mut()
673            .set_mime_version("1.0")
674            .context("set_mime_version")?;
675
676        let message_id = if params.stable_content {
677            format!("<UUID@{}>", params.reporting_mta.name)
678        } else {
679            let id = uuid_helper::now_v1();
680            format!("<{id}@{}>", params.reporting_mta.name)
681        };
682        report_msg
683            .headers_mut()
684            .set_message_id(message_id.as_str())?;
685        report_msg
686            .headers_mut()
687            .set_to(log.sender.as_str())
688            .context("set_to")?;
689
690        let from = format!(
691            "Mail Delivery Subsystem <mailer-daemon@{}>",
692            params.reporting_mta.name
693        );
694        report_msg
695            .headers_mut()
696            .set_from(from.as_str())
697            .context("set_from")?;
698
699        Ok(Some(report_msg))
700    }
701}
702
703#[derive(Default, Debug, PartialEq, Clone, Copy, Deserialize)]
704pub enum IncludeOriginalMessage {
705    #[default]
706    No,
707    HeadersOnly,
708    FullContent,
709}
710
711#[derive(Debug, PartialEq, Clone, Deserialize)]
712#[serde(deny_unknown_fields)]
713pub struct ReportGenerationParams {
714    pub include_original_message: IncludeOriginalMessage,
715    #[serde(default)]
716    pub enable_expiration: bool,
717    #[serde(default)]
718    pub enable_bounce: bool,
719    // If we decide to allow generating for delays in the future,
720    // we'll probably add `enable_delay` here, but we'll also need
721    // to have some kind of discriminating logic to decide when
722    // to emit a DSN; probably should be a list of num_attempts
723    // on which to emit? This is too fiddly to design for right
724    // now, considering that none of our target userbase will
725    // emit DSNs for delayed mail.
726    pub reporting_mta: RemoteMta,
727
728    /// When used for testing, use a stable mime boundary
729    #[serde(default)]
730    pub stable_content: bool,
731}
732
733#[cfg(test)]
734mod test {
735    use super::*;
736    use crate::ResolvedAddress;
737    use mailparsing::MessageConformance;
738    use rfc5321::{EnhancedStatusCode, Response};
739
740    #[test]
741    fn recipient_address_type_is_case_insensitive() {
742        for input in [
743            "rfc822;User+Tag@Example.COM",
744            "RFC822 ; User+Tag@Example.COM",
745            "Rfc822; <User+Tag@Example.COM>",
746            "rfc822 ; <User+Tag@Example.COM>",
747            " RFC822 ; <User+Tag@Example.COM> ",
748            "\tRFC822\t;\t<User+Tag@Example.COM>\t",
749        ] {
750            let recipient: Recipient = input.parse().unwrap();
751            k9::snapshot!(
752                recipient,
753                r#"
754Recipient {
755    recipient_type: "rfc822",
756    recipient: "User+Tag@example.com",
757}
758"#
759            );
760        }
761    }
762
763    #[test]
764    fn parse_recipient_fields_with_uppercase_address_type() {
765        let report = PerRecipientReportEntry::parse(
766            "Original-Recipient: RFC822 ; <Original+Tag@Example.COM>\r\n\
767             Final-Recipient: Rfc822 ; <Final+Tag@Example.COM>\r\n\
768             Action: failed\r\n\
769             Status: 5.2.2\r\n",
770        )
771        .unwrap();
772        k9::snapshot!(
773            (report.original_recipient.unwrap(), report.final_recipient),
774            r#"
775(
776    Recipient {
777        recipient_type: "rfc822",
778        recipient: "Original+Tag@example.com",
779    },
780    Recipient {
781        recipient_type: "rfc822",
782        recipient: "Final+Tag@example.com",
783    },
784)
785"#
786        );
787    }
788
789    #[test]
790    fn recipient_preserves_other_address_types() {
791        let recipient: Recipient = "unknown; <User@Example.COM> ".parse().unwrap();
792        k9::snapshot!(
793            recipient,
794            r#"
795Recipient {
796    recipient_type: "unknown",
797    recipient: "<User@Example.COM>",
798}
799"#
800        );
801    }
802
803    #[test]
804    fn parse_ses_obsolete_arrival_date() {
805        // Amazon SES OOB bounces carry an Arrival-Date in an obsolete RFC 2822
806        // form ("Thu, 02 Jul 26 18:55:38 UTC"). This must not fail the report;
807        // the arrival_date below shows it is recovered rather than dropped.
808        let report = Report::parse(include_bytes!("../data/rfc3464/obsolete_arrival_date.eml"))
809            .unwrap()
810            .expect("multipart/report DSN should parse as a report");
811        k9::snapshot!(
812            &report,
813            r#"
814Report {
815    per_message: PerMessageReportEntry {
816        original_envelope_id: None,
817        reporting_mta: RemoteMta {
818            mta_type: "dns",
819            name: "mx.example.com",
820        },
821        dsn_gateway: None,
822        received_from_mta: None,
823        arrival_date: Some(
824            2026-07-02T18:55:38Z,
825        ),
826        extensions: {},
827    },
828    per_recipient: [
829        PerRecipientReportEntry {
830            final_recipient: Recipient {
831                recipient_type: "rfc822",
832                recipient: "user@example.com",
833            },
834            action: Failed,
835            status: ReportStatus {
836                class: 5,
837                subject: 1,
838                detail: 1,
839                comment: None,
840            },
841            original_recipient: Some(
842                Recipient {
843                    recipient_type: "rfc822",
844                    recipient: "user@example.com",
845                },
846            ),
847            remote_mta: None,
848            diagnostic_code: Some(
849                DiagnosticCode {
850                    diagnostic_type: "smtp",
851                    diagnostic: "550 5.1.1 Mailbox does not exist",
852                },
853            ),
854            last_attempt_date: None,
855            final_log_id: None,
856            will_retry_until: None,
857            extensions: {},
858        },
859    ],
860    original_message: None,
861}
862"#
863        );
864    }
865
866    fn make_message() -> MimePart<'static> {
867        let mut part = MimePart::new_text_plain("hello there").unwrap();
868        part.headers_mut().set_subject("Hello!").unwrap();
869
870        part
871    }
872
873    fn make_bounce() -> JsonLogRecord {
874        let nodeid = uuid_helper::now_v1();
875        let created = mailparsing::parse_rfc2822_date("Tue, 1 Jul 2003 10:52:37 +0200").unwrap();
876        let now = mailparsing::parse_rfc2822_date("Tue, 1 Jul 2003 12:52:37 +0200").unwrap();
877        JsonLogRecord {
878            kind: RecordType::Bounce,
879            id: "ID".to_string(),
880            nodeid,
881            created: created.into(),
882            bounce_classification: Default::default(),
883            delivery_protocol: Some("ESMTP".to_string()),
884            egress_pool: None,
885            egress_source: None,
886            feedback_report: None,
887            headers: Default::default(),
888            meta: Default::default(),
889            num_attempts: 1,
890            peer_address: Some(ResolvedAddress {
891                name: "target.example.com".to_string(),
892                addr: "42.42.42.42".to_string().try_into().unwrap(),
893                is_secure: false,
894            }),
895            provider_name: None,
896            queue: "target.example.com".to_string(),
897            reception_protocol: None,
898            recipient: vec!["recip@target.example.com".to_string()],
899            sender: "sender@sender.example.com".to_string(),
900            session_id: None,
901            response: Response {
902                code: 550,
903                command: None,
904                content: "no thanks".to_string(),
905                enhanced_code: Some(EnhancedStatusCode {
906                    class: 5,
907                    subject: 7,
908                    detail: 1,
909                }),
910            },
911            site: "some-site".to_string(),
912            size: 0,
913            source_address: None,
914            timestamp: now.into(),
915            tls_cipher: None,
916            tls_peer_subject_name: None,
917            tls_protocol_version: None,
918        }
919    }
920
921    fn make_expiration() -> JsonLogRecord {
922        let nodeid = uuid_helper::now_v1();
923        let created = mailparsing::parse_rfc2822_date("Tue, 1 Jul 2003 10:52:37 +0200").unwrap();
924        let now = mailparsing::parse_rfc2822_date("Tue, 1 Jul 2003 12:52:37 +0200").unwrap();
925        JsonLogRecord {
926            kind: RecordType::Expiration,
927            id: "ID".to_string(),
928            nodeid,
929            created: created.into(),
930            bounce_classification: Default::default(),
931            delivery_protocol: None,
932            egress_pool: None,
933            egress_source: None,
934            feedback_report: None,
935            headers: Default::default(),
936            meta: Default::default(),
937            num_attempts: 3,
938            peer_address: None,
939            provider_name: None,
940            queue: "target.example.com".to_string(),
941            reception_protocol: None,
942            recipient: vec!["recip@target.example.com".to_string()],
943            sender: "sender@sender.example.com".to_string(),
944            session_id: None,
945            response: Response {
946                code: 551,
947                command: None,
948                content: "Next delivery time would be at SOME TIME which exceeds the expiry time EXPIRES configured via set_scheduling".to_string(),
949                enhanced_code: Some(EnhancedStatusCode {
950                    class: 5,
951                    subject: 4,
952                    detail: 7,
953                }),
954            },
955            site: "".to_string(),
956            size: 0,
957            source_address: None,
958            timestamp: now.into(),
959            tls_cipher: None,
960            tls_peer_subject_name: None,
961            tls_protocol_version: None,
962        }
963    }
964
965    #[test]
966    fn generate_expiration_with_headers() {
967        let params = ReportGenerationParams {
968            reporting_mta: RemoteMta {
969                mta_type: "dns".to_string(),
970                name: "mta1.example.com".to_string(),
971            },
972            enable_bounce: false,
973            enable_expiration: true,
974            include_original_message: IncludeOriginalMessage::HeadersOnly,
975            stable_content: true,
976        };
977
978        let original_msg = make_message();
979
980        let log = make_expiration();
981
982        let report_msg = Report::generate(&params, Some(&original_msg), &log)
983            .unwrap()
984            .unwrap();
985        let report_eml = BString::from(report_msg.to_message_bytes().unwrap());
986        k9::snapshot!(
987            &report_eml,
988            r#"
989Content-Type: multipart/report;\r
990\tboundary="report-boundary";\r
991\treport-type="delivery-status"\r
992Subject: Returned mail\r
993MIME-Version: 1.0\r
994Message-ID: <UUID@mta1.example.com>\r
995To: sender@sender.example.com\r
996From: Mail Delivery Subsystem <mailer-daemon@mta1.example.com>\r
997\r
998--report-boundary\r
999Content-Type: text/plain;\r
1000\tcharset="us-ascii"\r
1001Content-Transfer-Encoding: quoted-printable\r
1002\r
1003The message was received at Tue, 1 Jul 2003 08:52:37 +0000\r
1004from sender@sender.example.com and addressed to recip@target.example.com.\r
1005Status: 551 5.4.7 Next delivery time would be at SOME TIME which exceeds th=\r
1006e expiry time EXPIRES configured via set_scheduling\r
1007The message will be deleted from the queue.\r
1008No further attempts will be made to deliver it.\r
1009--report-boundary\r
1010Content-Type: message/delivery-status;\r
1011\tcharset="us-ascii"\r
1012Content-Transfer-Encoding: quoted-printable\r
1013\r
1014Reporting-MTA: dns; mta1.example.com\r
1015Arrival-Date: Tue, 1 Jul 2003 08:52:37 +0000\r
1016\r
1017Final-Recipient: rfc822;recip@target.example.com\r
1018Action: failed\r
1019Status: 5.4.7 Next delivery time would be at SOME TIME which exceeds the ex=\r
1020piry time EXPIRES configured via set_scheduling\r
1021Diagnostic-Code: smtp; 551 5.4.7 Next delivery time would be at SOME TIME w=\r
1022hich exceeds the expiry time EXPIRES configured via set_scheduling\r
1023Last-Attempt-Date: Tue, 1 Jul 2003 10:52:37 +0000\r
1024\r
1025--report-boundary\r
1026Content-Type: text/rfc822-headers\r
1027\r
1028Content-Type: text/plain;\r
1029\tcharset="us-ascii"\r
1030Subject: Hello!\r
1031--report-boundary--\r
1032
1033"#
1034        );
1035
1036        let round_trip = Report::parse(report_eml.as_bytes()).unwrap().unwrap();
1037        k9::snapshot!(
1038            &round_trip,
1039            r#"
1040Report {
1041    per_message: PerMessageReportEntry {
1042        original_envelope_id: None,
1043        reporting_mta: RemoteMta {
1044            mta_type: "dns",
1045            name: "mta1.example.com",
1046        },
1047        dsn_gateway: None,
1048        received_from_mta: None,
1049        arrival_date: Some(
1050            2003-07-01T08:52:37Z,
1051        ),
1052        extensions: {},
1053    },
1054    per_recipient: [
1055        PerRecipientReportEntry {
1056            final_recipient: Recipient {
1057                recipient_type: "rfc822",
1058                recipient: "recip@target.example.com",
1059            },
1060            action: Failed,
1061            status: ReportStatus {
1062                class: 5,
1063                subject: 4,
1064                detail: 7,
1065                comment: Some(
1066                    "Next delivery time would be at SOME TIME which exceeds the expiry time EXPIRES configured via set_scheduling",
1067                ),
1068            },
1069            original_recipient: None,
1070            remote_mta: None,
1071            diagnostic_code: Some(
1072                DiagnosticCode {
1073                    diagnostic_type: "smtp",
1074                    diagnostic: "551 5.4.7 Next delivery time would be at SOME TIME which exceeds the expiry time EXPIRES configured via set_scheduling",
1075                },
1076            ),
1077            last_attempt_date: Some(
1078                2003-07-01T10:52:37Z,
1079            ),
1080            final_log_id: None,
1081            will_retry_until: None,
1082            extensions: {},
1083        },
1084    ],
1085    original_message: Some(
1086        "Content-Type: text/plain;
1087\tcharset="us-ascii"
1088Subject: Hello!
1089",
1090    ),
1091}
1092"#
1093        );
1094    }
1095
1096    #[test]
1097    fn generate_bounce_with_headers() {
1098        let params = ReportGenerationParams {
1099            reporting_mta: RemoteMta {
1100                mta_type: "dns".to_string(),
1101                name: "mta1.example.com".to_string(),
1102            },
1103            enable_bounce: true,
1104            enable_expiration: true,
1105            include_original_message: IncludeOriginalMessage::HeadersOnly,
1106            stable_content: true,
1107        };
1108
1109        let original_msg = make_message();
1110
1111        let log = make_bounce();
1112
1113        let report_msg = Report::generate(&params, Some(&original_msg), &log)
1114            .unwrap()
1115            .unwrap();
1116        let report_eml = BString::from(report_msg.to_message_bytes().unwrap());
1117        k9::snapshot!(
1118            &report_eml,
1119            r#"
1120Content-Type: multipart/report;\r
1121\tboundary="report-boundary";\r
1122\treport-type="delivery-status"\r
1123Subject: Returned mail\r
1124MIME-Version: 1.0\r
1125Message-ID: <UUID@mta1.example.com>\r
1126To: sender@sender.example.com\r
1127From: Mail Delivery Subsystem <mailer-daemon@mta1.example.com>\r
1128\r
1129--report-boundary\r
1130Content-Type: text/plain;\r
1131\tcharset="us-ascii"\r
1132\r
1133The message was received at Tue, 1 Jul 2003 08:52:37 +0000\r
1134from sender@sender.example.com and addressed to recip@target.example.com.\r
1135While communicating with target.example.com (42.42.42.42):\r
1136Response: 550 5.7.1 no thanks\r
1137\r
1138The message will be deleted from the queue.\r
1139No further attempts will be made to deliver it.\r
1140--report-boundary\r
1141Content-Type: message/delivery-status;\r
1142\tcharset="us-ascii"\r
1143\r
1144Reporting-MTA: dns; mta1.example.com\r
1145Arrival-Date: Tue, 1 Jul 2003 08:52:37 +0000\r
1146\r
1147Final-Recipient: rfc822;recip@target.example.com\r
1148Action: failed\r
1149Status: 5.7.1 no thanks\r
1150Remote-MTA: dns; target.example.com\r
1151Diagnostic-Code: smtp; 550 5.7.1 no thanks\r
1152Last-Attempt-Date: Tue, 1 Jul 2003 10:52:37 +0000\r
1153\r
1154--report-boundary\r
1155Content-Type: text/rfc822-headers\r
1156\r
1157Content-Type: text/plain;\r
1158\tcharset="us-ascii"\r
1159Subject: Hello!\r
1160--report-boundary--\r
1161
1162"#
1163        );
1164
1165        let round_trip = Report::parse(report_eml.as_bytes()).unwrap().unwrap();
1166        k9::snapshot!(
1167            &round_trip,
1168            r#"
1169Report {
1170    per_message: PerMessageReportEntry {
1171        original_envelope_id: None,
1172        reporting_mta: RemoteMta {
1173            mta_type: "dns",
1174            name: "mta1.example.com",
1175        },
1176        dsn_gateway: None,
1177        received_from_mta: None,
1178        arrival_date: Some(
1179            2003-07-01T08:52:37Z,
1180        ),
1181        extensions: {},
1182    },
1183    per_recipient: [
1184        PerRecipientReportEntry {
1185            final_recipient: Recipient {
1186                recipient_type: "rfc822",
1187                recipient: "recip@target.example.com",
1188            },
1189            action: Failed,
1190            status: ReportStatus {
1191                class: 5,
1192                subject: 7,
1193                detail: 1,
1194                comment: Some(
1195                    "no thanks",
1196                ),
1197            },
1198            original_recipient: None,
1199            remote_mta: Some(
1200                RemoteMta {
1201                    mta_type: "dns",
1202                    name: "target.example.com",
1203                },
1204            ),
1205            diagnostic_code: Some(
1206                DiagnosticCode {
1207                    diagnostic_type: "smtp",
1208                    diagnostic: "550 5.7.1 no thanks",
1209                },
1210            ),
1211            last_attempt_date: Some(
1212                2003-07-01T10:52:37Z,
1213            ),
1214            final_log_id: None,
1215            will_retry_until: None,
1216            extensions: {},
1217        },
1218    ],
1219    original_message: Some(
1220        "Content-Type: text/plain;
1221\tcharset="us-ascii"
1222Subject: Hello!
1223",
1224    ),
1225}
1226"#
1227        );
1228    }
1229    #[test]
1230    fn generate_bounce_with_message() {
1231        let params = ReportGenerationParams {
1232            reporting_mta: RemoteMta {
1233                mta_type: "dns".to_string(),
1234                name: "mta1.example.com".to_string(),
1235            },
1236            enable_bounce: true,
1237            enable_expiration: true,
1238            include_original_message: IncludeOriginalMessage::FullContent,
1239            stable_content: true,
1240        };
1241
1242        let original_msg = make_message();
1243
1244        let log = make_bounce();
1245
1246        let report_msg = Report::generate(&params, Some(&original_msg), &log)
1247            .unwrap()
1248            .unwrap();
1249        let report_eml = BString::from(report_msg.to_message_bytes().unwrap());
1250        k9::snapshot!(
1251            &report_eml,
1252            r#"
1253Content-Type: multipart/report;\r
1254\tboundary="report-boundary";\r
1255\treport-type="delivery-status"\r
1256Subject: Returned mail\r
1257MIME-Version: 1.0\r
1258Message-ID: <UUID@mta1.example.com>\r
1259To: sender@sender.example.com\r
1260From: Mail Delivery Subsystem <mailer-daemon@mta1.example.com>\r
1261\r
1262--report-boundary\r
1263Content-Type: text/plain;\r
1264\tcharset="us-ascii"\r
1265\r
1266The message was received at Tue, 1 Jul 2003 08:52:37 +0000\r
1267from sender@sender.example.com and addressed to recip@target.example.com.\r
1268While communicating with target.example.com (42.42.42.42):\r
1269Response: 550 5.7.1 no thanks\r
1270\r
1271The message will be deleted from the queue.\r
1272No further attempts will be made to deliver it.\r
1273--report-boundary\r
1274Content-Type: message/delivery-status;\r
1275\tcharset="us-ascii"\r
1276\r
1277Reporting-MTA: dns; mta1.example.com\r
1278Arrival-Date: Tue, 1 Jul 2003 08:52:37 +0000\r
1279\r
1280Final-Recipient: rfc822;recip@target.example.com\r
1281Action: failed\r
1282Status: 5.7.1 no thanks\r
1283Remote-MTA: dns; target.example.com\r
1284Diagnostic-Code: smtp; 550 5.7.1 no thanks\r
1285Last-Attempt-Date: Tue, 1 Jul 2003 10:52:37 +0000\r
1286\r
1287--report-boundary\r
1288Content-Type: message/rfc822\r
1289\r
1290Content-Type: text/plain;\r
1291\tcharset="us-ascii"\r
1292Subject: Hello!\r
1293\r
1294hello there\r
1295--report-boundary--\r
1296
1297"#
1298        );
1299
1300        let round_trip = Report::parse(report_eml.as_bytes()).unwrap().unwrap();
1301        k9::snapshot!(
1302            &round_trip,
1303            r#"
1304Report {
1305    per_message: PerMessageReportEntry {
1306        original_envelope_id: None,
1307        reporting_mta: RemoteMta {
1308            mta_type: "dns",
1309            name: "mta1.example.com",
1310        },
1311        dsn_gateway: None,
1312        received_from_mta: None,
1313        arrival_date: Some(
1314            2003-07-01T08:52:37Z,
1315        ),
1316        extensions: {},
1317    },
1318    per_recipient: [
1319        PerRecipientReportEntry {
1320            final_recipient: Recipient {
1321                recipient_type: "rfc822",
1322                recipient: "recip@target.example.com",
1323            },
1324            action: Failed,
1325            status: ReportStatus {
1326                class: 5,
1327                subject: 7,
1328                detail: 1,
1329                comment: Some(
1330                    "no thanks",
1331                ),
1332            },
1333            original_recipient: None,
1334            remote_mta: Some(
1335                RemoteMta {
1336                    mta_type: "dns",
1337                    name: "target.example.com",
1338                },
1339            ),
1340            diagnostic_code: Some(
1341                DiagnosticCode {
1342                    diagnostic_type: "smtp",
1343                    diagnostic: "550 5.7.1 no thanks",
1344                },
1345            ),
1346            last_attempt_date: Some(
1347                2003-07-01T10:52:37Z,
1348            ),
1349            final_log_id: None,
1350            will_retry_until: None,
1351            extensions: {},
1352        },
1353    ],
1354    original_message: Some(
1355        "Content-Type: text/plain;
1356\tcharset="us-ascii"
1357Subject: Hello!
1358
1359hello there
1360",
1361    ),
1362}
1363"#
1364        );
1365    }
1366
1367    // Asserts that we can successfully generate a report when the original
1368    // message has malformed and unsuable boundary lines.
1369    #[test]
1370    fn generate_bounce_with_invalid_boundary_message() {
1371        let params = ReportGenerationParams {
1372            reporting_mta: RemoteMta {
1373                mta_type: "dns".to_string(),
1374                name: "mta1.example.com".to_string(),
1375            },
1376            enable_bounce: true,
1377            enable_expiration: true,
1378            include_original_message: IncludeOriginalMessage::FullContent,
1379            stable_content: true,
1380        };
1381
1382        const ORIGINAL: &[u8] =
1383            b"Subject: Broken\r\nContent-Type: multipart/mixed; boundary=\r\n\r\n--\r\nbody\r\n";
1384        let original_msg = MimePart::parse(ORIGINAL).unwrap();
1385        assert!(original_msg
1386            .conformance()
1387            .contains(MessageConformance::MIME_INVALID_BOUNDARY));
1388
1389        let log = make_bounce();
1390
1391        let report_msg = Report::generate(&params, Some(&original_msg), &log)
1392            .unwrap()
1393            .unwrap();
1394        let report_eml = BString::from(report_msg.to_message_bytes().unwrap());
1395
1396        let embedded = format!("message/rfc822\r\n\r\n{}", BString::from(ORIGINAL.to_vec()));
1397        assert!(
1398            report_eml.contains_str(&embedded),
1399            "report should embed the original verbatim; got:\n{report_eml}"
1400        );
1401    }
1402
1403    #[test]
1404    fn generate_bounce_no_message() {
1405        let params = ReportGenerationParams {
1406            reporting_mta: RemoteMta {
1407                mta_type: "dns".to_string(),
1408                name: "mta1.example.com".to_string(),
1409            },
1410            enable_bounce: true,
1411            enable_expiration: true,
1412            include_original_message: IncludeOriginalMessage::No,
1413            stable_content: true,
1414        };
1415
1416        let original_msg = make_message();
1417
1418        let log = make_bounce();
1419
1420        let report_msg = Report::generate(&params, Some(&original_msg), &log)
1421            .unwrap()
1422            .unwrap();
1423        let report_eml = BString::from(report_msg.to_message_bytes().unwrap());
1424        k9::snapshot!(
1425            &report_eml,
1426            r#"
1427Content-Type: multipart/report;\r
1428\tboundary="report-boundary";\r
1429\treport-type="delivery-status"\r
1430Subject: Returned mail\r
1431MIME-Version: 1.0\r
1432Message-ID: <UUID@mta1.example.com>\r
1433To: sender@sender.example.com\r
1434From: Mail Delivery Subsystem <mailer-daemon@mta1.example.com>\r
1435\r
1436--report-boundary\r
1437Content-Type: text/plain;\r
1438\tcharset="us-ascii"\r
1439\r
1440The message was received at Tue, 1 Jul 2003 08:52:37 +0000\r
1441from sender@sender.example.com and addressed to recip@target.example.com.\r
1442While communicating with target.example.com (42.42.42.42):\r
1443Response: 550 5.7.1 no thanks\r
1444\r
1445The message will be deleted from the queue.\r
1446No further attempts will be made to deliver it.\r
1447--report-boundary\r
1448Content-Type: message/delivery-status;\r
1449\tcharset="us-ascii"\r
1450\r
1451Reporting-MTA: dns; mta1.example.com\r
1452Arrival-Date: Tue, 1 Jul 2003 08:52:37 +0000\r
1453\r
1454Final-Recipient: rfc822;recip@target.example.com\r
1455Action: failed\r
1456Status: 5.7.1 no thanks\r
1457Remote-MTA: dns; target.example.com\r
1458Diagnostic-Code: smtp; 550 5.7.1 no thanks\r
1459Last-Attempt-Date: Tue, 1 Jul 2003 10:52:37 +0000\r
1460\r
1461--report-boundary--\r
1462
1463"#
1464        );
1465
1466        let round_trip = Report::parse(report_eml.as_bytes()).unwrap().unwrap();
1467        k9::snapshot!(
1468            &round_trip,
1469            r#"
1470Report {
1471    per_message: PerMessageReportEntry {
1472        original_envelope_id: None,
1473        reporting_mta: RemoteMta {
1474            mta_type: "dns",
1475            name: "mta1.example.com",
1476        },
1477        dsn_gateway: None,
1478        received_from_mta: None,
1479        arrival_date: Some(
1480            2003-07-01T08:52:37Z,
1481        ),
1482        extensions: {},
1483    },
1484    per_recipient: [
1485        PerRecipientReportEntry {
1486            final_recipient: Recipient {
1487                recipient_type: "rfc822",
1488                recipient: "recip@target.example.com",
1489            },
1490            action: Failed,
1491            status: ReportStatus {
1492                class: 5,
1493                subject: 7,
1494                detail: 1,
1495                comment: Some(
1496                    "no thanks",
1497                ),
1498            },
1499            original_recipient: None,
1500            remote_mta: Some(
1501                RemoteMta {
1502                    mta_type: "dns",
1503                    name: "target.example.com",
1504                },
1505            ),
1506            diagnostic_code: Some(
1507                DiagnosticCode {
1508                    diagnostic_type: "smtp",
1509                    diagnostic: "550 5.7.1 no thanks",
1510                },
1511            ),
1512            last_attempt_date: Some(
1513                2003-07-01T10:52:37Z,
1514            ),
1515            final_log_id: None,
1516            will_retry_until: None,
1517            extensions: {},
1518        },
1519    ],
1520    original_message: None,
1521}
1522"#
1523        );
1524    }
1525
1526    #[test]
1527    fn generate_bounce_far_future_created() {
1528        use chrono::TimeZone;
1529
1530        let params = ReportGenerationParams {
1531            reporting_mta: RemoteMta {
1532                mta_type: "dns".to_string(),
1533                name: "mta1.example.com".to_string(),
1534            },
1535            enable_bounce: true,
1536            enable_expiration: true,
1537            include_original_message: IncludeOriginalMessage::No,
1538            stable_content: true,
1539        };
1540
1541        // A corrupt spool id can yield a creation time whose year is past 9999.
1542        // Generating the report must not panic. The date renders with all of
1543        // its digits in both the Arrival-Date header and the prose.
1544        let mut log = make_bounce();
1545        log.created = chrono::Utc
1546            .with_ymd_and_hms(60123, 1, 1, 0, 0, 0)
1547            .unwrap()
1548            .into();
1549
1550        let report_msg = Report::generate(&params, None, &log).unwrap().unwrap();
1551        let report_eml = BString::from(report_msg.to_message_bytes().unwrap());
1552        k9::snapshot!(
1553            &report_eml,
1554            r#"
1555Content-Type: multipart/report;\r
1556\tboundary="report-boundary";\r
1557\treport-type="delivery-status"\r
1558Subject: Returned mail\r
1559MIME-Version: 1.0\r
1560Message-ID: <UUID@mta1.example.com>\r
1561To: sender@sender.example.com\r
1562From: Mail Delivery Subsystem <mailer-daemon@mta1.example.com>\r
1563\r
1564--report-boundary\r
1565Content-Type: text/plain;\r
1566\tcharset="us-ascii"\r
1567\r
1568The message was received at Fri, 1 Jan 60123 00:00:00 +0000\r
1569from sender@sender.example.com and addressed to recip@target.example.com.\r
1570While communicating with target.example.com (42.42.42.42):\r
1571Response: 550 5.7.1 no thanks\r
1572\r
1573The message will be deleted from the queue.\r
1574No further attempts will be made to deliver it.\r
1575--report-boundary\r
1576Content-Type: message/delivery-status;\r
1577\tcharset="us-ascii"\r
1578\r
1579Reporting-MTA: dns; mta1.example.com\r
1580Arrival-Date: Fri, 1 Jan 60123 00:00:00 +0000\r
1581\r
1582Final-Recipient: rfc822;recip@target.example.com\r
1583Action: failed\r
1584Status: 5.7.1 no thanks\r
1585Remote-MTA: dns; target.example.com\r
1586Diagnostic-Code: smtp; 550 5.7.1 no thanks\r
1587Last-Attempt-Date: Tue, 1 Jul 2003 10:52:37 +0000\r
1588\r
1589--report-boundary--\r
1590
1591"#
1592        );
1593    }
1594
1595    #[test]
1596    fn rfc3464_1() {
1597        let result = Report::parse(include_bytes!("../data/rfc3464/1.eml")).unwrap();
1598        k9::snapshot!(
1599            &result,
1600            r#"
1601Some(
1602    Report {
1603        per_message: PerMessageReportEntry {
1604            original_envelope_id: None,
1605            reporting_mta: RemoteMta {
1606                mta_type: "dns",
1607                name: "cs.utk.edu",
1608            },
1609            dsn_gateway: None,
1610            received_from_mta: None,
1611            arrival_date: None,
1612            extensions: {},
1613        },
1614        per_recipient: [
1615            PerRecipientReportEntry {
1616                final_recipient: Recipient {
1617                    recipient_type: "rfc822",
1618                    recipient: "louisl@larry.slip.umd.edu",
1619                },
1620                action: Failed,
1621                status: ReportStatus {
1622                    class: 4,
1623                    subject: 0,
1624                    detail: 0,
1625                    comment: None,
1626                },
1627                original_recipient: Some(
1628                    Recipient {
1629                        recipient_type: "rfc822",
1630                        recipient: "louisl@larry.slip.umd.edu",
1631                    },
1632                ),
1633                remote_mta: None,
1634                diagnostic_code: Some(
1635                    DiagnosticCode {
1636                        diagnostic_type: "smtp",
1637                        diagnostic: "426 connection timed out",
1638                    },
1639                ),
1640                last_attempt_date: Some(
1641                    1994-07-07T21:15:49Z,
1642                ),
1643                final_log_id: None,
1644                will_retry_until: None,
1645                extensions: {},
1646            },
1647        ],
1648        original_message: Some(
1649            "[original message goes here]
1650
1651",
1652        ),
1653    },
1654)
1655"#
1656        );
1657
1658        let report = result.unwrap();
1659
1660        assert_eq!(
1661            report.per_message.to_string(),
1662            "Reporting-MTA: dns; cs.utk.edu\r\n"
1663        );
1664        assert_eq!(
1665            report.per_recipient[0].to_string(),
1666            "Original-Recipient: rfc822;louisl@larry.slip.umd.edu\r\n\
1667            Final-Recipient: rfc822;louisl@larry.slip.umd.edu\r\n\
1668            Action: failed\r\n\
1669            Status: 4.0.0\r\n\
1670            Diagnostic-Code: smtp; 426 connection timed out\r\n\
1671            Last-Attempt-Date: Thu, 7 Jul 1994 21:15:49 +0000\r\n"
1672        );
1673    }
1674
1675    #[test]
1676    fn quoted_printable_rfc822_headers_are_decoded() {
1677        // A sender may return the original headers in a quoted-printable
1678        // text/rfc822-headers part, which is permitted for text types. The
1679        // parser must undo the transfer encoding while preserving the raw
1680        // header octets, here a Subject holding shift_jis bytes.
1681        let eml = concat!(
1682            "Content-Type: multipart/report; report-type=\"delivery-status\";\r\n",
1683            "\tboundary=\"b\"\r\n",
1684            "\r\n",
1685            "--b\r\n",
1686            "Content-Type: message/delivery-status\r\n",
1687            "\r\n",
1688            "Reporting-MTA: dns; mta.example.com\r\n",
1689            "\r\n",
1690            "Final-Recipient: rfc822;recip@example.com\r\n",
1691            "Action: failed\r\n",
1692            "Status: 5.0.0\r\n",
1693            "\r\n",
1694            "--b\r\n",
1695            "Content-Type: text/rfc822-headers; charset=\"shift_jis\"\r\n",
1696            "Content-Transfer-Encoding: quoted-printable\r\n",
1697            "\r\n",
1698            "Subject: =93=FA=96=7B=8C=EA\r\n",
1699            "--b--\r\n",
1700        );
1701
1702        let report = Report::parse(eml.as_bytes()).unwrap().unwrap();
1703        k9::assert_equal!(
1704            report.original_message.unwrap(),
1705            BString::from(b"Subject: \x93\xFA\x96\x7B\x8C\xEA\n")
1706        );
1707    }
1708
1709    #[test]
1710    fn returned_content_type_is_case_insensitive() {
1711        // Media types are case insensitive. A returned-content part whose
1712        // content type is not in canonical lower case is still recognized.
1713        let eml = concat!(
1714            "Content-Type: multipart/report; report-type=\"delivery-status\";\r\n",
1715            "\tboundary=\"b\"\r\n",
1716            "\r\n",
1717            "--b\r\n",
1718            "Content-Type: message/delivery-status\r\n",
1719            "\r\n",
1720            "Reporting-MTA: dns; mta.example.com\r\n",
1721            "\r\n",
1722            "Final-Recipient: rfc822;recip@example.com\r\n",
1723            "Action: failed\r\n",
1724            "Status: 5.0.0\r\n",
1725            "\r\n",
1726            "--b\r\n",
1727            "Content-Type: Message/RFC822\r\n",
1728            "\r\n",
1729            "Subject: Hello!\r\n",
1730            "--b--\r\n",
1731        );
1732
1733        let report = Report::parse(eml.as_bytes()).unwrap().unwrap();
1734        k9::assert_equal!(
1735            report.original_message.unwrap(),
1736            BString::from(b"Subject: Hello!\n")
1737        );
1738    }
1739
1740    #[test]
1741    fn generate_bounce_with_8bit_headers() {
1742        let params = ReportGenerationParams {
1743            reporting_mta: RemoteMta {
1744                mta_type: "dns".to_string(),
1745                name: "mta1.example.com".to_string(),
1746            },
1747            enable_bounce: true,
1748            enable_expiration: false,
1749            include_original_message: IncludeOriginalMessage::HeadersOnly,
1750            stable_content: true,
1751        };
1752
1753        // A Subject holding raw shift_jis octets that cannot be represented in
1754        // a 7-bit clean text/rfc822-headers part without a transfer encoding.
1755        let original_msg =
1756            MimePart::parse(&b"Subject: \x93\xFA\x96\x7B\x8C\xEA\r\n\r\nbody\r\n"[..]).unwrap();
1757        let log = make_bounce();
1758
1759        let report_eml = Report::generate(&params, Some(&original_msg), &log)
1760            .unwrap()
1761            .unwrap()
1762            .to_message_bytes()
1763            .unwrap();
1764
1765        // The report must be 7-bit clean because SMTPUTF8/8BITMIME cannot be
1766        // relied upon downstream.
1767        assert!(
1768            report_eml.is_ascii(),
1769            "generated report must be 7-bit clean"
1770        );
1771
1772        // It round-trips, recovering the raw 8-bit Subject octets.
1773        let round_trip = Report::parse(&report_eml).unwrap().unwrap();
1774        k9::assert_equal!(
1775            round_trip.original_message.unwrap(),
1776            BString::from(b"Subject: \x93\xFA\x96\x7B\x8C\xEA\n")
1777        );
1778    }
1779
1780    #[test]
1781    fn generate_bounce_with_8bit_full_content_degrades_to_headers() {
1782        let params = ReportGenerationParams {
1783            reporting_mta: RemoteMta {
1784                mta_type: "dns".to_string(),
1785                name: "mta1.example.com".to_string(),
1786            },
1787            enable_bounce: true,
1788            enable_expiration: false,
1789            include_original_message: IncludeOriginalMessage::FullContent,
1790            stable_content: true,
1791        };
1792
1793        // Only the body is 8-bit. The headers are ASCII. This isolates the body
1794        // as the trigger for the FullContent degrade under test.
1795        let original_msg = MimePart::parse(
1796            &b"Subject: hi\r\nContent-Type: text/plain\r\n\r\n\x93\xFA body\r\n"[..],
1797        )
1798        .unwrap();
1799        let log = make_bounce();
1800
1801        let report_eml = Report::generate(&params, Some(&original_msg), &log)
1802            .unwrap()
1803            .unwrap()
1804            .to_message_bytes()
1805            .unwrap();
1806
1807        assert!(
1808            report_eml.is_ascii(),
1809            "generated report must be 7-bit clean"
1810        );
1811
1812        let round_trip = Report::parse(&report_eml).unwrap().unwrap();
1813        k9::assert_equal!(
1814            round_trip.original_message.unwrap(),
1815            BString::from(b"Subject: hi\nContent-Type: text/plain\n")
1816        );
1817    }
1818
1819    #[test]
1820    fn rfc3464_2() {
1821        let result = Report::parse(include_bytes!("../data/rfc3464/2.eml")).unwrap();
1822        k9::snapshot!(
1823            result,
1824            r#"
1825Some(
1826    Report {
1827        per_message: PerMessageReportEntry {
1828            original_envelope_id: None,
1829            reporting_mta: RemoteMta {
1830                mta_type: "dns",
1831                name: "cs.utk.edu",
1832            },
1833            dsn_gateway: None,
1834            received_from_mta: None,
1835            arrival_date: None,
1836            extensions: {},
1837        },
1838        per_recipient: [
1839            PerRecipientReportEntry {
1840                final_recipient: Recipient {
1841                    recipient_type: "rfc822",
1842                    recipient: "arathib@vnet.ibm.com",
1843                },
1844                action: Failed,
1845                status: ReportStatus {
1846                    class: 5,
1847                    subject: 0,
1848                    detail: 0,
1849                    comment: Some(
1850                        "(permanent failure)",
1851                    ),
1852                },
1853                original_recipient: Some(
1854                    Recipient {
1855                        recipient_type: "rfc822",
1856                        recipient: "arathib@vnet.ibm.com",
1857                    },
1858                ),
1859                remote_mta: Some(
1860                    RemoteMta {
1861                        mta_type: "dns",
1862                        name: "vnet.ibm.com",
1863                    },
1864                ),
1865                diagnostic_code: Some(
1866                    DiagnosticCode {
1867                        diagnostic_type: "smtp",
1868                        diagnostic: "550 'arathib@vnet.IBM.COM' is not a registered gateway user",
1869                    },
1870                ),
1871                last_attempt_date: None,
1872                final_log_id: None,
1873                will_retry_until: None,
1874                extensions: {},
1875            },
1876            PerRecipientReportEntry {
1877                final_recipient: Recipient {
1878                    recipient_type: "rfc822",
1879                    recipient: "johnh@hpnjld.njd.hp.com",
1880                },
1881                action: Delayed,
1882                status: ReportStatus {
1883                    class: 4,
1884                    subject: 0,
1885                    detail: 0,
1886                    comment: Some(
1887                        "(hpnjld.njd.jp.com: host name lookup failure)",
1888                    ),
1889                },
1890                original_recipient: Some(
1891                    Recipient {
1892                        recipient_type: "rfc822",
1893                        recipient: "johnh@hpnjld.njd.hp.com",
1894                    },
1895                ),
1896                remote_mta: None,
1897                diagnostic_code: None,
1898                last_attempt_date: None,
1899                final_log_id: None,
1900                will_retry_until: None,
1901                extensions: {},
1902            },
1903            PerRecipientReportEntry {
1904                final_recipient: Recipient {
1905                    recipient_type: "rfc822",
1906                    recipient: "wsnell@sdcc13.ucsd.edu",
1907                },
1908                action: Failed,
1909                status: ReportStatus {
1910                    class: 5,
1911                    subject: 0,
1912                    detail: 0,
1913                    comment: None,
1914                },
1915                original_recipient: Some(
1916                    Recipient {
1917                        recipient_type: "rfc822",
1918                        recipient: "wsnell@sdcc13.ucsd.edu",
1919                    },
1920                ),
1921                remote_mta: Some(
1922                    RemoteMta {
1923                        mta_type: "dns",
1924                        name: "sdcc13.ucsd.edu",
1925                    },
1926                ),
1927                diagnostic_code: Some(
1928                    DiagnosticCode {
1929                        diagnostic_type: "smtp",
1930                        diagnostic: "550 user unknown",
1931                    },
1932                ),
1933                last_attempt_date: None,
1934                final_log_id: None,
1935                will_retry_until: None,
1936                extensions: {},
1937            },
1938        ],
1939        original_message: Some(
1940            "[original message goes here]
1941
1942",
1943        ),
1944    },
1945)
1946"#
1947        );
1948    }
1949
1950    #[test]
1951    fn rfc3464_3() {
1952        let result = Report::parse(include_bytes!("../data/rfc3464/3.eml")).unwrap();
1953        k9::snapshot!(
1954            result,
1955            r#"
1956Some(
1957    Report {
1958        per_message: PerMessageReportEntry {
1959            original_envelope_id: None,
1960            reporting_mta: RemoteMta {
1961                mta_type: "mailbus",
1962                name: "SYS30",
1963            },
1964            dsn_gateway: None,
1965            received_from_mta: None,
1966            arrival_date: None,
1967            extensions: {},
1968        },
1969        per_recipient: [
1970            PerRecipientReportEntry {
1971                final_recipient: Recipient {
1972                    recipient_type: "unknown",
1973                    recipient: "nair_s",
1974                },
1975                action: Failed,
1976                status: ReportStatus {
1977                    class: 5,
1978                    subject: 0,
1979                    detail: 0,
1980                    comment: Some(
1981                        "(unknown permanent failure)",
1982                    ),
1983                },
1984                original_recipient: None,
1985                remote_mta: None,
1986                diagnostic_code: None,
1987                last_attempt_date: None,
1988                final_log_id: None,
1989                will_retry_until: None,
1990                extensions: {},
1991            },
1992        ],
1993        original_message: None,
1994    },
1995)
1996"#
1997        );
1998    }
1999
2000    #[test]
2001    fn rfc3464_4() {
2002        let result = Report::parse(include_bytes!("../data/rfc3464/4.eml")).unwrap();
2003        k9::snapshot!(
2004            result,
2005            r#"
2006Some(
2007    Report {
2008        per_message: PerMessageReportEntry {
2009            original_envelope_id: None,
2010            reporting_mta: RemoteMta {
2011                mta_type: "dns",
2012                name: "sun2.nsfnet-relay.ac.uk",
2013            },
2014            dsn_gateway: None,
2015            received_from_mta: None,
2016            arrival_date: None,
2017            extensions: {},
2018        },
2019        per_recipient: [
2020            PerRecipientReportEntry {
2021                final_recipient: Recipient {
2022                    recipient_type: "rfc822",
2023                    recipient: "thomas@de-montfort.ac.uk",
2024                },
2025                action: Delayed,
2026                status: ReportStatus {
2027                    class: 4,
2028                    subject: 0,
2029                    detail: 0,
2030                    comment: Some(
2031                        "(unknown temporary failure)",
2032                    ),
2033                },
2034                original_recipient: None,
2035                remote_mta: None,
2036                diagnostic_code: None,
2037                last_attempt_date: None,
2038                final_log_id: None,
2039                will_retry_until: None,
2040                extensions: {},
2041            },
2042        ],
2043        original_message: None,
2044    },
2045)
2046"#
2047        );
2048    }
2049
2050    #[test]
2051    fn rfc3464_5() {
2052        let result = Report::parse(include_bytes!("../data/rfc3464/5.eml")).unwrap();
2053        k9::snapshot!(
2054            result,
2055            r#"
2056Some(
2057    Report {
2058        per_message: PerMessageReportEntry {
2059            original_envelope_id: None,
2060            reporting_mta: RemoteMta {
2061                mta_type: "dns",
2062                name: "mx-by.bbox.fr",
2063            },
2064            dsn_gateway: None,
2065            received_from_mta: None,
2066            arrival_date: Some(
2067                2025-01-29T16:36:51Z,
2068            ),
2069            extensions: {
2070                "x-postfix-queue-id": [
2071                    "897DAC0",
2072                ],
2073                "x-postfix-sender": [
2074                    "rfc822; user@example.com",
2075                ],
2076            },
2077        },
2078        per_recipient: [
2079            PerRecipientReportEntry {
2080                final_recipient: Recipient {
2081                    recipient_type: "rfc822",
2082                    recipient: "recipient@domain.com",
2083                },
2084                action: Failed,
2085                status: ReportStatus {
2086                    class: 5,
2087                    subject: 0,
2088                    detail: 0,
2089                    comment: None,
2090                },
2091                original_recipient: Some(
2092                    Recipient {
2093                        recipient_type: "rfc822",
2094                        recipient: "recipient@domain.com",
2095                    },
2096                ),
2097                remote_mta: Some(
2098                    RemoteMta {
2099                        mta_type: "dns",
2100                        name: "lmtp.cs.dolmen.bouyguestelecom.fr",
2101                    },
2102                ),
2103                diagnostic_code: Some(
2104                    DiagnosticCode {
2105                        diagnostic_type: "smtp",
2106                        diagnostic: "552 <recipient@domain.com> rejected: over quota",
2107                    },
2108                ),
2109                last_attempt_date: None,
2110                final_log_id: None,
2111                will_retry_until: None,
2112                extensions: {},
2113            },
2114        ],
2115        original_message: Some(
2116            "[original message goes here]
2117
2118",
2119        ),
2120    },
2121)
2122"#
2123        );
2124    }
2125
2126    #[test]
2127    fn rfc3464_6() {
2128        let result = Report::parse(include_bytes!("../data/rfc3464/6.eml")).unwrap();
2129        k9::snapshot!(
2130            result,
2131            r#"
2132Some(
2133    Report {
2134        per_message: PerMessageReportEntry {
2135            original_envelope_id: None,
2136            reporting_mta: RemoteMta {
2137                mta_type: "dns",
2138                name: "tls02.example.com",
2139            },
2140            dsn_gateway: None,
2141            received_from_mta: None,
2142            arrival_date: None,
2143            extensions: {},
2144        },
2145        per_recipient: [
2146            PerRecipientReportEntry {
2147                final_recipient: Recipient {
2148                    recipient_type: "rfc822",
2149                    recipient: "redacted@example.com",
2150                },
2151                action: Failed,
2152                status: ReportStatus {
2153                    class: 5,
2154                    subject: 0,
2155                    detail: 0,
2156                    comment: None,
2157                },
2158                original_recipient: Some(
2159                    Recipient {
2160                        recipient_type: "rfc822",
2161                        recipient: "redacted@example.com",
2162                    },
2163                ),
2164                remote_mta: Some(
2165                    RemoteMta {
2166                        mta_type: "dns",
2167                        name: "example-com.mail.eo.outlook.com:25",
2168                    },
2169                ),
2170                diagnostic_code: Some(
2171                    DiagnosticCode {
2172                        diagnostic_type: "smtp",
2173                        diagnostic: "host example-com.mail.eo.outlook.com:25 says: 550 5.4.1 Recipient address rejected: Access denied. For more information see https://aka.ms/EXOSmtpErrors [XXX.namprd05.prod.outlook.com 2026-03-13T18:10:42.797Z XXX]",
2174                    },
2175                ),
2176                last_attempt_date: None,
2177                final_log_id: None,
2178                will_retry_until: None,
2179                extensions: {},
2180            },
2181        ],
2182        original_message: Some(
2183            "Subject: [Bulk Mail] the subject
2184From: INFO <info@email.example.com>
2185To: redacted@example.com
2186
2187",
2188        ),
2189    },
2190)
2191"#
2192        );
2193    }
2194
2195    #[test]
2196    fn original_message_serializes_as_json_string() {
2197        let report = Report {
2198            per_message: PerMessageReportEntry {
2199                original_envelope_id: None,
2200                reporting_mta: RemoteMta {
2201                    mta_type: "dns".to_string(),
2202                    name: "mta.example.com".to_string(),
2203                },
2204                dsn_gateway: None,
2205                received_from_mta: None,
2206                arrival_date: None,
2207                extensions: BTreeMap::new(),
2208            },
2209            per_recipient: vec![],
2210            original_message: Some(BString::from("Subject: hi\n\nhello")),
2211        };
2212        let json = serde_json::to_value(&report).unwrap();
2213        k9::assert_equal!(
2214            json["original_message"],
2215            serde_json::Value::String("Subject: hi\n\nhello".to_string())
2216        );
2217    }
2218
2219    #[test]
2220    fn original_message_non_utf8_falls_back_to_bytes() {
2221        let report = Report {
2222            per_message: PerMessageReportEntry {
2223                original_envelope_id: None,
2224                reporting_mta: RemoteMta {
2225                    mta_type: "dns".to_string(),
2226                    name: "mta.example.com".to_string(),
2227                },
2228                dsn_gateway: None,
2229                received_from_mta: None,
2230                arrival_date: None,
2231                extensions: BTreeMap::new(),
2232            },
2233            per_recipient: vec![],
2234            original_message: Some(BString::from(b"abc\x80\xffxyz")),
2235        };
2236        let json = serde_json::to_value(&report).unwrap();
2237        assert!(json["original_message"].is_array());
2238    }
2239}