Skip to main content

camel_processor/
tar_splitter.rs

1//! TAR and TAR.GZ stream splitters: metadata constants, bounded
2//! configuration, and the TAR-specific error surface.
3//!
4//! Splitting itself (bounded sequential TAR reading over materialized bytes)
5//! is layered on this contract. Entry names are validated through the shared
6//! archive path validator, so TAR and ZIP reject the same unsafe shapes with
7//! format-prefixed error text. TAR.GZ runs the same reader over the output
8//! of the bounded single-member GZIP decoder shared with
9//! `GzipDataFormat`; concatenated multi-member GZIP input is rejected
10//! instead of silently split.
11
12use 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/// Bounded configuration for TAR and TAR.GZ stream splitting.
46///
47/// Unknown keys are rejected (`deny_unknown_fields`) and every cap has an
48/// explicit default mirroring the ZIP splitter, so deserialized
49/// configurations are always fully bounded.
50#[derive(Clone, Debug, Deserialize)]
51#[serde(deny_unknown_fields, default)]
52pub struct TarSplitConfig {
53    /// Maximum number of emitted entries before the split fails.
54    pub max_entries: usize,
55    /// Maximum aggregate decoded bytes across all regular-entry payloads.
56    /// TAR framing (headers and padding) is not counted against this cap;
57    /// on TAR.GZ the decode step is bounded separately by this cap plus a
58    /// framing allowance derived from `max_entries`.
59    pub max_total_decoded_size: u64,
60    /// Maximum decoded size of a single entry.
61    pub max_per_entry_size: u64,
62    /// Maximum compressed input size accepted before decoding (TAR.GZ).
63    pub max_compressed_size: u64,
64    /// Maximum validated entry path length.
65    pub max_path_length: usize,
66    /// Duplicate entry-name policy from the shared archive vocabulary:
67    /// `Reject` fails the split on the first duplicate, `AllowWithIndex`
68    /// emits deterministic collision-free indexed names. TAR applies this
69    /// policy directly; ZIP's reader-level duplicate collapse is pinned
70    /// historical behavior, not a parity target.
71    pub duplicate_names_policy: DuplicatePolicy,
72    /// Accept archives that contain zero regular-file entries.
73    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
90/// Validate a TAR entry name against the shared archive path rules
91/// (length, NUL, absolute paths, traversal, backslash, drive prefix) with
92/// TAR-prefixed error text.
93fn validate_tar_entry_path(name: &str, max_length: usize) -> Result<String, CamelError> {
94    validate_entry_path(name, max_length, "TAR")
95}
96
97/// Malformed archive (bad header, truncated stream, checksum mismatch).
98fn err_malformed_archive(detail: &str) -> CamelError {
99    CamelError::TypeConversionFailed(format!("Invalid TAR archive: {detail}"))
100}
101
102/// Duplicate entry name under [`DuplicatePolicy::Reject`].
103fn err_duplicate_entry_name(name: &str) -> CamelError {
104    CamelError::TypeConversionFailed(format!("Duplicate TAR entry name: {name}"))
105}
106
107/// Entry-count cap violation.
108fn err_max_entries(limit: usize) -> CamelError {
109    CamelError::TypeConversionFailed(format!("TAR exceeds max entries: {limit}"))
110}
111
112/// Per-entry decoded-size cap violation.
113fn 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
119/// Aggregate decoded-size cap violation.
120fn err_total_decoded_exceeded(limit: u64) -> CamelError {
121    CamelError::TypeConversionFailed(format!("TAR total decoded size exceeds max {limit}"))
122}
123
124/// Decoded-archive budget violation (TAR.GZ): the decompressed TAR stream
125/// (payloads plus framing) exceeded the derived decode bound, so it cannot
126/// be a payload-cap-respecting archive.
127fn 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
133/// Absolute fail-closed ceiling for the entry-count-derived part of the
134/// TAR.GZ framing allowance. Without it, a huge `max_entries` would
135/// saturate the allowance (and the budget) to `u64::MAX`, reopening an
136/// unbounded decode. 64 MiB is generous for realistic PAX/GNU archives:
137/// a default-cap archive (10,000 entries, each carrying a maximum-length
138/// 4,096-byte name through a GNU longname or PAX extension block) needs
139/// ~58.6 MiB of framing and still fits under the ceiling.
140const MAX_TAR_FRAMING_ALLOWANCE: u64 = 64 * 1024 * 1024;
141
142/// Constant base of the TAR.GZ framing allowance: the two end-of-archive
143/// blocks, a PAX global ('g') header block, and slack. Per-entry
144/// extension-block framing is covered by the per-entry term below.
145const BASE_TAR_FRAMING_ALLOWANCE: u64 = 64 * 1024;
146
147/// TAR block size in bytes.
148const TAR_BLOCK_SIZE: u64 = 512;
149
150/// Worst-case legit framing bytes per regular entry, derived from the
151/// validated path cap (`max_path_length`):
152///
153/// - entry header block: 512
154/// - GNU longname ('L') or PAX ('x') extension header block: 512 (tar
155///   emits at most one of the two per entry)
156/// - extension data block: the recorded path (bounded by the path cap,
157///   plus record overhead — the `path=` key, length digits, and NUL),
158///   padded to the 512-byte block boundary
159/// - payload padding: up to 511 bytes
160///
161/// With the default 4,096-byte path cap this is
162/// 512 + 512 + 4,608 + 511 = 6,143 bytes (~6 KiB) per entry.
163fn 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
168/// Decode bound for a TAR.GZ stream whose entry payloads must stay within
169/// `max_total_decoded_size`: the payload cap plus a dual-bounded TAR
170/// framing allowance — `min(max_entries x per-entry framing, ceiling) +
171/// base`. The per-entry term is sized from the validated path cap so a
172/// maximum-length-name archive is never falsely rejected; the ceiling
173/// keeps the allowance fail closed under absurd entry caps; the base
174/// covers end-of-archive and global-header blocks that are not
175/// proportional to the entry count. Payload accounting stays
176/// authoritative in the parse; this bound only keeps the inflate itself
177/// bounded.
178///
179/// Saturating arithmetic is contract, not accident: the budget derives
180/// from the operator's payload cap, so a `max_total_decoded_size` of
181/// `u64::MAX` is the operator explicitly opting out of decode bounding.
182/// The derived framing term is always finite under its ceiling, so only
183/// the operator-declared cap can saturate the sum; `checked_add` would
184/// not change that contract, only rename the opt-out.
185fn 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
192/// Compressed-input cap violation (TAR.GZ), checked before decoding.
193fn err_compressed_input_exceeded(size: u64, limit: u64) -> CamelError {
194    CamelError::TypeConversionFailed(format!("TAR compressed size {size} exceeds max {limit}"))
195}
196
197/// A concatenated multi-member GZIP stream, which TAR.GZ splitting does not
198/// support in v1.
199fn 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
207/// Zero regular-file entries while `allow_empty_archive` is false.
208fn 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
216/// One emitted regular-file TAR entry, carried from the blocking reader
217/// thread to the fragment-exchange builder.
218struct TarEntryData {
219    index: usize,
220    path: String,
221    size: u64,
222    data: Vec<u8>,
223}
224
225/// Split a TAR archive's materialized bytes into a stream of Exchanges, one
226/// per regular-file entry in header order.
227///
228/// Takes owned `Bytes` (for `'static` lifetime), a parent `Exchange` whose
229/// headers and properties are cloned into each entry's exchange, and a
230/// `TarSplitConfig` controlling limits and policy. Entries are read
231/// sequentially from the in-memory archive: names are validated before any
232/// body is read, directories/symlinks/hard links/devices are skipped (link
233/// targets are never read), and each regular body is materialized through a
234/// bounded `take(max_per_entry_size + 1)` read so an oversized entry is
235/// rejected before its bytes are retained.
236pub 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        // Compressed-input cap: applies to the materialized input bytes
243        // before any entry is decoded.
244        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
259/// Split a single-member TAR.GZ stream into a stream of Exchanges, one per
260/// regular-file entry in header order.
261///
262/// The compressed-input cap is checked before decompression is accepted, the
263/// input is then decoded through the bounded single-member GZIP decoder
264/// shared with `GzipDataFormat`. The decode budget is the payload cap
265/// (`max_total_decoded_size`) plus a bounded TAR framing allowance, so the
266/// inflate is bounded without counting framing against the payload cap; the
267/// resulting TAR bytes run through the same bounded entry reader as plain
268/// TAR splitting, which enforces the payload accounting authoritatively. A
269/// concatenated multi-member GZIP stream is rejected instead of silently
270/// splitting only the first member.
271pub 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        // Compressed-input cap: enforced on the compressed bytes before any
278        // decompression is accepted.
279        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        // Bounded single-member GZIP decode, run on the blocking pool so the
288        // inflate never executes on the async runtime. The decompressed TAR
289        // stream is budgeted from the payload cap plus the TAR framing
290        // allowance; entry-level caps and payload accounting are still
291        // enforced during the parse. If the fragment stream is dropped
292        // before the decode finishes, the detached blocking task still
293        // terminates on its own: the input is fully materialized and the
294        // decode is capped at `take_limit` bytes.
295        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        // `take_limit` is one past the budget, so a full buffer means the
319        // decompressed stream exceeded the budget (a framing-heavy
320        // decompression bomb that would never satisfy the payload cap).
321        if first.data.len() as u64 >= take_limit {
322            yield Err(err_decoded_archive_budget(decode_budget));
323            return;
324        }
325
326        // v1 TAR.GZ is single-member: trailing input past the first member is
327        // rejected rather than silently split.
328        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
340/// Sequential bounded TAR parse over materialized (already decompressed)
341/// bytes. Runs the reader on a blocking thread and drains the bounded
342/// channel into the fragment stream; callers own any input-level cap checks.
343fn 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        // The `tar` reader state is not `Send`, so the sequential parse runs
361        // on a blocking thread, keeping blocking reads off the async runtime.
362        // The bounded channel backpressures the reader; dropping the stream
363        // drops the receiver, so `blocking_send` fails and the task exits.
364        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                // Validate the entry name before any body use; the name is
389                // never handed to the filesystem.
390                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                // Skip directories, symlinks, hard links, and device nodes;
414                // link targets are never read and nothing touches the
415                // filesystem.
416                if !matches!(entry.header().entry_type(), tar::EntryType::Regular) {
417                    continue;
418                }
419
420                // Bounded read: one extra byte detects overflow before the
421                // body is retained.
422                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                    // Report the header-declared size: the bounded read only
433                    // pulled through max + 1 bytes before rejecting.
434                    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                        // The occurrence counter alone cannot guarantee
466                        // uniqueness: a literal entry can occupy an indexed
467                        // name first (a.txt, a.1.txt, a.txt would derive
468                        // a.1.txt twice), so the emitted-name set is the
469                        // authority and the index bumps until the candidate
470                        // is free.
471                        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                            // The suffix grows the name, so the path-length
484                            // cap stays authoritative for indexed names too.
485                            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                    // Strip parent-level content headers that are stale for
532                    // individual TAR entries.
533                    ex.input.headers.remove("Content-Length");
534                    ex.input.headers.remove("Content-Type");
535                    ex.properties = parent.properties.clone();
536                    // The entry body is new content, so the parent's
537                    // request-dependent suppression marker must not be inherited.
538                    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
576/// Build a [`StreamingSplitExpression`] that splits TAR archive bodies into
577/// per-entry Exchanges.
578pub 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
593/// Build a [`StreamingSplitExpression`] that splits single-member TAR.GZ
594/// bodies into per-entry Exchanges after bounded GZIP decoding.
595pub 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    /// Build one 512-byte TAR header block with a valid checksum.
620    ///
621    /// Hand-rolled so tests can create entry shapes the `tar` writer refuses
622    /// to produce (absolute names, traversal names, device nodes).
623    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        // Checksum field must be spaces while the checksum is computed.
628        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    /// Assemble headers, padded data blocks, and the two-block end marker
638    /// into a complete TAR archive.
639    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        // Known keys deserialize; missing keys fall back to the bounded defaults.
671        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        // Unknown keys fail closed instead of being ignored.
680        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        // Header order: file, dir, symlink, hard link, char device, file.
691        // Only the two regular files may surface as fragments.
692        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        // Entry-count cap: three regular entries against max_entries: 2.
775        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        // Per-entry cap: one 200-byte entry against max_per_entry_size: 100.
793        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        // Total-decoded cap: two 10-byte entries against max 15.
810        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        // Compressed-input cap: the materialized input itself against max 512.
827        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        // Path-length cap: a 26-character name against max_path_length: 10.
844        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    /// Compress raw bytes into a single-member GZIP stream for TAR.GZ setups.
889    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    /// TAR applies the shared archive duplicate-name policy directly
955    /// (per the narrowed spec this is TAR's own contract, not ZIP
956    /// parity): `Reject` fails on the first duplicate; `AllowWithIndex`
957    /// emits every entry with a deterministic indexed name for later
958    /// duplicates.
959    #[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        // Reject policy: the split fails on the first duplicate name.
968        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        // AllowWithIndex: every entry is emitted and the later duplicate gets
981        // a deterministic index inserted before its extension.
982        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    /// `DuplicatePolicy` ownership, per the narrowed spec: TAR applies the
1038    /// shared archive duplicate-name vocabulary (`Reject` fails the split;
1039    /// `AllowWithIndex` emits deterministic collision-free indexed names via
1040    /// the shared [`crate::archive_splitter::indexed_duplicate_name`] /
1041    /// [`crate::archive_splitter::next_free_indexed_name`] helpers). ZIP's
1042    /// historical behavior is pinned, not claimed as parity: the `zip`
1043    /// reader indexes the central directory by name, so duplicate entries
1044    /// collapse (last data wins) before the splitter observes them. That
1045    /// boundary is pinned here so a reader change that starts surfacing
1046    /// duplicates forces the ZIP mangling/reject branches (shared with TAR)
1047    /// to be revisited instead of silently changing behavior. ZIP runtime
1048    /// behavior is unchanged by this change.
1049    #[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        // AllowWithIndex on TAR: every entry is emitted and the later
1061        // duplicate carries the shared deterministic indexed suffix.
1062        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        // AllowWithIndex on ZIP over the same logical entries: the reader
1078        // collapses the duplicates, so exactly one unmangled fragment with
1079        // the surviving (last) body is observable.
1080        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        // Reject on TAR: the split fails on the first duplicate name.
1104        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        // Reject on ZIP over the same logical entries: with duplicates
1119        // collapsed away the names are unique, so the split succeeds — the
1120        // reject branch stays reserved for a reader that surfaces them.
1121        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    /// `max_total_decoded_size` is a payload-byte cap. TAR framing
1179    /// (512-byte headers, padding, end-of-archive blocks) must not count
1180    /// against it on TAR.GZ: the decode step is bounded by the payload cap
1181    /// plus a framing allowance derived from `max_entries`, and the parse
1182    /// enforces the payload accounting authoritatively.
1183    #[tokio::test]
1184    async fn tar_gz_total_decoded_cap_counts_payload_not_framing() {
1185        // Three tiny entries: payload total (30 bytes) well under the
1186        // 64-byte cap, decoded stream (~4 KiB with framing) well over it.
1187        // A framing-inclusive decode gate would reject this archive.
1188        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        // A payload that itself exceeds the cap still fails, at the parse,
1212        // with the payload-cap error.
1213        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    /// The entry-count term of the framing allowance must be ceilinged,
1235    /// not saturating: an absurd `max_entries` must not inflate the decode
1236    /// budget toward `u64::MAX` (fail-open decode bomb).
1237    #[test]
1238    fn tar_gz_decode_budget_is_fail_closed_under_absurd_entry_caps() {
1239        // Per-entry derivation at the default path cap: 512 (header)
1240        // + 512 (extension header) + 4,608 (padded extension data for a
1241        // 4,096-byte name) + 511 (payload padding) = 6,143.
1242        assert_eq!(tar_per_entry_framing(4096), 6143);
1243        // Default config: 10,000 entries x 6,143 (~58.6 MiB) stays under
1244        // the 64 MiB ceiling, so the ceiling does not bite by default.
1245        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    /// GNU longname ('L') and PAX ('x') extension blocks are physical
1265    /// stream framing without being separate entries: the constant base
1266    /// of the framing allowance must keep single-entry long-name archives
1267    /// inside the decode budget instead of falsely rejecting them.
1268    #[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        // GNU: `append_data` emits a 'L' longname extension block before
1274        // the real header when the path does not fit the name field.
1275        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        // PAX: a hand-crafted 'x' extended header whose record overrides
1286        // the short header name of the following entry.
1287        let pax_record = {
1288            let body = format!(" path={long_path}\n");
1289            // The record's declared length includes its own digits.
1290            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                    // Tight payload cap: 10 payload bytes plus margin, so
1306                    // only the allowance keeps the decode accepted.
1307                    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    /// The occurrence counter alone cannot guarantee unique emitted names:
1326    /// `a.txt`, `a.1.txt`, `a.txt` would derive `a.1.txt` twice. The
1327    /// emitted-name set is the collision authority and the index bumps
1328    /// until the candidate is free.
1329    #[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        // Reverse order: a literal name colliding with an already-emitted
1359        // indexed name is itself re-indexed, keeping every emitted name
1360        // unique.
1361        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}