Skip to main content

camel_processor/
zip_splitter.rs

1use bytes::Bytes;
2use std::collections::HashMap;
3use std::io::Read;
4use std::path::Path;
5use std::pin::Pin;
6use std::sync::Arc;
7use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
8use tokio::sync::mpsc;
9
10use camel_api::{
11    Body, CamelError, Exchange, Message, PROPERTY_HTTP_CONTENT_TYPE_INHERITED,
12    StreamingSplitExpression, Value,
13};
14use futures::Stream;
15
16use crate::archive_splitter::{
17    DEFAULT_MAX_PATH_LENGTH, next_free_indexed_name, validate_entry_path,
18};
19
20/// Duplicate-name policy shared with the TAR splitter; re-exported to
21/// preserve the historical public path
22/// `camel_processor::zip_splitter::DuplicatePolicy`.
23pub use crate::archive_splitter::DuplicatePolicy;
24
25const DEFAULT_MAX_ENTRIES: usize = 10000;
26const DEFAULT_MAX_TOTAL_DECOMPRESSED_SIZE: u64 = 1_073_741_824;
27const DEFAULT_MAX_PER_ENTRY_SIZE: u64 = 512 * 1024 * 1024;
28const DEFAULT_MAX_COMPRESSED_SIZE: u64 = 1_073_741_824;
29const DEFAULT_CHANNEL_CAPACITY: usize = 2;
30
31pub const CAMEL_ZIP_ENTRY_NAME: &str = "CamelZipEntryName";
32pub const CAMEL_ZIP_ENTRY_PATH: &str = "CamelZipEntryPath";
33pub const CAMEL_ZIP_ENTRY_INDEX: &str = "CamelZipEntryIndex";
34pub const CAMEL_ZIP_ENTRY_SIZE: &str = "CamelZipEntrySize";
35pub const CAMEL_ZIP_ENTRY_COMPRESSED_SIZE: &str = "CamelZipEntryCompressedSize";
36pub const CAMEL_ZIP_ENTRY_CRC32: &str = "CamelZipEntryCrc32";
37pub const CAMEL_ZIP_ENTRY_IS_DIRECTORY: &str = "CamelZipEntryIsDirectory";
38pub const CAMEL_ZIP_ENTRY_COMPRESSION: &str = "CamelZipEntryCompression";
39
40#[derive(Debug, Clone)]
41pub struct ZipSplitConfig {
42    pub max_entries: usize,
43    pub max_total_decompressed_size: u64,
44    pub max_per_entry_size: u64,
45    pub max_compressed_size: u64,
46    pub max_path_length: usize,
47    pub allow_empty_directories: bool,
48    pub duplicate_names_policy: DuplicatePolicy,
49    pub channel_capacity: usize,
50}
51
52impl Default for ZipSplitConfig {
53    fn default() -> Self {
54        Self {
55            max_entries: DEFAULT_MAX_ENTRIES,
56            max_total_decompressed_size: DEFAULT_MAX_TOTAL_DECOMPRESSED_SIZE,
57            max_per_entry_size: DEFAULT_MAX_PER_ENTRY_SIZE,
58            max_compressed_size: DEFAULT_MAX_COMPRESSED_SIZE,
59            max_path_length: DEFAULT_MAX_PATH_LENGTH,
60            allow_empty_directories: false,
61            duplicate_names_policy: DuplicatePolicy::AllowWithIndex,
62            channel_capacity: DEFAULT_CHANNEL_CAPACITY,
63        }
64    }
65}
66
67struct ZipEntryData {
68    index: usize,
69    path: String,
70    size: u64,
71    compressed_size: u64,
72    crc32: Option<u32>,
73    is_dir: bool,
74    compression: String,
75    data: Vec<u8>,
76}
77
78/// Split a ZIP archive's bytes into a stream of Exchanges, one per entry.
79///
80/// Takes owned `Bytes` (for `'static` lifetime), a parent `Exchange` whose headers
81/// and properties are cloned into each entry's exchange, and a `ZipSplitConfig`
82/// controlling limits and policy.
83///
84/// This is the core extraction — callers such as `zip_splitter()` or `camel-core`
85/// component code can invoke it directly with already-acquired bytes.
86pub fn split_zip_bytes(
87    parent: Exchange,
88    bytes: Bytes,
89    config: ZipSplitConfig,
90) -> Pin<Box<dyn Stream<Item = Result<Exchange, CamelError>> + Send>> {
91    Box::pin(async_stream::stream! {
92        if config.channel_capacity == 0 {
93            yield Err(CamelError::Config(
94                "ZipSplitConfig.channel_capacity must be > 0".into(),
95            ));
96            return;
97        }
98
99        if bytes.len() as u64 > config.max_compressed_size {
100            yield Err(CamelError::TypeConversionFailed(format!(
101                "ZIP compressed size {} exceeds max {}",
102                bytes.len(),
103                config.max_compressed_size
104            )));
105            return;
106        }
107
108        let (tx, mut rx) = mpsc::channel::<Result<ZipEntryData, CamelError>>(config.channel_capacity);
109
110        let total_decompressed = Arc::new(AtomicU64::new(0));
111        let entry_count = Arc::new(AtomicUsize::new(0));
112        // Entry name -> occurrence count; drives both duplicate policies and
113        // mirrors the TAR splitter's bookkeeping exactly.
114        let seen_names: Arc<std::sync::Mutex<HashMap<String, usize>>> =
115            Arc::new(std::sync::Mutex::new(HashMap::new()));
116        // Names already emitted (original or indexed). The occurrence
117        // counter alone cannot guarantee uniqueness — a literal entry can
118        // occupy an indexed name first — so this set is the collision
119        // authority, mirroring the TAR splitter.
120        let emitted_names: Arc<std::sync::Mutex<std::collections::HashSet<String>>> =
121            Arc::new(std::sync::Mutex::new(std::collections::HashSet::new()));
122
123        let max_entries = config.max_entries;
124        let max_per_entry = config.max_per_entry_size;
125        let max_total = config.max_total_decompressed_size;
126        let max_path_len = config.max_path_length;
127        let allow_dirs = config.allow_empty_directories;
128        let dup_policy = config.duplicate_names_policy;
129
130        tokio::task::spawn_blocking(move || {
131            let reader = std::io::Cursor::new(bytes);
132            let mut archive = match zip::ZipArchive::new(reader) {
133                Ok(a) => a,
134                Err(e) => {
135                    let _ = tx.blocking_send(Err(CamelError::TypeConversionFailed(
136                        format!("Invalid ZIP archive: {e}"),
137                    )));
138                    return;
139                }
140            };
141
142            for i in 0..archive.len() {
143                let mut entry = match archive.by_index(i) {
144                    Ok(e) => e,
145                    Err(e) => {
146                        let _ = tx.blocking_send(Err(CamelError::TypeConversionFailed(
147                            format!("Failed to read ZIP entry {i}: {e}"),
148                        )));
149                        return;
150                    }
151                };
152
153                let raw_name = match entry.name() {
154                    Ok(n) => n.into_owned(),
155                    Err(e) => {
156                        let _ = tx.blocking_send(Err(CamelError::TypeConversionFailed(
157                            format!("Failed to read ZIP entry {i} name: {e}"),
158                        )));
159                        return;
160                    }
161                };
162                let is_dir = entry.is_dir();
163
164                let mut validated = match validate_entry_path(&raw_name, max_path_len, "ZIP") {
165                    Ok(p) => p,
166                    Err(e) => {
167                        let _ = tx.blocking_send(Err(e));
168                        return;
169                    }
170                };
171
172                if is_dir {
173                    if allow_dirs {
174                        let count = entry_count.fetch_add(1, Ordering::SeqCst);
175                        if count >= max_entries {
176                            let _ = tx.blocking_send(Err(CamelError::TypeConversionFailed(
177                                format!("ZIP exceeds max entries: {max_entries}"),
178                            )));
179                            return;
180                        }
181                        if tx.blocking_send(Ok(ZipEntryData {
182                            index: count,
183                            path: validated,
184                            size: 0,
185                            compressed_size: entry.compressed_size(),
186                            crc32: Some(entry.crc32()),
187                            is_dir: true,
188                            compression: format!("{:?}", entry.compression()),
189                            data: Vec::new(),
190                        }))
191                        .is_err()
192                        {
193                            return;
194                        }
195                    }
196                    continue;
197                }
198
199                let compressed_size = entry.compressed_size();
200                let crc32 = entry.crc32();
201
202                let mut data = Vec::new();
203                let mut limited =
204                    std::io::Read::take(&mut entry, max_per_entry.saturating_add(1));
205                if let Err(e) = limited.read_to_end(&mut data) {
206                    let _ = tx.blocking_send(Err(CamelError::TypeConversionFailed(
207                        format!("Failed to decompress ZIP entry '{raw_name}': {e}"),
208                    )));
209                    return;
210                }
211
212                if data.len() as u64 > max_per_entry {
213                    let _ = tx.blocking_send(Err(CamelError::TypeConversionFailed(
214                        format!(
215                            "ZIP entry '{raw_name}' size {} exceeds max {}",
216                            data.len(),
217                            max_per_entry
218                        ),
219                    )));
220                    return;
221                }
222
223                let entry_size = data.len() as u64;
224                let prev_total = total_decompressed.load(Ordering::SeqCst);
225                let new_total = prev_total.saturating_add(entry_size);
226                if new_total > max_total {
227                    let _ = tx.blocking_send(Err(CamelError::TypeConversionFailed(
228                        format!("ZIP total decompressed size exceeds max {max_total}"),
229                    )));
230                    return;
231                }
232                total_decompressed.store(new_total, Ordering::SeqCst);
233
234                let count = entry_count.fetch_add(1, Ordering::SeqCst);
235                if count >= max_entries {
236                    let _ = tx.blocking_send(Err(CamelError::TypeConversionFailed(
237                        format!("ZIP exceeds max entries: {max_entries}"),
238                    )));
239                    return;
240                }
241
242                match &dup_policy {
243                    DuplicatePolicy::Reject => {
244                        let mut seen = seen_names.lock().unwrap_or_else(|e| e.into_inner());
245                        if seen.contains_key(&validated) {
246                            let _ = tx.blocking_send(Err(CamelError::TypeConversionFailed(
247                                format!("Duplicate ZIP entry name: {validated}"),
248                            )));
249                            return;
250                        }
251                        seen.insert(validated.clone(), 0);
252                        emitted_names
253                            .lock()
254                            .unwrap_or_else(|e| e.into_inner())
255                            .insert(validated.clone());
256                    }
257                    DuplicatePolicy::AllowWithIndex => {
258                        let mut seen = seen_names.lock().unwrap_or_else(|e| e.into_inner());
259                        let mut emitted_set =
260                            emitted_names.lock().unwrap_or_else(|e| e.into_inner());
261                        let occurrences = seen.entry(validated.clone()).or_insert(0);
262                        let start = if *occurrences > 0 {
263                            *occurrences
264                        } else if emitted_set.contains(&validated) {
265                            1
266                        } else {
267                            0
268                        };
269                        if start > 0 {
270                            // Identical to the TAR splitter: later duplicates
271                            // and literal collisions with already-emitted
272                            // indexed names get a deterministic collision-free
273                            // index inserted before the extension, and the
274                            // suffix grows the name, so the path-length cap
275                            // stays authoritative for indexed names too.
276                            let (candidate, used) =
277                                next_free_indexed_name(&validated, start, &emitted_set);
278                            validated =
279                                match validate_entry_path(&candidate, max_path_len, "ZIP") {
280                                    Ok(p) => p,
281                                    Err(e) => {
282                                        let _ = tx.blocking_send(Err(e));
283                                        return;
284                                    }
285                                };
286                            *occurrences = (*occurrences).max(used + 1);
287                        }
288                        emitted_set.insert(validated.clone());
289                    }
290                }
291
292                if tx
293                    .blocking_send(Ok(ZipEntryData {
294                        index: count,
295                        path: validated,
296                        size: data.len() as u64,
297                        compressed_size,
298                        crc32: Some(crc32),
299                        is_dir: false,
300                        compression: format!("{:?}", entry.compression()),
301                        data,
302                    }))
303                    .is_err()
304                {
305                    return;
306                }
307            }
308        });
309
310        while let Some(result) = rx.recv().await {
311            match result {
312                Ok(entry) => {
313                    let ZipEntryData {
314                        index,
315                        path,
316                        size,
317                        compressed_size,
318                        crc32,
319                        is_dir,
320                        compression,
321                        data,
322                    } = entry;
323                    let body = if is_dir {
324                        Body::Empty
325                    } else {
326                        Body::Bytes(Bytes::from(data))
327                    };
328                    let msg = Message {
329                        headers: parent.input.headers.clone(),
330                        body,
331                    };
332                    let mut ex = Exchange::new(msg);
333                    // Strip parent-level content headers that are stale for individual ZIP entries
334                    ex.input.headers.remove("Content-Length");
335                    ex.input.headers.remove("Content-Type");
336                    ex.properties = parent.properties.clone();
337                    // The entry body is new content, so the parent's
338                    // request-dependent suppression marker must not be inherited.
339                    ex.remove_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED);
340                    ex.pattern = parent.pattern;
341                    ex.otel_context = parent.otel_context.clone();
342
343                    let entry_name = Path::new(&path)
344                        .file_name()
345                        .map(|n| n.to_string_lossy().to_string())
346                        .unwrap_or_default();
347
348                    ex.input.headers.insert(
349                        CAMEL_ZIP_ENTRY_NAME.to_string(),
350                        Value::String(entry_name),
351                    );
352                    ex.input.headers.insert(
353                        CAMEL_ZIP_ENTRY_PATH.to_string(),
354                        Value::String(path),
355                    );
356                    ex.input.headers.insert(
357                        CAMEL_ZIP_ENTRY_INDEX.to_string(),
358                        Value::from(index as u64),
359                    );
360                    ex.input.headers
361                        .insert(CAMEL_ZIP_ENTRY_SIZE.to_string(), Value::from(size));
362                    ex.input.headers.insert(
363                        CAMEL_ZIP_ENTRY_COMPRESSED_SIZE.to_string(),
364                        Value::from(compressed_size),
365                    );
366                    if let Some(crc) = crc32 {
367                        ex.input
368                            .headers
369                            .insert(CAMEL_ZIP_ENTRY_CRC32.to_string(), Value::from(crc));
370                    }
371                    ex.input.headers.insert(
372                        CAMEL_ZIP_ENTRY_IS_DIRECTORY.to_string(),
373                        Value::Bool(is_dir),
374                    );
375                    ex.input.headers.insert(
376                        CAMEL_ZIP_ENTRY_COMPRESSION.to_string(),
377                        Value::String(compression),
378                    );
379
380                    yield Ok(ex);
381                }
382                Err(e) => {
383                    yield Err(e);
384                }
385            }
386        }
387    })
388}
389
390pub fn zip_splitter(config: ZipSplitConfig) -> StreamingSplitExpression {
391    Arc::new(move |exchange: Exchange| {
392        let config = config.clone();
393        match exchange.input.body.clone() {
394            Body::Bytes(b) => split_zip_bytes(exchange, b, config),
395            Body::Text(s) => split_zip_bytes(exchange, Bytes::from(s.as_bytes().to_vec()), config),
396            _ => Box::pin(async_stream::stream! {
397                yield Err(CamelError::TypeConversionFailed(
398                    "ZipSplitter requires Body::Bytes or Body::Text".to_string(),
399                ));
400            }),
401        }
402    })
403}
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408    use crate::archive_splitter::test_util::make_zip_raw;
409    use futures::StreamExt;
410    use std::io::Write;
411
412    fn make_zip_with_files(files: Vec<(&str, &[u8])>) -> Vec<u8> {
413        let mut buf = Vec::new();
414        {
415            let mut writer = zip::ZipWriter::new(std::io::Cursor::new(&mut buf));
416            let options = zip::write::SimpleFileOptions::default()
417                .compression_method(zip::CompressionMethod::Deflated);
418            for (name, content) in &files {
419                writer.start_file(*name, options).unwrap();
420                writer.write_all(content).unwrap();
421            }
422            writer.finish().unwrap();
423        }
424        buf
425    }
426
427    fn make_zip_with_dirs(entries: Vec<(&str, bool)>) -> Vec<u8> {
428        let mut buf = Vec::new();
429        {
430            let mut writer = zip::ZipWriter::new(std::io::Cursor::new(&mut buf));
431            let options = zip::write::SimpleFileOptions::default();
432            for (name, is_dir) in &entries {
433                if *is_dir {
434                    writer.add_directory(*name, options).unwrap();
435                } else {
436                    writer.start_file(name, options).unwrap();
437                    writer.write_all(b"content").unwrap();
438                }
439            }
440            writer.finish().unwrap();
441        }
442        buf
443    }
444
445    async fn collect_entries(
446        config: ZipSplitConfig,
447        zip_data: Vec<u8>,
448    ) -> Vec<Result<Exchange, CamelError>> {
449        let expr = zip_splitter(config);
450        let exchange = Exchange::new(Message {
451            headers: Default::default(),
452            body: Body::Bytes(Bytes::from(zip_data)),
453        });
454        let stream = expr(exchange);
455        stream.collect().await
456    }
457
458    #[tokio::test]
459    async fn test_zip_split_single_file() {
460        let zip_data = make_zip_with_files(vec![("hello.txt", b"hello world")]);
461        let results = collect_entries(ZipSplitConfig::default(), zip_data).await;
462        assert_eq!(results.len(), 1);
463        let ex = results[0].as_ref().unwrap();
464        match &ex.input.body {
465            Body::Bytes(b) => assert_eq!(b.as_ref(), b"hello world"),
466            _ => panic!("expected Body::Bytes"),
467        }
468        assert_eq!(
469            ex.input.headers.get(CAMEL_ZIP_ENTRY_NAME),
470            Some(&Value::String("hello.txt".to_string()))
471        );
472    }
473
474    #[tokio::test]
475    async fn test_zip_split_multiple_files() {
476        let zip_data = make_zip_with_files(vec![("a.txt", b"aaa"), ("b.txt", b"bbb")]);
477        let results = collect_entries(ZipSplitConfig::default(), zip_data).await;
478        assert_eq!(results.len(), 2);
479    }
480
481    #[tokio::test]
482    async fn test_zip_split_with_directories() {
483        let zip_data = make_zip_with_dirs(vec![("subdir/", true), ("subdir/file.txt", false)]);
484        let config = ZipSplitConfig {
485            allow_empty_directories: true,
486            ..Default::default()
487        };
488        let results = collect_entries(config, zip_data).await;
489        assert_eq!(results.len(), 2);
490        let dir_ex = results[0].as_ref().unwrap();
491        assert!(dir_ex.input.body.is_empty());
492        assert_eq!(
493            dir_ex.input.headers.get(CAMEL_ZIP_ENTRY_IS_DIRECTORY),
494            Some(&Value::Bool(true))
495        );
496    }
497
498    #[tokio::test]
499    async fn test_zip_split_preserves_paths() {
500        let zip_data = make_zip_with_files(vec![("deep/nested/path/file.txt", b"deep")]);
501        let results = collect_entries(ZipSplitConfig::default(), zip_data).await;
502        assert_eq!(results.len(), 1);
503        let ex = results[0].as_ref().unwrap();
504        assert_eq!(
505            ex.input.headers.get(CAMEL_ZIP_ENTRY_PATH),
506            Some(&Value::String("deep/nested/path/file.txt".to_string()))
507        );
508    }
509
510    #[tokio::test]
511    async fn test_zip_split_max_entries_exceeded() {
512        let files: Vec<(String, Vec<u8>)> = (0..5)
513            .map(|i| (format!("f{i}.txt"), b"x".to_vec()))
514            .collect();
515        let zip_data = {
516            let mut buf = Vec::new();
517            {
518                let mut writer = zip::ZipWriter::new(std::io::Cursor::new(&mut buf));
519                let options = zip::write::SimpleFileOptions::default();
520                for (name, content) in &files {
521                    writer.start_file(name, options).unwrap();
522                    writer.write_all(content).unwrap();
523                }
524                writer.finish().unwrap();
525            }
526            buf
527        };
528        let config = ZipSplitConfig {
529            max_entries: 3,
530            ..Default::default()
531        };
532        let results = collect_entries(config, zip_data).await;
533        let has_error = results.iter().any(|r| r.is_err());
534        assert!(has_error);
535    }
536
537    #[tokio::test]
538    async fn test_zip_split_path_traversal_rejected() {
539        let mut buf = Vec::new();
540        {
541            let mut writer = zip::ZipWriter::new(std::io::Cursor::new(&mut buf));
542            let options = zip::write::SimpleFileOptions::default();
543            writer.start_file("../etc/passwd", options).unwrap();
544            writer.write_all(b"oops").unwrap();
545            writer.finish().unwrap();
546        }
547        let results = collect_entries(ZipSplitConfig::default(), buf).await;
548        let has_error = results.iter().any(|r| r.is_err());
549        assert!(has_error);
550    }
551
552    #[tokio::test]
553    async fn test_zip_split_headers_set() {
554        let zip_data = make_zip_with_files(vec![("test.txt", b"content")]);
555        let results = collect_entries(ZipSplitConfig::default(), zip_data).await;
556        let ex = results[0].as_ref().unwrap();
557        assert!(ex.input.headers.contains_key(CAMEL_ZIP_ENTRY_NAME));
558        assert!(ex.input.headers.contains_key(CAMEL_ZIP_ENTRY_PATH));
559        assert!(ex.input.headers.contains_key(CAMEL_ZIP_ENTRY_INDEX));
560        assert!(ex.input.headers.contains_key(CAMEL_ZIP_ENTRY_SIZE));
561        assert!(
562            ex.input
563                .headers
564                .contains_key(CAMEL_ZIP_ENTRY_COMPRESSED_SIZE)
565        );
566        assert!(ex.input.headers.contains_key(CAMEL_ZIP_ENTRY_IS_DIRECTORY));
567        assert!(ex.input.headers.contains_key(CAMEL_ZIP_ENTRY_COMPRESSION));
568    }
569
570    #[tokio::test]
571    async fn test_zip_split_empty_zip() {
572        let mut buf = Vec::new();
573        {
574            let writer = zip::ZipWriter::new(std::io::Cursor::new(&mut buf));
575            writer.finish().unwrap();
576        }
577        let results = collect_entries(ZipSplitConfig::default(), buf).await;
578        assert!(results.is_empty());
579    }
580
581    /// Under `Reject`, unique names always pass. True duplicate names never
582    /// reach the splitter — the `zip` reader indexes the central directory by
583    /// name and collapses them — so the reject branch is defense-in-depth
584    /// shared with the TAR splitter (see
585    /// `archive_splitter::indexed_duplicate_name` and the cross-format parity
586    /// test in `tar_splitter`).
587    #[tokio::test]
588    async fn test_zip_split_duplicate_names_reject() {
589        let files: Vec<(&str, &[u8])> = vec![("a.txt", b"first"), ("b.txt", b"second")];
590        let zip_data = make_zip_with_files(files);
591        let config = ZipSplitConfig {
592            duplicate_names_policy: DuplicatePolicy::Reject,
593            ..Default::default()
594        };
595        let results = collect_entries(config, zip_data).await;
596        assert_eq!(results.len(), 2);
597        assert!(results.iter().all(|r| r.is_ok()));
598    }
599    /// Boundary guard: a hand-built ZIP carrying true duplicate names has
600    /// them collapsed by the `zip` reader (first position, last entry's data
601    /// wins) before the splitter sees it, so `AllowWithIndex` observes only
602    /// unique names and never mangles. If a reader upgrade starts surfacing
603    /// duplicates, this test fails and the shared index-mangling branch
604    /// becomes live end-to-end.
605    #[tokio::test]
606    async fn test_zip_split_raw_duplicate_entries_collapse_at_reader() {
607        let zip_data = make_zip_raw(&[
608            ("dup.txt", b"first"),
609            ("other.txt", b"mid"),
610            ("dup.txt", b"second"),
611        ]);
612        let results = collect_entries(ZipSplitConfig::default(), zip_data).await;
613        assert_eq!(
614            results.len(),
615            2,
616            "duplicate names must collapse at the reader: {results:?}"
617        );
618        let first = results[0].as_ref().unwrap();
619        assert_eq!(
620            first.input.headers.get(CAMEL_ZIP_ENTRY_PATH),
621            Some(&Value::String("dup.txt".to_string())),
622            "the first position wins with the surviving name unmangled"
623        );
624        match &first.input.body {
625            Body::Bytes(b) => assert_eq!(b.as_ref(), b"second", "last entry's data wins"),
626            other => panic!("expected Body::Bytes, got {other:?}"),
627        }
628        assert_eq!(
629            results[1]
630                .as_ref()
631                .unwrap()
632                .input
633                .headers
634                .get(CAMEL_ZIP_ENTRY_PATH),
635            Some(&Value::String("other.txt".to_string()))
636        );
637    }
638
639    #[tokio::test]
640    async fn test_zip_split_max_per_entry_size_exceeded() {
641        let zip_data = make_zip_with_files(vec![("big.txt", b"x".repeat(200).as_slice())]);
642        let config = ZipSplitConfig {
643            max_per_entry_size: 100,
644            ..Default::default()
645        };
646        let results = collect_entries(config, zip_data).await;
647        let has_error = results.iter().any(|r| r.is_err());
648        assert!(has_error);
649    }
650
651    #[tokio::test]
652    async fn test_zip_split_max_total_decompressed_size_exceeded() {
653        let zip_data =
654            make_zip_with_files(vec![("a.txt", b"aaaaaaaaaa"), ("b.txt", b"bbbbbbbbbb")]);
655        let config = ZipSplitConfig {
656            max_total_decompressed_size: 15,
657            ..Default::default()
658        };
659        let results = collect_entries(config, zip_data).await;
660        let has_error = results.iter().any(|r| r.is_err());
661        assert!(has_error);
662    }
663
664    #[tokio::test]
665    async fn test_zip_split_corrupt_zip() {
666        let results = collect_entries(ZipSplitConfig::default(), b"not a zip file".to_vec()).await;
667        let has_error = results.iter().any(|r| r.is_err());
668        assert!(has_error);
669    }
670
671    #[tokio::test]
672    async fn test_zip_split_backslash_rejected() {
673        let mut buf = Vec::new();
674        {
675            let mut writer = zip::ZipWriter::new(std::io::Cursor::new(&mut buf));
676            let options = zip::write::SimpleFileOptions::default();
677            writer.start_file("sub\\file.txt", options).unwrap();
678            writer.write_all(b"oops").unwrap();
679            writer.finish().unwrap();
680        }
681        let results = collect_entries(ZipSplitConfig::default(), buf).await;
682        let has_error = results.iter().any(|r| r.is_err());
683        assert!(has_error);
684    }
685
686    /// Regression guard for the shared-validator extraction: safe names are
687    /// accepted and unsafe names are rejected with the exact pre-refactor
688    /// ZIP error text.
689    #[tokio::test]
690    async fn zip_path_validation_behavior_is_unchanged() {
691        // Safe relative name is accepted with its path preserved.
692        let safe = collect_entries(
693            ZipSplitConfig::default(),
694            make_zip_with_files(vec![("docs/readme.txt", b"ok")]),
695        )
696        .await;
697        assert_eq!(safe.len(), 1);
698        let ex = safe[0].as_ref().unwrap();
699        assert_eq!(
700            ex.input.headers.get(CAMEL_ZIP_ENTRY_PATH),
701            Some(&Value::String("docs/readme.txt".to_string()))
702        );
703
704        // Absolute and traversal names are rejected with identical error text.
705        let cases = [
706            ("/etc/passwd", "ZIP entry path is absolute: /etc/passwd"),
707            (
708                "../etc/passwd",
709                "ZIP entry path contains '..' traversal: ../etc/passwd",
710            ),
711        ];
712        for (name, expected) in cases {
713            let results = collect_entries(
714                ZipSplitConfig::default(),
715                make_zip_with_files(vec![(name, b"oops")]),
716            )
717            .await;
718            assert_eq!(
719                results.len(),
720                1,
721                "expected exactly the validation error for {name}"
722            );
723            let err = results[0]
724                .as_ref()
725                .expect_err(&format!("'{name}' must be rejected"))
726                .to_string();
727            assert!(
728                err.contains(expected),
729                "error text mismatch for {name}: {err}"
730            );
731        }
732    }
733
734    #[tokio::test]
735    async fn zip_fragment_clears_marker() {
736        let zip_data = make_zip_with_files(vec![("hello.txt", b"hello world")]);
737        let mut parent = Exchange::new(Message {
738            headers: Default::default(),
739            body: Body::Bytes(Bytes::from(zip_data)),
740        });
741        parent.set_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED, Value::Bool(true));
742        parent.input.headers.insert(
743            "Content-Type".to_string(),
744            Value::String("application/zip".into()),
745        );
746        assert_eq!(
747            parent.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
748            Some(&Value::Bool(true)),
749            "parent must start with the marker armed"
750        );
751
752        let results = zip_splitter(ZipSplitConfig::default())(parent)
753            .collect::<Vec<_>>()
754            .await;
755
756        assert_eq!(results.len(), 1);
757        let fragment = results[0].as_ref().expect("entry fragment ok");
758        assert_eq!(
759            fragment.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
760            None,
761            "the entry fragment must clear the inherited suppression marker"
762        );
763    }
764}