Skip to main content

camel_processor/
mime_splitter.rs

1use bytes::Bytes;
2use camel_api::fragment_exchange;
3use camel_api::{Body, CamelError, Exchange, Value};
4use futures::Stream;
5use mail_parser::{MessageParser, MessagePart, MimeHeaders, PartType};
6use std::pin::Pin;
7
8/// Zero-based index of the emitted fragment.
9pub const CAMEL_MIME_PART_INDEX: &str = "CamelMimePartIndex";
10/// Decoded attachment filename.
11pub const CAMEL_MIME_PART_NAME: &str = "CamelMimePartName";
12/// Declared Content-Type of the part, untrusted.
13pub const CAMEL_MIME_PART_CONTENT_TYPE: &str = "CamelMimePartContentType";
14/// Decoded byte length of the fragment body.
15pub const CAMEL_MIME_PART_SIZE: &str = "CamelMimePartSize";
16/// `attachment` or `inline`, from Content-Disposition.
17pub const CAMEL_MIME_PART_DISPOSITION: &str = "CamelMimePartDisposition";
18/// Content-ID of the part, when declared.
19pub const CAMEL_MIME_PART_CONTENT_ID: &str = "CamelMimePartContentId";
20
21/// Default maximum number of fragments emitted by [`MimeSplitConfig`].
22pub const DEFAULT_MAX_PARTS: usize = 100;
23
24/// Maximum byte length of sender-supplied header values.
25const MAX_PART_VALUE_BYTES: usize = 255;
26
27/// Configuration for the MIME splitter.
28#[derive(Debug, Clone)]
29pub struct MimeSplitConfig {
30    /// Maximum number of fragments to emit.
31    pub max_parts: usize,
32    /// Maximum decoded size per part; defaults to the input length.
33    pub max_part_size: Option<usize>,
34    /// Optional allowlist of declared `type/subtype` values.
35    pub content_types: Option<Vec<String>>,
36}
37
38impl Default for MimeSplitConfig {
39    fn default() -> Self {
40        Self {
41            max_parts: DEFAULT_MAX_PARTS,
42            max_part_size: None,
43            content_types: None,
44        }
45    }
46}
47
48/// Effective per-part size limit: an explicit limit or the input length.
49fn effective_part_limit(input_len: usize, max_part_size: Option<usize>) -> usize {
50    max_part_size.unwrap_or(input_len)
51}
52
53/// Declared `type/subtype` of a part, ignoring parameters.
54fn declared_content_type(part: &MessagePart<'_>) -> Option<String> {
55    let content_type = part.content_type()?;
56    match content_type.subtype() {
57        Some(subtype) => Some(format!("{}/{}", content_type.ctype(), subtype)),
58        None => Some(content_type.ctype().to_string()),
59    }
60}
61
62/// Disposition from Content-Disposition; absent means `attachment`.
63fn part_disposition(part: &MessagePart<'_>) -> &'static str {
64    match part.content_disposition() {
65        Some(disposition) if disposition.is_inline() => "inline",
66        _ => "attachment",
67    }
68}
69
70/// Remove Unicode control characters (NUL, C0, DEL, C1).
71fn strip_controls(raw: &str) -> String {
72    raw.chars()
73        .filter(|character| !character.is_control())
74        .collect()
75}
76
77/// Cap a string at `max_bytes` without splitting a UTF-8 sequence.
78fn cap_utf8_bytes(mut value: String, max_bytes: usize) -> String {
79    if value.len() <= max_bytes {
80        return value;
81    }
82    let mut boundary = max_bytes;
83    while !value.is_char_boundary(boundary) {
84        boundary -= 1;
85    }
86    value.truncate(boundary);
87    value
88}
89
90/// Sanitize a sender-supplied header value: strip controls and cap it.
91fn clean_part_value(raw: &str) -> String {
92    cap_utf8_bytes(strip_controls(raw), MAX_PART_VALUE_BYTES)
93}
94
95/// Sanitize a sender-supplied attachment name for use as a fragment header.
96fn sanitize_part_name(raw: Option<&str>, index: usize) -> String {
97    let Some(raw) = raw else {
98        return format!("part-{index}");
99    };
100    let basename = match raw.rfind(['/', '\\']) {
101        Some(position) => &raw[position + 1..],
102        None => raw,
103    };
104    let stripped = strip_controls(basename);
105    let trimmed = stripped.trim_matches([' ', '.']);
106    if trimmed.is_empty() {
107        return format!("part-{index}");
108    }
109    cap_utf8_bytes(trimmed.to_string(), MAX_PART_VALUE_BYTES)
110}
111
112/// Whether a declared content type matches the allowlist.
113fn allowlist_matches(allowlist: Option<&[String]>, declared: Option<&str>) -> bool {
114    let Some(allowlist) = allowlist.filter(|list| !list.is_empty()) else {
115        return true;
116    };
117    let Some(declared) = declared else {
118        return false;
119    };
120    allowlist
121        .iter()
122        .any(|allowed| allowed.trim().eq_ignore_ascii_case(declared))
123}
124
125/// Split a MIME message's attachment parts into a stream of Exchanges.
126///
127/// Emits one fragment per attachment reported by `mail-parser`, in document
128/// order. Text and HTML body parts, multipart containers, and nested
129/// `message/rfc822` descendants are not emitted.
130pub fn split_mime_bytes(
131    parent: Exchange,
132    bytes: Bytes,
133    config: MimeSplitConfig,
134) -> Pin<Box<dyn Stream<Item = Result<Exchange, CamelError>> + Send>> {
135    Box::pin(async_stream::stream! {
136        let part_limit = effective_part_limit(bytes.len(), config.max_part_size);
137        let allowlist = config.content_types.as_deref();
138        let Some(message) = MessageParser::default().parse(bytes.as_ref()) else {
139            yield Err(CamelError::TypeConversionFailed(
140                "MIME message could not be parsed".into(),
141            ));
142            return;
143        };
144
145        let mut index = 0usize;
146        for (current_part, part) in message.attachments().enumerate() {
147            let declared = declared_content_type(part);
148            if !allowlist_matches(allowlist, declared.as_deref()) {
149                continue;
150            }
151            if part.is_encoding_problem {
152                yield Err(CamelError::TypeConversionFailed(format!(
153                    "MIME part {current_part} has a malformed transfer encoding"
154                )));
155                return;
156            }
157            if index >= config.max_parts {
158                yield Err(CamelError::TypeConversionFailed(format!(
159                    "MIME message exceeds max_parts ({})",
160                    config.max_parts
161                )));
162                return;
163            }
164            let decoded = match &part.body {
165                PartType::Text(text) | PartType::Html(text) => Some(text.as_bytes().to_vec()),
166                PartType::Binary(binary) | PartType::InlineBinary(binary) => Some(binary.to_vec()),
167                // `mail-parser` 0.11.9 stores the outer raw message in the
168                // nested message's `raw_message` field, so slice the part
169                // offsets to preserve the exact embedded RFC 822 bytes. Fall
170                // back to nothing rather than emitting the outer message.
171                PartType::Message(_) => bytes
172                    .get(part.raw_body_offset() as usize..part.raw_end_offset() as usize)
173                    .map(<[u8]>::to_vec),
174                PartType::Multipart(_) => continue,
175            };
176            let Some(decoded) = decoded else {
177                yield Err(CamelError::TypeConversionFailed(
178                    "message/rfc822 part offsets unavailable".into(),
179                ));
180                return;
181            };
182            let size = decoded.len();
183            if size > part_limit {
184                yield Err(CamelError::TypeConversionFailed(format!(
185                    "MIME part {current_part} exceeds max_part_size ({size} > {part_limit})"
186                )));
187                return;
188            }
189
190            let mut exchange = fragment_exchange(&parent, Body::Bytes(Bytes::from(decoded)));
191            for inherited in [
192                CAMEL_MIME_PART_INDEX,
193                CAMEL_MIME_PART_NAME,
194                CAMEL_MIME_PART_CONTENT_TYPE,
195                CAMEL_MIME_PART_SIZE,
196                CAMEL_MIME_PART_DISPOSITION,
197                CAMEL_MIME_PART_CONTENT_ID,
198            ] {
199                exchange.input.headers.remove(inherited);
200            }
201
202            exchange.input.headers.insert(
203                CAMEL_MIME_PART_INDEX.to_string(),
204                Value::from(index as u64),
205            );
206            exchange.input.headers.insert(
207                CAMEL_MIME_PART_NAME.to_string(),
208                Value::String(sanitize_part_name(part.attachment_name(), index)),
209            );
210            if let Some(content_type) = declared {
211                exchange.input.headers.insert(
212                    CAMEL_MIME_PART_CONTENT_TYPE.to_string(),
213                    Value::String(clean_part_value(&content_type)),
214                );
215            }
216            exchange.input.headers.insert(
217                CAMEL_MIME_PART_SIZE.to_string(),
218                Value::from(size as u64),
219            );
220            exchange.input.headers.insert(
221                CAMEL_MIME_PART_DISPOSITION.to_string(),
222                Value::String(part_disposition(part).to_string()),
223            );
224            if let Some(content_id) = part.content_id() {
225                exchange.input.headers.insert(
226                    CAMEL_MIME_PART_CONTENT_ID.to_string(),
227                    Value::String(clean_part_value(content_id)),
228                );
229            }
230
231            index += 1;
232            yield Ok(exchange);
233        }
234    })
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240    use camel_api::{Message, Value};
241    use flate2::Compression;
242    use flate2::write::GzEncoder;
243    use futures::StreamExt;
244    use std::io::Write;
245
246    fn make_parent(headers: &[(&str, &str)]) -> Exchange {
247        let mut msg = Message::new(Body::Empty);
248        for (name, value) in headers {
249            msg.headers
250                .insert((*name).to_string(), Value::String((*value).to_string()));
251        }
252        Exchange::new(msg)
253    }
254
255    async fn collect(
256        parent: Exchange,
257        raw: Vec<u8>,
258        config: MimeSplitConfig,
259    ) -> Vec<Result<Exchange, CamelError>> {
260        split_mime_bytes(parent, Bytes::from(raw), config)
261            .collect()
262            .await
263    }
264
265    async fn collect_default(raw: Vec<u8>) -> Vec<Result<Exchange, CamelError>> {
266        collect(make_parent(&[]), raw, MimeSplitConfig::default()).await
267    }
268
269    fn body_bytes(exchange: &Exchange) -> &[u8] {
270        match &exchange.input.body {
271            Body::Bytes(bytes) => bytes.as_ref(),
272            other => panic!("expected Body::Bytes, got {other:?}"),
273        }
274    }
275
276    fn header_str<'a>(exchange: &'a Exchange, name: &str) -> Option<&'a str> {
277        match exchange.input.headers.get(name) {
278            Some(Value::String(value)) => Some(value.as_str()),
279            _ => None,
280        }
281    }
282
283    fn header_u64(exchange: &Exchange, name: &str) -> Option<u64> {
284        match exchange.input.headers.get(name) {
285            Some(Value::Number(value)) => value.as_u64(),
286            _ => None,
287        }
288    }
289
290    fn multipart_mixed(parts: &[String]) -> Vec<u8> {
291        multipart("mixed", "test-boundary", parts)
292    }
293
294    fn multipart(kind: &str, boundary: &str, parts: &[String]) -> Vec<u8> {
295        let mut raw = format!(
296            "MIME-Version: 1.0\r\nContent-Type: multipart/{kind}; boundary=\"{boundary}\"\r\n\r\n"
297        );
298        for part in parts {
299            raw.push_str(&format!("--{boundary}\r\n{part}\r\n"));
300        }
301        raw.push_str(&format!("--{boundary}--\r\n"));
302        raw.into_bytes()
303    }
304
305    fn text_attachment(filename: &str, body: &str) -> String {
306        format!(
307            "Content-Type: text/plain; name=\"{filename}\"\r\n\
308             Content-Disposition: attachment; filename=\"{filename}\"\r\n\r\n{body}"
309        )
310    }
311
312    fn typed_attachment(content_type: &str, filename: &str, body: &str) -> String {
313        format!(
314            "Content-Type: {content_type}; name=\"{filename}\"\r\n\
315             Content-Disposition: attachment; filename=\"{filename}\"\r\n\r\n{body}"
316        )
317    }
318
319    fn error_message(results: &[Result<Exchange, CamelError>]) -> String {
320        match results.last() {
321            Some(Err(error)) => error.to_string(),
322            other => panic!("expected a trailing error, got {other:?}"),
323        }
324    }
325
326    #[tokio::test]
327    async fn emits_zero_fragments_for_plain_text() {
328        let raw =
329            b"MIME-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nhello world\r\n"
330                .to_vec();
331        let results = collect_default(raw).await;
332        assert_eq!(results.len(), 0, "{results:?}");
333    }
334
335    #[tokio::test]
336    async fn emits_one_and_three_in_document_order() {
337        let one = multipart_mixed(&[text_attachment("only.txt", "one")]);
338        let results = collect_default(one).await;
339        assert_eq!(results.len(), 1, "{results:?}");
340        let first = results[0].as_ref().expect("one fragment");
341        assert_eq!(header_str(first, CAMEL_MIME_PART_NAME), Some("only.txt"));
342
343        let three = multipart_mixed(&[
344            text_attachment("a.txt", "alpha"),
345            text_attachment("b.txt", "beta"),
346            text_attachment("c.txt", "gamma"),
347        ]);
348        let results = collect_default(three).await;
349        assert_eq!(results.len(), 3, "{results:?}");
350        let names: Vec<_> = results
351            .iter()
352            .map(|r| header_str(r.as_ref().expect("fragment"), CAMEL_MIME_PART_NAME).unwrap())
353            .collect();
354        assert_eq!(names, ["a.txt", "b.txt", "c.txt"]);
355        let indexes: Vec<_> = results
356            .iter()
357            .map(|r| header_u64(r.as_ref().expect("fragment"), CAMEL_MIME_PART_INDEX).unwrap())
358            .collect();
359        assert_eq!(indexes, [0, 1, 2]);
360    }
361
362    #[tokio::test]
363    async fn alternative_bodies_not_emitted() {
364        let parts = vec![
365            "Content-Type: text/plain\r\n\r\nplain body".to_string(),
366            "Content-Type: text/html\r\n\r\n<p>html body</p>".to_string(),
367        ];
368        let raw = multipart("alternative", "alt-boundary", &parts);
369        let results = collect_default(raw).await;
370        assert_eq!(results.len(), 0, "{results:?}");
371    }
372
373    #[tokio::test]
374    async fn text_csv_attachment_emitted() {
375        let mut raw = b"MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"b\"\r\n\r\n--b\r\nContent-Type: text/csv; charset=iso-8859-1; name=\"data.csv\"\r\nContent-Disposition: attachment; filename=\"data.csv\"\r\n\r\na,".to_vec();
376        raw.extend_from_slice(&[0xE9]);
377        raw.extend_from_slice(b"\r\n--b--\r\n");
378
379        let results = collect_default(raw).await;
380        assert_eq!(results.len(), 1, "{results:?}");
381        let fragment = results[0].as_ref().expect("csv fragment");
382        assert_eq!(body_bytes(fragment), b"a,\xC3\xA9");
383        assert_eq!(
384            header_str(fragment, CAMEL_MIME_PART_CONTENT_TYPE),
385            Some("text/csv")
386        );
387        assert_eq!(
388            header_str(fragment, CAMEL_MIME_PART_DISPOSITION),
389            Some("attachment")
390        );
391    }
392
393    #[tokio::test]
394    async fn inline_image_emitted_with_content_id() {
395        let parts = vec![
396            "Content-Type: text/html\r\n\r\n<img src=\"cid:img1\">".to_string(),
397            "Content-Type: image/png; name=\"pic.png\"\r\n\
398             Content-Disposition: inline; filename=\"pic.png\"\r\n\
399             Content-ID: <img1>\r\n\
400             Content-Transfer-Encoding: base64\r\n\r\niVBORw0KGgo="
401                .to_string(),
402        ];
403        let raw = multipart("related", "rel-boundary", &parts);
404        let results = collect_default(raw).await;
405        assert_eq!(results.len(), 1, "{results:?}");
406        let fragment = results[0].as_ref().expect("inline image");
407        assert_eq!(
408            header_str(fragment, CAMEL_MIME_PART_DISPOSITION),
409            Some("inline")
410        );
411        let content_id = header_str(fragment, CAMEL_MIME_PART_CONTENT_ID).unwrap_or_default();
412        assert!(content_id.contains("img1"), "content id was {content_id:?}");
413    }
414
415    #[tokio::test]
416    async fn message_rfc822_one_raw_fragment_no_descendants() {
417        let inner = "From: inner@example.com\r\nSubject: Inner\r\nContent-Type: multipart/mixed; boundary=\"inner\"\r\n\r\n--inner\r\nContent-Type: text/plain\r\nContent-Disposition: attachment; filename=\"hidden.txt\"\r\n\r\npayload\r\n--inner--";
418        let part = format!(
419            "Content-Type: message/rfc822\r\n\
420             Content-Disposition: attachment; filename=\"inner.eml\"\r\n\r\n{inner}"
421        );
422        let outer = multipart_mixed(&[part]);
423
424        let results = collect_default(outer).await;
425        assert_eq!(results.len(), 1, "{results:?}");
426        let fragment = results[0].as_ref().expect("raw message fragment");
427        assert_eq!(body_bytes(fragment), inner.as_bytes());
428        assert_eq!(
429            header_str(fragment, CAMEL_MIME_PART_NAME),
430            Some("inner.eml")
431        );
432    }
433
434    #[tokio::test]
435    async fn base64_aaec_decodes_to_0_1_2() {
436        let part = "Content-Type: application/octet-stream; name=\"blob.bin\"\r\n\
437                    Content-Disposition: attachment; filename=\"blob.bin\"\r\n\
438                    Content-Transfer-Encoding: base64\r\n\r\nAAEC"
439            .to_string();
440        let raw = multipart_mixed(&[part]);
441        let results = collect_default(raw).await;
442        assert_eq!(results.len(), 1, "{results:?}");
443        let fragment = results[0].as_ref().expect("base64 fragment");
444        assert_eq!(body_bytes(fragment), [0, 1, 2]);
445        assert_eq!(header_u64(fragment, CAMEL_MIME_PART_SIZE), Some(3));
446        assert_eq!(
447            header_str(fragment, CAMEL_MIME_PART_DISPOSITION),
448            Some("attachment")
449        );
450    }
451
452    #[tokio::test]
453    async fn quoted_printable_decoded() {
454        let part = "Content-Type: application/octet-stream; name=\"qp.bin\"\r\n\
455                    Content-Disposition: attachment; filename=\"qp.bin\"\r\n\
456                    Content-Transfer-Encoding: quoted-printable\r\n\r\n=00=01=02"
457            .to_string();
458        let raw = multipart_mixed(&[part]);
459        let results = collect_default(raw).await;
460        assert_eq!(results.len(), 1, "{results:?}");
461        let fragment = results[0].as_ref().expect("quoted-printable fragment");
462        assert_eq!(body_bytes(fragment), [0, 1, 2]);
463    }
464
465    #[tokio::test]
466    async fn parent_headers_copied() {
467        let raw = multipart_mixed(&[
468            text_attachment("first.txt", "first"),
469            text_attachment("second.txt", "second"),
470        ]);
471        let parent = make_parent(&[("X-Parent", "kept")]);
472        let results = collect(parent, raw, MimeSplitConfig::default()).await;
473        assert_eq!(results.len(), 2, "{results:?}");
474        for (expected_index, result) in results.iter().enumerate() {
475            let fragment = result.as_ref().expect("fragment");
476            assert_eq!(header_str(fragment, "X-Parent"), Some("kept"));
477            assert_eq!(
478                header_u64(fragment, CAMEL_MIME_PART_INDEX),
479                Some(expected_index as u64)
480            );
481            assert!(header_str(fragment, CAMEL_MIME_PART_CONTENT_TYPE).is_some());
482            assert!(header_u64(fragment, CAMEL_MIME_PART_SIZE).is_some());
483            assert!(header_str(fragment, CAMEL_MIME_PART_DISPOSITION).is_some());
484        }
485    }
486
487    #[tokio::test]
488    async fn default_max_part_size_is_input_length() {
489        let mut raw = b"MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"b\"\r\n\r\n--b\r\nContent-Type: text/csv; charset=iso-8859-1; name=\"latin.csv\"\r\nContent-Disposition: attachment; filename=\"latin.csv\"\r\n\r\n".to_vec();
490        raw.extend(std::iter::repeat_n(0xE9u8, 500));
491        raw.extend_from_slice(b"\r\n--b--\r\n");
492
493        let config = MimeSplitConfig::default();
494        let limit = effective_part_limit(raw.len(), config.max_part_size);
495        assert_eq!(
496            limit,
497            raw.len(),
498            "default per-part limit must be the input length"
499        );
500
501        let message = MessageParser::default()
502            .parse(raw.as_slice())
503            .expect("parse");
504        let part = message.attachments().next().expect("latin-1 attachment");
505        let converted_len = match &part.body {
506            PartType::Text(text) | PartType::Html(text) => text.len(),
507            other => panic!("expected text part, got {other:?}"),
508        };
509        assert!(
510            converted_len > limit,
511            "UTF-8 conversion ({converted_len}) must exceed the input length ({limit})"
512        );
513
514        let results = collect_default(raw).await;
515        assert_eq!(results.len(), 1, "{results:?}");
516        assert!(
517            error_message(&results).contains("max_part_size"),
518            "error must name the default limit: {results:?}"
519        );
520    }
521
522    #[tokio::test]
523    async fn gzip_attachment_not_decompressed() {
524        let payload = b"the quick brown fox jumps over the lazy dog";
525        let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
526        encoder.write_all(payload).expect("gzip encode");
527        let compressed = encoder.finish().expect("finish gzip");
528        assert_eq!(&compressed[..2], b"\x1f\x8b");
529
530        let mut raw = b"MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"b\"\r\n\r\n--b\r\nContent-Type: application/gzip; name=\"data.gz\"\r\nContent-Disposition: attachment; filename=\"data.gz\"\r\n\r\n".to_vec();
531        raw.extend_from_slice(&compressed);
532        raw.extend_from_slice(b"\r\n--b--\r\n");
533
534        let results = collect_default(raw).await;
535        assert_eq!(results.len(), 1, "{results:?}");
536        let fragment = results[0].as_ref().expect("gzip fragment");
537        let body = body_bytes(fragment);
538        assert_eq!(&body[..2], b"\x1f\x8b");
539        assert_eq!(body, compressed.as_slice());
540    }
541
542    #[tokio::test]
543    async fn max_parts_excess_fails() {
544        let raw = multipart_mixed(&[
545            text_attachment("a.txt", "alpha"),
546            text_attachment("b.txt", "beta"),
547            text_attachment("c.txt", "gamma"),
548        ]);
549        let config = MimeSplitConfig {
550            max_parts: 2,
551            ..MimeSplitConfig::default()
552        };
553        let results = collect(make_parent(&[]), raw, config).await;
554
555        assert_eq!(results.len(), 3, "{results:?}");
556        assert_eq!(
557            results[..2]
558                .iter()
559                .map(|r| header_u64(r.as_ref().expect("fragment"), CAMEL_MIME_PART_INDEX).unwrap())
560                .collect::<Vec<_>>(),
561            [0, 1]
562        );
563        let message = error_message(&results);
564        assert!(message.contains("max_parts"), "error was {message:?}");
565    }
566
567    #[tokio::test]
568    async fn filtered_parts_do_not_consume_limit() {
569        let raw = multipart_mixed(&[
570            typed_attachment("application/zip", "a.zip", "a"),
571            typed_attachment("application/zip", "b.zip", "b"),
572            typed_attachment("application/zip", "c.zip", "c"),
573            typed_attachment("application/pdf", "d.pdf", "%PDF-1.7"),
574        ]);
575        let config = MimeSplitConfig {
576            max_parts: 2,
577            content_types: Some(vec!["application/pdf".to_string()]),
578            ..MimeSplitConfig::default()
579        };
580        let results = collect(make_parent(&[]), raw, config).await;
581
582        assert_eq!(results.len(), 1, "{results:?}");
583        let fragment = results[0].as_ref().expect("pdf fragment");
584        assert_eq!(header_u64(fragment, CAMEL_MIME_PART_INDEX), Some(0));
585        assert_eq!(
586            header_str(fragment, CAMEL_MIME_PART_CONTENT_TYPE),
587            Some("application/pdf")
588        );
589    }
590
591    #[tokio::test]
592    async fn max_part_size_excess_fails() {
593        let raw = multipart_mixed(&[typed_attachment(
594            "application/octet-stream",
595            "blob.bin",
596            "0123456789a",
597        )]);
598        let config = MimeSplitConfig {
599            max_part_size: Some(10),
600            ..MimeSplitConfig::default()
601        };
602        let results = collect(make_parent(&[]), raw, config).await;
603
604        assert_eq!(results.len(), 1, "{results:?}");
605        let message = error_message(&results);
606        assert!(message.contains("max_part_size"), "error was {message:?}");
607    }
608
609    #[tokio::test]
610    async fn allowlist_drops_non_matching() {
611        let raw = multipart_mixed(&[
612            typed_attachment("application/zip", "a.zip", "zip"),
613            typed_attachment("application/pdf", "b.pdf", "%PDF-1.7"),
614        ]);
615        let config = MimeSplitConfig {
616            content_types: Some(vec!["application/zip".to_string()]),
617            ..MimeSplitConfig::default()
618        };
619        let results = collect(make_parent(&[]), raw, config).await;
620
621        assert_eq!(results.len(), 1, "{results:?}");
622        assert_eq!(
623            header_str(
624                results[0].as_ref().expect("zip fragment"),
625                CAMEL_MIME_PART_CONTENT_TYPE
626            ),
627            Some("application/zip")
628        );
629    }
630
631    #[tokio::test]
632    async fn all_parts_filtered_succeeds_empty() {
633        let raw = multipart_mixed(&[typed_attachment("application/pdf", "b.pdf", "%PDF-1.7")]);
634        let config = MimeSplitConfig {
635            content_types: Some(vec!["application/zip".to_string()]),
636            ..MimeSplitConfig::default()
637        };
638        let results = collect(make_parent(&[]), raw, config).await;
639
640        assert_eq!(results.len(), 0, "{results:?}");
641    }
642
643    #[tokio::test]
644    async fn allowlist_case_insensitive_parameter_blind() {
645        let raw = multipart_mixed(&[typed_attachment("Application/ZIP", "a.zip", "zip")]);
646        let config = MimeSplitConfig {
647            content_types: Some(vec!["application/zip".to_string()]),
648            ..MimeSplitConfig::default()
649        };
650        let results = collect(make_parent(&[]), raw, config).await;
651
652        assert_eq!(results.len(), 1, "{results:?}");
653        assert_eq!(
654            header_str(
655                results[0].as_ref().expect("zip fragment"),
656                CAMEL_MIME_PART_NAME
657            ),
658            Some("a.zip")
659        );
660    }
661
662    #[test]
663    fn sanitization_table() {
664        for (raw, expected) in [
665            ("../../etc/passwd", "passwd"),
666            ("a\0b.txt", "ab.txt"),
667            ("  .hidden.  ", "hidden"),
668            ("..", "part-0"),
669            (" report .zip ", "report .zip"),
670        ] {
671            assert_eq!(
672                sanitize_part_name(Some(raw), 0),
673                expected,
674                "sanitizing {raw:?}"
675            );
676        }
677    }
678
679    #[test]
680    fn multibyte_name_capped_at_utf8_boundary() {
681        let raw = "é".repeat(300);
682        let sanitized = sanitize_part_name(Some(&raw), 0);
683        assert!(
684            sanitized.len() <= 255,
685            "capped name has {} bytes",
686            sanitized.len()
687        );
688        assert_eq!(sanitized.chars().count(), 127);
689    }
690
691    #[tokio::test]
692    async fn unparseable_message_fails() {
693        let results = collect_default(Vec::new()).await;
694
695        assert_eq!(results.len(), 1, "{results:?}");
696        let message = error_message(&results);
697        assert!(
698            message.contains("could not be parsed"),
699            "error was {message:?}"
700        );
701    }
702
703    #[tokio::test]
704    async fn malformed_transfer_encoding_fails() {
705        let part = "Content-Type: application/octet-stream; name=\"bad.bin\"\r\n\
706                    Content-Disposition: attachment; filename=\"bad.bin\"\r\n\
707                    Content-Transfer-Encoding: base64\r\n\r\n*AAA"
708            .to_string();
709        let raw = multipart_mixed(&[part]);
710        let results = collect_default(raw).await;
711
712        assert_eq!(results.len(), 1, "{results:?}");
713        let message = error_message(&results);
714        assert!(
715            message.contains("malformed transfer encoding"),
716            "error was {message:?}"
717        );
718        assert!(message.contains('0'), "error names the part: {message:?}");
719    }
720
721    #[tokio::test]
722    async fn inherited_content_id_not_leaked() {
723        let raw = multipart_mixed(&[text_attachment("plain.txt", "body")]);
724        let parent = make_parent(&[(CAMEL_MIME_PART_CONTENT_ID, "inherited-id")]);
725        let results = collect(parent, raw, MimeSplitConfig::default()).await;
726
727        assert_eq!(results.len(), 1, "{results:?}");
728        let fragment = results[0].as_ref().expect("fragment");
729        assert_eq!(header_str(fragment, CAMEL_MIME_PART_CONTENT_ID), None);
730    }
731
732    #[tokio::test]
733    async fn content_type_and_id_control_stripped_and_capped() {
734        let long_subtype = format!("{}{}", "a".repeat(320), '\u{1}');
735        let long_id = format!("<{}{}{}>", "a".repeat(200), '\u{7f}', "b".repeat(200));
736        let part = format!(
737            "Content-Type: text/{long_subtype}; name=\"long.txt\"\r\n\
738             Content-Disposition: attachment; filename=\"long.txt\"\r\n\
739             Content-ID: {long_id}\r\n\r\npayload"
740        );
741        let raw = multipart_mixed(&[part]);
742        let results = collect_default(raw).await;
743
744        assert_eq!(results.len(), 1, "{results:?}");
745        let fragment = results[0].as_ref().expect("fragment");
746        let content_type =
747            header_str(fragment, CAMEL_MIME_PART_CONTENT_TYPE).expect("content type");
748        let content_id = header_str(fragment, CAMEL_MIME_PART_CONTENT_ID).expect("content id");
749        for value in [content_type, content_id] {
750            assert!(
751                !value.chars().any(char::is_control),
752                "value carries a control character: {value:?}"
753            );
754            assert!(value.len() <= 255, "value is {} bytes", value.len());
755        }
756    }
757
758    #[tokio::test]
759    async fn name_falls_back_to_content_type_name() {
760        let raw = multipart_mixed(&[
761            "Content-Type: text/plain\r\n\r\nbody".to_string(),
762            "Content-Type: text/plain; name=\"x.pdf\"\r\n\r\npayload".to_string(),
763        ]);
764        let results = collect_default(raw).await;
765
766        assert_eq!(results.len(), 1, "{results:?}");
767        assert_eq!(
768            header_str(results[0].as_ref().expect("fragment"), CAMEL_MIME_PART_NAME),
769            Some("x.pdf")
770        );
771    }
772
773    #[tokio::test]
774    async fn rfc2231_filename_decoded() {
775        let part = "Content-Type: application/zip\r\n\
776                    Content-Disposition: attachment; filename*=UTF-8''caf%C3%A9.zip\r\n\r\nzip"
777            .to_string();
778        let raw = multipart_mixed(&[part]);
779        let results = collect_default(raw).await;
780
781        assert_eq!(results.len(), 1, "{results:?}");
782        assert_eq!(
783            header_str(results[0].as_ref().expect("fragment"), CAMEL_MIME_PART_NAME),
784            Some("café.zip")
785        );
786    }
787}