1use std::collections::{HashMap, HashSet};
13use std::io::Read;
14use std::path::Path;
15use std::pin::Pin;
16use std::sync::Arc;
17
18use bytes::Bytes;
19use futures::Stream;
20use serde::Deserialize;
21use tokio::sync::mpsc;
22
23use camel_api::{
24 Body, CamelError, Exchange, Message, PROPERTY_HTTP_CONTENT_TYPE_INHERITED,
25 StreamingSplitExpression, Value,
26};
27
28use crate::archive_splitter::{
29 DEFAULT_MAX_PATH_LENGTH, DuplicatePolicy, next_free_indexed_name, validate_entry_path,
30};
31use crate::data_format::gzip::decode_first_member;
32
33pub const CAMEL_TAR_ENTRY_NAME: &str = "CamelTarEntryName";
34pub const CAMEL_TAR_ENTRY_PATH: &str = "CamelTarEntryPath";
35pub const CAMEL_TAR_ENTRY_INDEX: &str = "CamelTarEntryIndex";
36pub const CAMEL_TAR_ENTRY_SIZE: &str = "CamelTarEntrySize";
37pub const CAMEL_TAR_ENTRY_IS_DIRECTORY: &str = "CamelTarEntryIsDirectory";
38
39const DEFAULT_MAX_ENTRIES: usize = 10_000;
40const DEFAULT_MAX_TOTAL_DECODED_SIZE: u64 = 1_073_741_824;
41const DEFAULT_MAX_PER_ENTRY_SIZE: u64 = 512 * 1024 * 1024;
42const DEFAULT_MAX_COMPRESSED_SIZE: u64 = 1_073_741_824;
43const DEFAULT_CHANNEL_CAPACITY: usize = 2;
44
45#[derive(Clone, Debug, Deserialize)]
51#[serde(deny_unknown_fields, default)]
52pub struct TarSplitConfig {
53 pub max_entries: usize,
55 pub max_total_decoded_size: u64,
60 pub max_per_entry_size: u64,
62 pub max_compressed_size: u64,
64 pub max_path_length: usize,
66 pub duplicate_names_policy: DuplicatePolicy,
72 pub allow_empty_archive: bool,
74}
75
76impl Default for TarSplitConfig {
77 fn default() -> Self {
78 Self {
79 max_entries: DEFAULT_MAX_ENTRIES,
80 max_total_decoded_size: DEFAULT_MAX_TOTAL_DECODED_SIZE,
81 max_per_entry_size: DEFAULT_MAX_PER_ENTRY_SIZE,
82 max_compressed_size: DEFAULT_MAX_COMPRESSED_SIZE,
83 max_path_length: DEFAULT_MAX_PATH_LENGTH,
84 duplicate_names_policy: DuplicatePolicy::default(),
85 allow_empty_archive: false,
86 }
87 }
88}
89
90fn validate_tar_entry_path(name: &str, max_length: usize) -> Result<String, CamelError> {
94 validate_entry_path(name, max_length, "TAR")
95}
96
97fn err_malformed_archive(detail: &str) -> CamelError {
99 CamelError::TypeConversionFailed(format!("Invalid TAR archive: {detail}"))
100}
101
102fn err_duplicate_entry_name(name: &str) -> CamelError {
104 CamelError::TypeConversionFailed(format!("Duplicate TAR entry name: {name}"))
105}
106
107fn err_max_entries(limit: usize) -> CamelError {
109 CamelError::TypeConversionFailed(format!("TAR exceeds max entries: {limit}"))
110}
111
112fn err_entry_too_large(name: &str, size: u64, limit: u64) -> CamelError {
114 CamelError::TypeConversionFailed(format!(
115 "TAR entry '{name}' size {size} exceeds max {limit}"
116 ))
117}
118
119fn err_total_decoded_exceeded(limit: u64) -> CamelError {
121 CamelError::TypeConversionFailed(format!("TAR total decoded size exceeds max {limit}"))
122}
123
124fn err_decoded_archive_budget(limit: u64) -> CamelError {
128 CamelError::TypeConversionFailed(format!(
129 "TAR.GZ decoded archive stream exceeds bounded decode budget {limit}"
130 ))
131}
132
133const MAX_TAR_FRAMING_ALLOWANCE: u64 = 64 * 1024 * 1024;
141
142const BASE_TAR_FRAMING_ALLOWANCE: u64 = 64 * 1024;
146
147const TAR_BLOCK_SIZE: u64 = 512;
149
150fn tar_per_entry_framing(path_cap: usize) -> u64 {
164 let extension_data = (path_cap as u64 + 32).div_ceil(TAR_BLOCK_SIZE) * TAR_BLOCK_SIZE;
165 TAR_BLOCK_SIZE + TAR_BLOCK_SIZE + extension_data + (TAR_BLOCK_SIZE - 1)
166}
167
168fn tar_gz_decode_budget(config: &TarSplitConfig) -> u64 {
186 let per_entry =
187 (config.max_entries as u64).saturating_mul(tar_per_entry_framing(config.max_path_length));
188 let framing = per_entry.min(MAX_TAR_FRAMING_ALLOWANCE) + BASE_TAR_FRAMING_ALLOWANCE;
189 config.max_total_decoded_size.saturating_add(framing)
190}
191
192fn err_compressed_input_exceeded(size: u64, limit: u64) -> CamelError {
194 CamelError::TypeConversionFailed(format!("TAR compressed size {size} exceeds max {limit}"))
195}
196
197fn err_multi_member_gzip() -> CamelError {
200 CamelError::TypeConversionFailed(
201 "TAR.GZ input contains multiple GZIP members; only a single-member \
202 GZIP stream is supported"
203 .to_string(),
204 )
205}
206
207fn err_empty_archive() -> CamelError {
209 CamelError::TypeConversionFailed(
210 "TAR archive contains no regular entries; enable allow_empty_archive \
211 to accept it"
212 .to_string(),
213 )
214}
215
216struct TarEntryData {
219 index: usize,
220 path: String,
221 size: u64,
222 data: Vec<u8>,
223}
224
225pub fn split_tar_bytes(
237 parent: Exchange,
238 bytes: Bytes,
239 config: TarSplitConfig,
240) -> Pin<Box<dyn Stream<Item = Result<Exchange, CamelError>> + Send>> {
241 Box::pin(async_stream::stream! {
242 if bytes.len() as u64 > config.max_compressed_size {
245 yield Err(err_compressed_input_exceeded(
246 bytes.len() as u64,
247 config.max_compressed_size,
248 ));
249 return;
250 }
251
252 let entries = tar_entry_stream(parent, bytes, config);
253 for await result in entries {
254 yield result;
255 }
256 })
257}
258
259pub fn split_tar_gz_bytes(
272 parent: Exchange,
273 bytes: Bytes,
274 config: TarSplitConfig,
275) -> Pin<Box<dyn Stream<Item = Result<Exchange, CamelError>> + Send>> {
276 Box::pin(async_stream::stream! {
277 if bytes.len() as u64 > config.max_compressed_size {
280 yield Err(err_compressed_input_exceeded(
281 bytes.len() as u64,
282 config.max_compressed_size,
283 ));
284 return;
285 }
286
287 let decode_budget = tar_gz_decode_budget(&config);
296 let take_limit = decode_budget.saturating_add(1);
297 let decode_input = bytes.clone();
298 let first = match tokio::task::spawn_blocking(move || {
299 decode_first_member(&decode_input, take_limit)
300 })
301 .await
302 {
303 Ok(Ok(first)) => first,
304 Ok(Err(e)) => {
305 yield Err(err_malformed_archive(&format!(
306 "failed to decode GZIP stream: {e}"
307 )));
308 return;
309 }
310 Err(e) => {
311 yield Err(err_malformed_archive(&format!(
312 "GZIP decode task failed: {e}"
313 )));
314 return;
315 }
316 };
317
318 if first.data.len() as u64 >= take_limit {
322 yield Err(err_decoded_archive_budget(decode_budget));
323 return;
324 }
325
326 if first.has_trailing_input {
329 yield Err(err_multi_member_gzip());
330 return;
331 }
332
333 let entries = tar_entry_stream(parent, Bytes::from(first.data), config);
334 for await result in entries {
335 yield result;
336 }
337 })
338}
339
340fn tar_entry_stream(
344 parent: Exchange,
345 bytes: Bytes,
346 config: TarSplitConfig,
347) -> Pin<Box<dyn Stream<Item = Result<Exchange, CamelError>> + Send>> {
348 Box::pin(async_stream::stream! {
349 let (tx, mut rx) = mpsc::channel::<Result<TarEntryData, CamelError>>(
350 DEFAULT_CHANNEL_CAPACITY,
351 );
352
353 let max_entries = config.max_entries;
354 let max_per_entry = config.max_per_entry_size;
355 let max_total = config.max_total_decoded_size;
356 let max_path_len = config.max_path_length;
357 let allow_empty = config.allow_empty_archive;
358 let dup_policy = config.duplicate_names_policy;
359
360 tokio::task::spawn_blocking(move || {
365 let mut archive = tar::Archive::new(std::io::Cursor::new(bytes));
366 let entries = match archive.entries() {
367 Ok(entries) => entries,
368 Err(e) => {
369 let _ = tx.blocking_send(Err(err_malformed_archive(&e.to_string())));
370 return;
371 }
372 };
373
374 let mut total_decoded: u64 = 0;
375 let mut emitted: usize = 0;
376 let mut emitted_names: HashSet<String> = HashSet::new();
377 let mut name_occurrences: HashMap<String, usize> = HashMap::new();
378
379 for entry in entries {
380 let mut entry = match entry {
381 Ok(e) => e,
382 Err(e) => {
383 let _ = tx.blocking_send(Err(err_malformed_archive(&e.to_string())));
384 return;
385 }
386 };
387
388 let raw_name = match entry.path() {
391 Ok(p) => match p.to_str() {
392 Some(name) => name.to_string(),
393 None => {
394 let _ = tx.blocking_send(Err(err_malformed_archive(
395 "entry name is not valid UTF-8",
396 )));
397 return;
398 }
399 },
400 Err(e) => {
401 let _ = tx.blocking_send(Err(err_malformed_archive(&e.to_string())));
402 return;
403 }
404 };
405 let mut validated = match validate_tar_entry_path(&raw_name, max_path_len) {
406 Ok(path) => path,
407 Err(e) => {
408 let _ = tx.blocking_send(Err(e));
409 return;
410 }
411 };
412
413 if !matches!(entry.header().entry_type(), tar::EntryType::Regular) {
417 continue;
418 }
419
420 let mut data = Vec::new();
423 let mut limited = Read::take(&mut entry, max_per_entry.saturating_add(1));
424 if let Err(e) = limited.read_to_end(&mut data) {
425 let _ = tx.blocking_send(Err(err_malformed_archive(&format!(
426 "failed to read TAR entry '{raw_name}': {e}"
427 ))));
428 return;
429 }
430
431 if data.len() as u64 > max_per_entry {
432 let declared = entry.header().size().unwrap_or(data.len() as u64);
435 let _ = tx.blocking_send(Err(err_entry_too_large(
436 &raw_name,
437 declared,
438 max_per_entry,
439 )));
440 return;
441 }
442
443 let new_total = total_decoded.saturating_add(data.len() as u64);
444 if new_total > max_total {
445 let _ = tx.blocking_send(Err(err_total_decoded_exceeded(max_total)));
446 return;
447 }
448 total_decoded = new_total;
449
450 let index = emitted;
451 if index >= max_entries {
452 let _ = tx.blocking_send(Err(err_max_entries(max_entries)));
453 return;
454 }
455 emitted += 1;
456
457 match dup_policy {
458 DuplicatePolicy::Reject => {
459 if !emitted_names.insert(validated.clone()) {
460 let _ = tx.blocking_send(Err(err_duplicate_entry_name(&validated)));
461 return;
462 }
463 }
464 DuplicatePolicy::AllowWithIndex => {
465 let occurrences =
472 name_occurrences.entry(validated.clone()).or_insert(0);
473 let start = if *occurrences > 0 {
474 *occurrences
475 } else if emitted_names.contains(&validated) {
476 1
477 } else {
478 0
479 };
480 if start > 0 {
481 let (candidate, used) =
482 next_free_indexed_name(&validated, start, &emitted_names);
483 validated = match validate_tar_entry_path(&candidate, max_path_len)
486 {
487 Ok(path) => path,
488 Err(e) => {
489 let _ = tx.blocking_send(Err(e));
490 return;
491 }
492 };
493 *occurrences = (*occurrences).max(used + 1);
494 }
495 emitted_names.insert(validated.clone());
496 }
497 }
498
499 if tx
500 .blocking_send(Ok(TarEntryData {
501 index,
502 path: validated,
503 size: data.len() as u64,
504 data,
505 }))
506 .is_err()
507 {
508 return;
509 }
510 }
511
512 if emitted == 0 && !allow_empty {
513 let _ = tx.blocking_send(Err(err_empty_archive()));
514 }
515 });
516
517 while let Some(result) = rx.recv().await {
518 match result {
519 Ok(entry) => {
520 let TarEntryData {
521 index,
522 path,
523 size,
524 data,
525 } = entry;
526 let msg = Message {
527 headers: parent.input.headers.clone(),
528 body: Body::Bytes(Bytes::from(data)),
529 };
530 let mut ex = Exchange::new(msg);
531 ex.input.headers.remove("Content-Length");
534 ex.input.headers.remove("Content-Type");
535 ex.properties = parent.properties.clone();
536 ex.remove_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED);
539 ex.pattern = parent.pattern;
540 ex.otel_context = parent.otel_context.clone();
541
542 let entry_name = Path::new(&path)
543 .file_name()
544 .map(|n| n.to_string_lossy().to_string())
545 .unwrap_or_default();
546
547 ex.input.headers.insert(
548 CAMEL_TAR_ENTRY_NAME.to_string(),
549 Value::String(entry_name),
550 );
551 ex.input
552 .headers
553 .insert(CAMEL_TAR_ENTRY_PATH.to_string(), Value::String(path));
554 ex.input.headers.insert(
555 CAMEL_TAR_ENTRY_INDEX.to_string(),
556 Value::from(index as u64),
557 );
558 ex.input
559 .headers
560 .insert(CAMEL_TAR_ENTRY_SIZE.to_string(), Value::from(size));
561 ex.input.headers.insert(
562 CAMEL_TAR_ENTRY_IS_DIRECTORY.to_string(),
563 Value::Bool(false),
564 );
565
566 yield Ok(ex);
567 }
568 Err(e) => {
569 yield Err(e);
570 }
571 }
572 }
573 })
574}
575
576pub fn tar_splitter(config: TarSplitConfig) -> StreamingSplitExpression {
579 Arc::new(move |exchange: Exchange| {
580 let config = config.clone();
581 match exchange.input.body.clone() {
582 Body::Bytes(b) => split_tar_bytes(exchange, b, config),
583 Body::Text(s) => split_tar_bytes(exchange, Bytes::from(s.as_bytes().to_vec()), config),
584 _ => Box::pin(async_stream::stream! {
585 yield Err(CamelError::TypeConversionFailed(
586 "TarSplitter requires Body::Bytes or Body::Text".to_string(),
587 ));
588 }),
589 }
590 })
591}
592
593pub fn tar_gz_splitter(config: TarSplitConfig) -> StreamingSplitExpression {
596 Arc::new(move |exchange: Exchange| {
597 let config = config.clone();
598 match exchange.input.body.clone() {
599 Body::Bytes(b) => split_tar_gz_bytes(exchange, b, config),
600 Body::Text(s) => {
601 split_tar_gz_bytes(exchange, Bytes::from(s.as_bytes().to_vec()), config)
602 }
603 _ => Box::pin(async_stream::stream! {
604 yield Err(CamelError::TypeConversionFailed(
605 "TarGzSplitter requires Body::Bytes or Body::Text".to_string(),
606 ));
607 }),
608 }
609 })
610}
611
612#[cfg(test)]
613mod tests {
614 use super::*;
615 use crate::archive_splitter::test_util::make_zip_raw;
616 use crate::zip_splitter::{CAMEL_ZIP_ENTRY_PATH, ZipSplitConfig, zip_splitter};
617 use futures::StreamExt;
618
619 fn tar_header(name: &str, size: u64, typeflag: u8) -> [u8; 512] {
624 let mut h = [0u8; 512];
625 h[..name.len()].copy_from_slice(name.as_bytes());
626 h[124..136].copy_from_slice(format!("{size:011o}\0").as_bytes());
627 h[148..156].copy_from_slice(b" ");
629 h[156] = typeflag;
630 h[257..263].copy_from_slice(b"ustar\0");
631 h[263..265].copy_from_slice(b"00");
632 let sum: u32 = h.iter().map(|&b| u32::from(b)).sum();
633 h[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes());
634 h
635 }
636
637 fn tar_archive(entries: &[(&str, u8, &[u8])]) -> Vec<u8> {
640 let mut out = Vec::new();
641 for &(name, typeflag, data) in entries {
642 out.extend_from_slice(&tar_header(name, data.len() as u64, typeflag));
643 if !data.is_empty() {
644 let mut block = data.to_vec();
645 let rem = block.len() % 512;
646 if rem != 0 {
647 block.extend_from_slice(&vec![0u8; 512 - rem]);
648 }
649 out.extend_from_slice(&block);
650 }
651 }
652 out.extend_from_slice(&[0u8; 1024]);
653 out
654 }
655
656 async fn collect(
657 config: TarSplitConfig,
658 tar_data: Vec<u8>,
659 ) -> Vec<Result<Exchange, CamelError>> {
660 let expr = tar_splitter(config);
661 let exchange = Exchange::new(Message {
662 headers: Default::default(),
663 body: Body::Bytes(Bytes::from(tar_data)),
664 });
665 expr(exchange).collect().await
666 }
667
668 #[test]
669 fn tar_split_config_rejects_unknown_fields() {
670 let cfg: TarSplitConfig =
672 serde_json::from_str(r#"{"max_entries": 5, "allow_empty_archive": true}"#)
673 .expect("valid config must deserialize");
674 assert_eq!(cfg.max_entries, 5);
675 assert!(cfg.allow_empty_archive);
676 assert_eq!(cfg.max_per_entry_size, DEFAULT_MAX_PER_ENTRY_SIZE);
677 assert_eq!(cfg.max_path_length, DEFAULT_MAX_PATH_LENGTH);
678
679 let err = serde_json::from_str::<TarSplitConfig>(r#"{"unknown_key": 1}"#)
681 .expect_err("unknown config key must fail");
682 assert!(
683 err.to_string().contains("unknown field `unknown_key`"),
684 "{err}"
685 );
686 }
687
688 #[tokio::test]
689 async fn tar_split_emits_regular_files_in_header_order() {
690 let tar_data = tar_archive(&[
693 ("first.txt", b'0', b"alpha".as_slice()),
694 ("docs", b'5', b""),
695 ("link.txt", b'2', b""),
696 ("hard.txt", b'1', b""),
697 ("dev-zero", b'3', b""),
698 ("second.txt", b'0', b"beta".as_slice()),
699 ]);
700 let results = collect(TarSplitConfig::default(), tar_data).await;
701 assert_eq!(results.len(), 2, "non-regular entries must be omitted");
702
703 let first = results[0].as_ref().expect("first fragment ok");
704 let second = results[1].as_ref().expect("second fragment ok");
705
706 assert_eq!(
707 first.input.headers.get(CAMEL_TAR_ENTRY_NAME),
708 Some(&Value::String("first.txt".to_string()))
709 );
710 assert_eq!(
711 second.input.headers.get(CAMEL_TAR_ENTRY_NAME),
712 Some(&Value::String("second.txt".to_string()))
713 );
714 assert_eq!(
715 first.input.headers.get(CAMEL_TAR_ENTRY_INDEX),
716 Some(&Value::from(0u64))
717 );
718 assert_eq!(
719 second.input.headers.get(CAMEL_TAR_ENTRY_INDEX),
720 Some(&Value::from(1u64))
721 );
722 match &first.input.body {
723 Body::Bytes(b) => assert_eq!(b.as_ref(), b"alpha"),
724 other => panic!("expected Body::Bytes, got {other:?}"),
725 }
726 match &second.input.body {
727 Body::Bytes(b) => assert_eq!(b.as_ref(), b"beta"),
728 other => panic!("expected Body::Bytes, got {other:?}"),
729 }
730 assert_eq!(
731 first.input.headers.get(CAMEL_TAR_ENTRY_PATH),
732 Some(&Value::String("first.txt".to_string()))
733 );
734 assert_eq!(
735 first.input.headers.get(CAMEL_TAR_ENTRY_SIZE),
736 Some(&Value::from(5u64))
737 );
738 assert_eq!(
739 first.input.headers.get(CAMEL_TAR_ENTRY_IS_DIRECTORY),
740 Some(&Value::Bool(false))
741 );
742 }
743
744 #[tokio::test]
745 async fn tar_split_rejects_traversal_and_absolute_names() {
746 let cases = [
747 (
748 "../escape",
749 "TAR entry path contains '..' traversal: ../escape",
750 ),
751 ("/absolute", "TAR entry path is absolute: /absolute"),
752 ];
753 for (name, expected) in cases {
754 let tar_data = tar_archive(&[(name, b'0', b"oops".as_slice())]);
755 let results = collect(TarSplitConfig::default(), tar_data).await;
756 assert_eq!(
757 results.len(),
758 1,
759 "expected exactly the validation error for {name}"
760 );
761 let err = results[0]
762 .as_ref()
763 .expect_err(&format!("'{name}' must be rejected"))
764 .to_string();
765 assert!(
766 err.contains(expected),
767 "error text mismatch for {name}: {err}"
768 );
769 }
770 }
771
772 #[tokio::test]
773 async fn tar_split_enforces_all_bounds() {
774 let tar_data = tar_archive(&[
776 ("a.txt", b'0', b"1".as_slice()),
777 ("b.txt", b'0', b"2".as_slice()),
778 ("c.txt", b'0', b"3".as_slice()),
779 ]);
780 let config = TarSplitConfig {
781 max_entries: 2,
782 ..Default::default()
783 };
784 let results = collect(config, tar_data).await;
785 assert!(
786 results.iter().any(|r| r
787 .as_ref()
788 .is_err_and(|e| e.to_string().contains("TAR exceeds max entries: 2"))),
789 "expected entry-count cap error, got {results:?}"
790 );
791
792 let tar_data = tar_archive(&[("big.bin", b'0', &[b'x'; 200])]);
794 let config = TarSplitConfig {
795 max_per_entry_size: 100,
796 ..Default::default()
797 };
798 let results = collect(config, tar_data).await;
799 assert_eq!(results.len(), 1);
800 assert!(
801 results[0]
802 .as_ref()
803 .expect_err("per-entry cap")
804 .to_string()
805 .contains("TAR entry 'big.bin' size 200 exceeds max 100"),
806 "expected per-entry cap error"
807 );
808
809 let tar_data = tar_archive(&[
811 ("a.txt", b'0', b"0123456789".as_slice()),
812 ("b.txt", b'0', b"9876543210".as_slice()),
813 ]);
814 let config = TarSplitConfig {
815 max_total_decoded_size: 15,
816 ..Default::default()
817 };
818 let results = collect(config, tar_data).await;
819 assert!(
820 results.iter().any(|r| r.as_ref().is_err_and(|e| e
821 .to_string()
822 .contains("TAR total decoded size exceeds max 15"))),
823 "expected total-decoded cap error, got {results:?}"
824 );
825
826 let tar_data = tar_archive(&[("a.txt", b'0', b"x".as_slice())]);
828 let config = TarSplitConfig {
829 max_compressed_size: 512,
830 ..Default::default()
831 };
832 let results = collect(config, tar_data).await;
833 assert_eq!(results.len(), 1);
834 assert!(
835 results[0]
836 .as_ref()
837 .expect_err("compressed-input cap")
838 .to_string()
839 .contains("exceeds max 512"),
840 "expected compressed-input cap error"
841 );
842
843 let long_name = "a-very-long-entry-name.bin";
845 let tar_data = tar_archive(&[(long_name, b'0', b"x".as_slice())]);
846 let config = TarSplitConfig {
847 max_path_length: 10,
848 ..Default::default()
849 };
850 let results = collect(config, tar_data).await;
851 assert_eq!(results.len(), 1);
852 assert!(
853 results[0]
854 .as_ref()
855 .expect_err("path-length cap")
856 .to_string()
857 .contains(&format!(
858 "TAR entry path exceeds max length: {} > 10",
859 long_name.len()
860 )),
861 "expected path-length cap error"
862 );
863 }
864
865 #[tokio::test]
866 async fn tar_split_empty_and_directory_only_archives_emit_zero() {
867 let config = TarSplitConfig {
868 allow_empty_archive: true,
869 ..Default::default()
870 };
871 let results = collect(config.clone(), tar_archive(&[])).await;
872 assert!(
873 results.is_empty(),
874 "empty archive must emit zero fragments: {results:?}"
875 );
876
877 let results = collect(
878 config,
879 tar_archive(&[("only-dir", b'5', b""), ("nested", b'5', b"")]),
880 )
881 .await;
882 assert!(
883 results.is_empty(),
884 "directory-only archive must emit zero fragments: {results:?}"
885 );
886 }
887
888 fn gzip_bytes(raw: &[u8]) -> Vec<u8> {
890 use std::io::Write as _;
891 let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
892 encoder.write_all(raw).expect("gzip write");
893 encoder.finish().expect("gzip finish")
894 }
895
896 async fn collect_gz(
897 config: TarSplitConfig,
898 gz_data: Vec<u8>,
899 ) -> Vec<Result<Exchange, CamelError>> {
900 let expr = tar_gz_splitter(config);
901 let exchange = Exchange::new(Message {
902 headers: Default::default(),
903 body: Body::Bytes(Bytes::from(gz_data)),
904 });
905 expr(exchange).collect().await
906 }
907
908 fn header_string(exchange: &Exchange, key: &str) -> String {
909 match exchange.input.headers.get(key) {
910 Some(Value::String(s)) => s.clone(),
911 other => panic!("header {key} must be a string, got {other:?}"),
912 }
913 }
914
915 fn body_bytes(exchange: &Exchange) -> Vec<u8> {
916 match &exchange.input.body {
917 Body::Bytes(b) => b.to_vec(),
918 other => panic!("expected Body::Bytes, got {other:?}"),
919 }
920 }
921
922 #[tokio::test]
923 async fn tar_gz_split_matches_tar_metadata() {
924 let tar_data = tar_archive(&[
925 ("first.txt", b'0', b"alpha".as_slice()),
926 ("docs", b'5', b""),
927 ("second.txt", b'0', b"beta".as_slice()),
928 ]);
929
930 let tar_results = collect(TarSplitConfig::default(), tar_data.clone()).await;
931 let gz_results = collect_gz(TarSplitConfig::default(), gzip_bytes(&tar_data)).await;
932
933 assert_eq!(gz_results.len(), tar_results.len(), "same entries emitted");
934 for (t, g) in tar_results.iter().zip(gz_results.iter()) {
935 let t = t.as_ref().expect("TAR fragment ok");
936 let g = g.as_ref().expect("TAR.GZ fragment ok");
937 for header in [
938 CAMEL_TAR_ENTRY_NAME,
939 CAMEL_TAR_ENTRY_PATH,
940 CAMEL_TAR_ENTRY_INDEX,
941 CAMEL_TAR_ENTRY_SIZE,
942 CAMEL_TAR_ENTRY_IS_DIRECTORY,
943 ] {
944 assert_eq!(
945 t.input.headers.get(header),
946 g.input.headers.get(header),
947 "header {header} must match TAR output"
948 );
949 }
950 assert_eq!(t.input.body, g.input.body, "body must match TAR output");
951 }
952 }
953
954 #[tokio::test]
960 async fn tar_split_applies_shared_duplicate_policy() {
961 let tar_data = tar_archive(&[
962 ("dup.txt", b'0', b"one".as_slice()),
963 ("other.txt", b'0', b"mid".as_slice()),
964 ("dup.txt", b'0', b"two".as_slice()),
965 ]);
966
967 let reject_config = TarSplitConfig {
969 duplicate_names_policy: DuplicatePolicy::Reject,
970 ..Default::default()
971 };
972 let results = collect(reject_config, tar_data.clone()).await;
973 assert!(
974 results.iter().any(|r| r
975 .as_ref()
976 .is_err_and(|e| e.to_string().contains("Duplicate TAR entry name: dup.txt"))),
977 "reject policy must fail on the duplicate: {results:?}"
978 );
979
980 let index_config = TarSplitConfig {
983 duplicate_names_policy: DuplicatePolicy::AllowWithIndex,
984 ..Default::default()
985 };
986 let first_run = collect(index_config.clone(), tar_data.clone()).await;
987 let second_run = collect(index_config, tar_data).await;
988
989 assert_eq!(first_run.len(), 3, "every entry must be emitted");
990 let snapshot: Vec<(String, String, Vec<u8>)> = first_run
991 .iter()
992 .map(|r| {
993 let ex = r.as_ref().expect("allow-with-index must not fail");
994 (
995 header_string(ex, CAMEL_TAR_ENTRY_PATH),
996 header_string(ex, CAMEL_TAR_ENTRY_NAME),
997 body_bytes(ex),
998 )
999 })
1000 .collect();
1001 assert_eq!(
1002 snapshot,
1003 [
1004 (
1005 "dup.txt".to_string(),
1006 "dup.txt".to_string(),
1007 b"one".to_vec()
1008 ),
1009 (
1010 "other.txt".to_string(),
1011 "other.txt".to_string(),
1012 b"mid".to_vec()
1013 ),
1014 (
1015 "dup.1.txt".to_string(),
1016 "dup.1.txt".to_string(),
1017 b"two".to_vec()
1018 ),
1019 ],
1020 "indexed names must be deterministic"
1021 );
1022
1023 let second_paths: Vec<String> = second_run
1024 .iter()
1025 .map(|r| {
1026 let ex = r.as_ref().expect("second run must not fail");
1027 header_string(ex, CAMEL_TAR_ENTRY_PATH)
1028 })
1029 .collect();
1030 let first_paths: Vec<String> = snapshot.into_iter().map(|(p, _, _)| p).collect();
1031 assert_eq!(
1032 first_paths, second_paths,
1033 "naming must be deterministic across runs"
1034 );
1035 }
1036
1037 #[tokio::test]
1050 async fn tar_duplicate_policy_is_shared_zip_collapse_is_pinned() {
1051 let tar_data = tar_archive(&[
1052 ("dup.txt", b'0', b"one".as_slice()),
1053 ("dup.txt", b'0', b"two".as_slice()),
1054 ]);
1055 let zip_data = make_zip_raw(&[
1056 ("dup.txt", b"one".as_slice()),
1057 ("dup.txt", b"two".as_slice()),
1058 ]);
1059
1060 let index_config = TarSplitConfig {
1063 duplicate_names_policy: DuplicatePolicy::AllowWithIndex,
1064 ..Default::default()
1065 };
1066 let tar_results = collect(index_config, tar_data.clone()).await;
1067 let tar_paths: Vec<String> = tar_results
1068 .iter()
1069 .map(|r| header_string(r.as_ref().expect("TAR fragment ok"), CAMEL_TAR_ENTRY_PATH))
1070 .collect();
1071 assert_eq!(
1072 tar_paths,
1073 ["dup.txt".to_string(), "dup.1.txt".to_string()],
1074 "TAR indexed names must come from the shared mangling helper"
1075 );
1076
1077 let zip_expr = zip_splitter(ZipSplitConfig {
1081 duplicate_names_policy: DuplicatePolicy::AllowWithIndex,
1082 ..Default::default()
1083 });
1084 let zip_exchange = Exchange::new(Message {
1085 headers: Default::default(),
1086 body: Body::Bytes(Bytes::from(zip_data.clone())),
1087 });
1088 let zip_results: Vec<Result<Exchange, CamelError>> = zip_expr(zip_exchange).collect().await;
1089 assert_eq!(
1090 zip_results.len(),
1091 1,
1092 "the zip reader must collapse duplicate names for now: {zip_results:?}"
1093 );
1094 let zip_path = header_string(
1095 zip_results[0].as_ref().expect("ZIP fragment ok"),
1096 CAMEL_ZIP_ENTRY_PATH,
1097 );
1098 assert_eq!(
1099 zip_path, "dup.txt",
1100 "unique observable names stay unmangled"
1101 );
1102
1103 let reject_config = TarSplitConfig {
1105 duplicate_names_policy: DuplicatePolicy::Reject,
1106 ..Default::default()
1107 };
1108 let tar_err = collect(reject_config, tar_data).await;
1109 let tar_msg = tar_err
1110 .iter()
1111 .find_map(|r| r.as_ref().err().map(|e| e.to_string()))
1112 .expect("TAR reject must fail");
1113 assert!(
1114 tar_msg.contains("Duplicate TAR entry name: dup.txt"),
1115 "{tar_msg}"
1116 );
1117
1118 let zip_expr = zip_splitter(ZipSplitConfig {
1122 duplicate_names_policy: DuplicatePolicy::Reject,
1123 ..Default::default()
1124 });
1125 let zip_exchange = Exchange::new(Message {
1126 headers: Default::default(),
1127 body: Body::Bytes(Bytes::from(zip_data)),
1128 });
1129 let zip_results: Vec<Result<Exchange, CamelError>> = zip_expr(zip_exchange).collect().await;
1130 assert!(
1131 zip_results.iter().all(|r| r.is_ok()),
1132 "collapsed names are unique, so reject must not fire: {zip_results:?}"
1133 );
1134 }
1135
1136 #[tokio::test]
1137 async fn tar_gz_compressed_input_limit_is_checked() {
1138 let gz = gzip_bytes(&tar_archive(&[("a.txt", b'0', b"payload".as_slice())]));
1139 let config = TarSplitConfig {
1140 max_compressed_size: gz.len() as u64 - 1,
1141 ..Default::default()
1142 };
1143 let results = collect_gz(config, gz.clone()).await;
1144 assert_eq!(results.len(), 1);
1145 let err = results[0]
1146 .as_ref()
1147 .expect_err("compressed input over the cap must fail before decompression")
1148 .to_string();
1149 assert!(
1150 err.contains(&format!(
1151 "TAR compressed size {} exceeds max {}",
1152 gz.len(),
1153 gz.len() - 1
1154 )),
1155 "expected the compressed-input cap error: {err}"
1156 );
1157 }
1158
1159 #[tokio::test]
1160 async fn tar_gz_multi_member_is_rejected() {
1161 let member_one = gzip_bytes(&tar_archive(&[("a.txt", b'0', b"one".as_slice())]));
1162 let member_two = gzip_bytes(&tar_archive(&[("b.txt", b'0', b"two".as_slice())]));
1163 let mut concatenated = member_one;
1164 concatenated.extend_from_slice(&member_two);
1165
1166 let results = collect_gz(TarSplitConfig::default(), concatenated).await;
1167 assert_eq!(results.len(), 1);
1168 let err = results[0]
1169 .as_ref()
1170 .expect_err("multi-member input must be rejected, not split silently")
1171 .to_string();
1172 assert!(
1173 err.contains("multiple GZIP members"),
1174 "expected the unsupported-multi-member error: {err}"
1175 );
1176 }
1177
1178 #[tokio::test]
1184 async fn tar_gz_total_decoded_cap_counts_payload_not_framing() {
1185 let payload: &[u8] = b"0123456789";
1189 let gz = gzip_bytes(&tar_archive(&[
1190 ("a.txt", b'0', payload),
1191 ("b.txt", b'0', payload),
1192 ("c.txt", b'0', payload),
1193 ]));
1194 let results = collect_gz(
1195 TarSplitConfig {
1196 max_total_decoded_size: 64,
1197 ..Default::default()
1198 },
1199 gz,
1200 )
1201 .await;
1202 assert_eq!(
1203 results.len(),
1204 3,
1205 "framing must not count against the payload cap"
1206 );
1207 for r in &results {
1208 assert!(r.is_ok(), "fragment must succeed: {r:?}");
1209 }
1210
1211 let big = vec![b'x'; 100];
1214 let gz_big = gzip_bytes(&tar_archive(&[("big.txt", b'0', big.as_slice())]));
1215 let over = collect_gz(
1216 TarSplitConfig {
1217 max_total_decoded_size: 64,
1218 ..Default::default()
1219 },
1220 gz_big,
1221 )
1222 .await;
1223 assert_eq!(over.len(), 1);
1224 let err = over[0]
1225 .as_ref()
1226 .expect_err("payload over the cap must fail at the parse")
1227 .to_string();
1228 assert!(
1229 err.contains("TAR total decoded size exceeds max 64"),
1230 "expected the payload-cap error: {err}"
1231 );
1232 }
1233
1234 #[test]
1238 fn tar_gz_decode_budget_is_fail_closed_under_absurd_entry_caps() {
1239 assert_eq!(tar_per_entry_framing(4096), 6143);
1243 assert_eq!(
1246 tar_gz_decode_budget(&TarSplitConfig::default()),
1247 1024 * 1024 * 1024 + 61_430_000 + 64 * 1024
1248 );
1249
1250 let config = TarSplitConfig {
1251 max_entries: usize::MAX,
1252 max_total_decoded_size: 1024,
1253 ..Default::default()
1254 };
1255 let budget = tar_gz_decode_budget(&config);
1256 assert_eq!(
1257 budget,
1258 1024 + MAX_TAR_FRAMING_ALLOWANCE + BASE_TAR_FRAMING_ALLOWANCE,
1259 "the entry-count term must hit the absolute ceiling, not saturate"
1260 );
1261 assert!(budget < u64::MAX, "the budget must stay fail-closed finite");
1262 }
1263
1264 #[tokio::test]
1269 async fn tar_gz_long_name_extension_blocks_stay_within_budget() {
1270 let long_path = format!("{}file.txt", "very/long/directory/prefix/".repeat(12));
1271 assert!(long_path.len() > 100, "the path must exceed the name field");
1272
1273 let mut builder = tar::Builder::new(Vec::new());
1276 let mut header = tar::Header::new_gnu();
1277 header.set_size(10);
1278 header.set_mode(0o644);
1279 header.set_cksum();
1280 builder
1281 .append_data(&mut header, long_path.as_str(), b"0123456789".as_slice())
1282 .expect("append GNU long-name entry");
1283 let gnu_archive = builder.into_inner().expect("finish GNU archive");
1284
1285 let pax_record = {
1288 let body = format!(" path={long_path}\n");
1289 let mut total = body.len() + 1;
1291 while total.to_string().len() + body.len() != total {
1292 total += 1;
1293 }
1294 format!("{total}{body}").into_bytes()
1295 };
1296 let pax_archive = tar_archive(&[
1297 ("./PaxHeaders.0/f", b'x', pax_record.as_slice()),
1298 ("file.txt", b'0', b"0123456789".as_slice()),
1299 ]);
1300
1301 for (label, archive) in [("gnu", gnu_archive), ("pax", pax_archive)] {
1302 let gz = gzip_bytes(&archive);
1303 let results = collect_gz(
1304 TarSplitConfig {
1305 max_total_decoded_size: 32,
1308 ..Default::default()
1309 },
1310 gz,
1311 )
1312 .await;
1313 assert_eq!(results.len(), 1, "{label}: one fragment expected");
1314 let ex = results[0]
1315 .as_ref()
1316 .unwrap_or_else(|e| panic!("{label}: long-name archive must split: {e}"));
1317 let path = header_string(ex, CAMEL_TAR_ENTRY_PATH);
1318 assert!(
1319 path.ends_with("file.txt") && path.len() > 100,
1320 "{label}: the long path must survive: {path}"
1321 );
1322 }
1323 }
1324
1325 #[tokio::test]
1330 async fn tar_split_indexed_names_never_collide_with_emitted() {
1331 let data = tar_archive(&[
1332 ("a.txt", b'0', b"first".as_slice()),
1333 ("a.1.txt", b'0', b"literal".as_slice()),
1334 ("a.txt", b'0', b"second".as_slice()),
1335 ]);
1336 let results = collect(
1337 TarSplitConfig {
1338 duplicate_names_policy: DuplicatePolicy::AllowWithIndex,
1339 ..Default::default()
1340 },
1341 data,
1342 )
1343 .await;
1344 let paths: Vec<String> = results
1345 .iter()
1346 .map(|r| header_string(r.as_ref().expect("fragment ok"), CAMEL_TAR_ENTRY_PATH))
1347 .collect();
1348 assert_eq!(
1349 paths,
1350 [
1351 "a.txt".to_string(),
1352 "a.1.txt".to_string(),
1353 "a.2.txt".to_string()
1354 ],
1355 "the second a.txt must skip the occupied a.1.txt"
1356 );
1357
1358 let data = tar_archive(&[
1362 ("a.txt", b'0', b"first".as_slice()),
1363 ("a.txt", b'0', b"second".as_slice()),
1364 ("a.1.txt", b'0', b"literal".as_slice()),
1365 ]);
1366 let results = collect(
1367 TarSplitConfig {
1368 duplicate_names_policy: DuplicatePolicy::AllowWithIndex,
1369 ..Default::default()
1370 },
1371 data,
1372 )
1373 .await;
1374 let paths: Vec<String> = results
1375 .iter()
1376 .map(|r| header_string(r.as_ref().expect("fragment ok"), CAMEL_TAR_ENTRY_PATH))
1377 .collect();
1378 assert_eq!(
1379 paths,
1380 [
1381 "a.txt".to_string(),
1382 "a.1.txt".to_string(),
1383 "a.1.1.txt".to_string()
1384 ],
1385 "the literal a.1.txt must skip the emitted indexed a.1.txt"
1386 );
1387 }
1388
1389 #[tokio::test]
1390 async fn tar_split_empty_default_is_rejected() {
1391 let results = collect(TarSplitConfig::default(), tar_archive(&[])).await;
1392 assert_eq!(results.len(), 1);
1393 let err = results[0]
1394 .as_ref()
1395 .expect_err("empty archive must fail closed by default")
1396 .to_string();
1397 assert!(
1398 err.contains("no regular entries") && err.contains("allow_empty_archive"),
1399 "expected the fail-closed empty-archive error: {err}"
1400 );
1401 }
1402
1403 #[tokio::test]
1404 async fn tar_fragment_clears_marker() {
1405 let tar_data = tar_archive(&[("hello.txt", b'0', b"hello world".as_slice())]);
1406 let mut parent = Exchange::new(Message {
1407 headers: Default::default(),
1408 body: Body::Bytes(Bytes::from(tar_data)),
1409 });
1410 parent.set_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED, Value::Bool(true));
1411 parent.input.headers.insert(
1412 "Content-Type".to_string(),
1413 Value::String("application/x-tar".into()),
1414 );
1415 assert_eq!(
1416 parent.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
1417 Some(&Value::Bool(true)),
1418 "parent must start with the marker armed"
1419 );
1420
1421 let results = tar_splitter(TarSplitConfig::default())(parent)
1422 .collect::<Vec<_>>()
1423 .await;
1424
1425 assert_eq!(results.len(), 1);
1426 let fragment = results[0].as_ref().expect("entry fragment ok");
1427 assert_eq!(
1428 fragment.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
1429 None,
1430 "the entry fragment must clear the inherited suppression marker"
1431 );
1432 }
1433}