Skip to main content

exarch_core/security/
quota.rs

1//! Extraction quota tracking and validation.
2
3use std::marker::PhantomData;
4use std::num::NonZeroU64;
5
6use crate::ArchiveError;
7use crate::Limit;
8use crate::Result;
9use crate::SecurityConfig;
10use crate::security::zipbomb::Uncompressed;
11
12/// Proof that a file's size was successfully reserved against a
13/// `QuotaTracker`.
14///
15/// This is a capability token that records the byte count it reserved, so the
16/// write cap is read from the permit and cannot be re-supplied by a caller
17/// that reserved one quantity and enforces another (GHSA-5j8q). Its only
18/// producers are `QuotaTracker::reserve` and the crate-private
19/// `QuotaTracker::charge` — the private field means no other code, in or out of
20/// this crate, can assemble one directly. The extraction pipeline reserves one
21/// when it admits a file, and spends it into an [`AdmittedSize`] for the
22/// sink; hardlinks charge theirs in a second pass, after [`EntryCount`]
23/// counted them in the first.
24///
25/// Deliberately not `Clone`/`Copy`/`Default`: a permit represents a single
26/// reservation and must not be duplicated or spent more than once.
27#[derive(Debug)]
28#[must_use]
29pub struct QuotaPermit {
30    bytes: Uncompressed,
31}
32
33impl QuotaPermit {
34    const fn new(bytes: u64) -> Self {
35        Self {
36            bytes: Uncompressed(bytes),
37        }
38    }
39
40    /// Spends the permit, yielding the byte count it reserved, which is also
41    /// the write ceiling.
42    pub(crate) const fn into_bytes(self) -> u64 {
43        self.bytes.0
44    }
45
46    /// Spends the permit, yielding a copyable view of the bytes it reserved
47    /// for a sink to read.
48    pub(crate) const fn into_admitted(self) -> AdmittedSize {
49        AdmittedSize(self.bytes.0)
50    }
51}
52
53/// The size of a file the pipeline admitted: the bytes a [`QuotaPermit`]
54/// reserved for it.
55///
56/// A read-only, copyable view handed to an [`EntrySink`](crate::EntrySink) so
57/// it can tell a size the quota tracker already charged from any other number.
58/// Only the pipeline can build one: the field is private and the sole
59/// constructor spends a permit.
60///
61/// # Examples
62///
63/// ```
64/// use exarch_core::AdmittedSize;
65///
66/// fn capacity_hint(size: AdmittedSize) -> usize {
67///     usize::try_from(size.get().min(1 << 16)).unwrap_or(0)
68/// }
69/// # let _ = capacity_hint;
70/// ```
71#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
72pub struct AdmittedSize(u64);
73
74impl AdmittedSize {
75    /// The admitted size in bytes.
76    #[must_use]
77    pub const fn get(self) -> u64 {
78        self.0
79    }
80}
81
82/// Proof that one entry was counted against `max_file_count` while its bytes
83/// are not yet charged.
84///
85/// A hardlink's size is only known in the second extraction pass, but the
86/// number of entries must be bounded in the first, before anything is
87/// buffered or copied. The first pass takes an `EntryCount`; the second spends
88/// it in `QuotaTracker::charge`, which adds the bytes without counting the
89/// entry again. Holding one therefore makes counting an entry twice, or never,
90/// unrepresentable.
91///
92/// Deliberately not `Clone`/`Copy`/`Default`, and only producible by
93/// `QuotaTracker::reserve_count`. Zero-sized.
94#[derive(Debug)]
95#[must_use]
96pub struct EntryCount(PhantomData<()>);
97
98/// Tracks resource usage during extraction.
99#[derive(Debug, Default)]
100pub struct QuotaTracker {
101    files_extracted: usize,
102    bytes_written: u64,
103}
104
105fn check_file_size(size: u64, max: Limit<NonZeroU64>) -> Result<()> {
106    if !max.admits(size) {
107        core::hint::cold_path();
108        return Err(ArchiveError::QuotaExceeded {
109            resource: crate::QuotaResource::FileSize {
110                size,
111                max: max.ceiling(),
112            },
113        });
114    }
115    Ok(())
116}
117
118impl QuotaTracker {
119    /// Creates a new quota tracker.
120    #[must_use]
121    pub fn new() -> Self {
122        Self::default()
123    }
124
125    /// Reserves quota capacity for a file extraction, returning a capability
126    /// token that proves the reservation succeeded.
127    ///
128    /// # Errors
129    ///
130    /// Returns an error if quotas are exceeded or integer overflow is detected.
131    ///
132    /// # Performance
133    ///
134    /// OPT-C003: Fast path for unlimited quotas reduces overhead by 3-5%.
135    /// When all quotas are set to maximum values (unlimited), the function
136    /// skips quota checks and only tracks counters with overflow detection.
137    #[inline]
138    pub fn reserve(&mut self, size: u64, config: &SecurityConfig) -> Result<QuotaPermit> {
139        self.reserve_within(size, config.max_file_size, config)
140    }
141
142    /// Counts one entry against `max_file_count` without charging any bytes,
143    /// returning the token [`charge`](Self::charge) later spends.
144    ///
145    /// # Errors
146    ///
147    /// Returns [`ArchiveError::QuotaExceeded`] if the file count limit is
148    /// exceeded or the counter overflows.
149    pub(crate) fn reserve_count(&mut self, config: &SecurityConfig) -> Result<EntryCount> {
150        self.bump_files()?;
151        self.check_file_count(config)?;
152
153        Ok(EntryCount(PhantomData))
154    }
155
156    /// Charges `size` bytes for an entry already counted by
157    /// [`reserve_count`](Self::reserve_count), without counting it again.
158    ///
159    /// # Errors
160    ///
161    /// Returns [`ArchiveError::QuotaExceeded`] if `size` exceeds
162    /// `max_file_size`, the running total exceeds `max_total_size`, or the
163    /// byte counter overflows.
164    pub(crate) fn charge(
165        &mut self,
166        count: EntryCount,
167        size: u64,
168        config: &SecurityConfig,
169    ) -> Result<QuotaPermit> {
170        drop(count);
171
172        check_file_size(size, config.max_file_size)?;
173        self.add_bytes(size)?;
174        self.check_total_size(config)?;
175
176        Ok(QuotaPermit::new(size))
177    }
178
179    /// Reserves quota capacity without enforcing the per-file size limit.
180    ///
181    /// For `verify`'s listing pre-flight only, which must see oversized
182    /// entries so `verify_entry` can report them. The file count and total
183    /// size limits still apply; extraction must use [`reserve`](Self::reserve).
184    ///
185    /// # Errors
186    ///
187    /// Returns an error if the file count or total size quota is exceeded or
188    /// integer overflow is detected.
189    pub(crate) fn reserve_without_file_limit(
190        &mut self,
191        size: u64,
192        config: &SecurityConfig,
193    ) -> Result<QuotaPermit> {
194        self.reserve_within(size, Limit::Unbounded, config)
195    }
196
197    #[inline]
198    fn reserve_within(
199        &mut self,
200        size: u64,
201        max_file_size: Limit<NonZeroU64>,
202        config: &SecurityConfig,
203    ) -> Result<QuotaPermit> {
204        // OPT-C003: Fast path when all quotas unlimited - skip checks, only
205        // detect overflow
206        if max_file_size == Limit::Unbounded
207            && config.max_file_count == Limit::Unbounded
208            && config.max_total_size == Limit::Unbounded
209        {
210            self.files_extracted = self.files_extracted.checked_add(1).ok_or_else(|| {
211                core::hint::cold_path();
212                ArchiveError::QuotaExceeded {
213                    resource: crate::QuotaResource::IntegerOverflow,
214                }
215            })?;
216
217            self.bytes_written = self.bytes_written.checked_add(size).ok_or_else(|| {
218                core::hint::cold_path();
219                ArchiveError::QuotaExceeded {
220                    resource: crate::QuotaResource::IntegerOverflow,
221                }
222            })?;
223
224            return Ok(QuotaPermit::new(size));
225        }
226
227        self.record_file_checked(size, max_file_size, config)?;
228        Ok(QuotaPermit::new(size))
229    }
230
231    /// Internal implementation with full quota validation.
232    ///
233    /// This is the slow path called when quotas are actually enforced.
234    /// Separated from the fast path to keep the hot path small and inlinable.
235    #[inline(never)]
236    fn record_file_checked(
237        &mut self,
238        size: u64,
239        max_file_size: Limit<NonZeroU64>,
240        config: &SecurityConfig,
241    ) -> Result<()> {
242        check_file_size(size, max_file_size)?;
243        self.bump_files()?;
244        self.add_bytes(size)?;
245        self.check_file_count(config)?;
246        self.check_total_size(config)
247    }
248
249    fn bump_files(&mut self) -> Result<()> {
250        self.files_extracted = self.files_extracted.checked_add(1).ok_or_else(|| {
251            core::hint::cold_path();
252            ArchiveError::QuotaExceeded {
253                resource: crate::QuotaResource::IntegerOverflow,
254            }
255        })?;
256        Ok(())
257    }
258
259    fn add_bytes(&mut self, size: u64) -> Result<()> {
260        self.bytes_written = self.bytes_written.checked_add(size).ok_or_else(|| {
261            core::hint::cold_path();
262            ArchiveError::QuotaExceeded {
263                resource: crate::QuotaResource::IntegerOverflow,
264            }
265        })?;
266        Ok(())
267    }
268
269    fn check_file_count(&self, config: &SecurityConfig) -> Result<()> {
270        if !config.max_file_count.admits(self.files_extracted) {
271            core::hint::cold_path();
272            return Err(ArchiveError::QuotaExceeded {
273                resource: crate::QuotaResource::FileCount {
274                    current: self.files_extracted,
275                    max: config.max_file_count.ceiling(),
276                },
277            });
278        }
279        Ok(())
280    }
281
282    fn check_total_size(&self, config: &SecurityConfig) -> Result<()> {
283        if !config.max_total_size.admits(self.bytes_written) {
284            core::hint::cold_path();
285            return Err(ArchiveError::QuotaExceeded {
286                resource: crate::QuotaResource::TotalSize {
287                    current: self.bytes_written,
288                    max: config.max_total_size.ceiling(),
289                },
290            });
291        }
292        Ok(())
293    }
294
295    /// Returns the number of files extracted.
296    #[cfg(any(test, feature = "testing"))]
297    #[must_use]
298    pub fn files_extracted(&self) -> usize {
299        self.files_extracted
300    }
301
302    /// Returns the total bytes written.
303    #[cfg(any(test, feature = "testing"))]
304    #[must_use]
305    pub fn bytes_written(&self) -> u64 {
306        self.bytes_written
307    }
308}
309
310#[cfg(test)]
311#[allow(clippy::field_reassign_with_default, clippy::expect_used)]
312mod tests {
313    use super::*;
314    use std::assert_matches;
315
316    #[test]
317    fn test_quota_tracker_new() {
318        let tracker = QuotaTracker::new();
319        assert_eq!(tracker.files_extracted(), 0);
320        assert_eq!(tracker.bytes_written(), 0);
321    }
322
323    #[test]
324    fn permit_carries_the_reserved_size() {
325        let mut tracker = QuotaTracker::new();
326        let config = SecurityConfig::default();
327
328        let permit = tracker.reserve(1234, &config).expect("within quota");
329
330        assert_eq!(permit.into_bytes(), 1234);
331    }
332
333    #[test]
334    fn test_quota_tracker_reserve() {
335        let mut tracker = QuotaTracker::new();
336        let config = SecurityConfig::default();
337
338        assert!(tracker.reserve(1000, &config).is_ok());
339        assert_eq!(tracker.files_extracted(), 1);
340        assert_eq!(tracker.bytes_written(), 1000);
341    }
342
343    #[test]
344    fn test_quota_tracker_exceed_file_count() {
345        let mut tracker = QuotaTracker::new();
346        let mut config = SecurityConfig::default();
347        config.max_file_count = crate::Limit::Bounded(crate::non_zero!(2));
348
349        assert!(tracker.reserve(100, &config).is_ok());
350        assert!(tracker.reserve(100, &config).is_ok());
351        let result = tracker.reserve(100, &config);
352        assert_matches!(result, Err(ArchiveError::QuotaExceeded { .. }));
353    }
354
355    #[test]
356    fn test_quota_tracker_exceed_total_size() {
357        let mut tracker = QuotaTracker::new();
358        let mut config = SecurityConfig::default();
359        config.max_total_size = crate::Limit::Bounded(crate::non_zero!(1000));
360
361        assert!(tracker.reserve(600, &config).is_ok());
362        let result = tracker.reserve(500, &config);
363        assert_matches!(result, Err(ArchiveError::QuotaExceeded { .. }));
364    }
365
366    #[test]
367    fn test_quota_tracker_exceed_file_size() {
368        let mut tracker = QuotaTracker::new();
369        let mut config = SecurityConfig::default();
370        config.max_file_size = crate::Limit::Bounded(crate::non_zero!(1000));
371
372        let result = tracker.reserve(2000, &config);
373        assert_matches!(result, Err(ArchiveError::QuotaExceeded { .. }));
374    }
375
376    // H-TEST-4: Quota boundary conditions test
377    #[test]
378    fn test_quota_exactly_at_file_count_limit() {
379        let mut tracker = QuotaTracker::new();
380        let mut config = SecurityConfig::default();
381        config.max_file_count = crate::Limit::Bounded(crate::non_zero!(3));
382        config.max_total_size = crate::Limit::Unbounded;
383        config.max_file_size = crate::Limit::Unbounded;
384
385        // Exactly at file count limit should succeed
386        assert!(
387            tracker.reserve(100, &config).is_ok(),
388            "file 1 should succeed"
389        );
390        assert!(
391            tracker.reserve(100, &config).is_ok(),
392            "file 2 should succeed"
393        );
394        assert!(
395            tracker.reserve(100, &config).is_ok(),
396            "file 3 should succeed"
397        );
398        assert_eq!(tracker.files_extracted(), 3, "should have 3 files");
399
400        // One more should fail (exceeds limit)
401        let result = tracker.reserve(100, &config);
402        assert_matches!(
403            result,
404            Err(ArchiveError::QuotaExceeded {
405                resource: crate::QuotaResource::FileCount { current: 4, max: 3 }
406            }),
407            "file 4 should exceed quota"
408        );
409    }
410
411    #[test]
412    fn test_quota_exactly_at_total_size_limit() {
413        let mut tracker = QuotaTracker::new();
414        let mut config = SecurityConfig::default();
415        config.max_file_count = crate::Limit::Bounded(crate::non_zero!(100));
416        config.max_total_size = crate::Limit::Bounded(crate::non_zero!(1000));
417        config.max_file_size = crate::Limit::Unbounded;
418
419        // Add files up to exactly the limit
420        assert!(tracker.reserve(600, &config).is_ok());
421        assert_eq!(tracker.bytes_written(), 600);
422
423        assert!(tracker.reserve(400, &config).is_ok());
424        assert_eq!(tracker.bytes_written(), 1000, "should be exactly at limit");
425
426        // One more byte should fail
427        let result = tracker.reserve(1, &config);
428        assert_matches!(
429            result,
430            Err(ArchiveError::QuotaExceeded {
431                resource: crate::QuotaResource::TotalSize {
432                    current: 1001,
433                    max: 1000
434                }
435            }),
436            "exceeding total size should fail"
437        );
438    }
439
440    #[test]
441    fn test_quota_exactly_at_file_size_limit() {
442        let mut tracker = QuotaTracker::new();
443        let mut config = SecurityConfig::default();
444        config.max_file_count = crate::Limit::Bounded(crate::non_zero!(100));
445        config.max_total_size = crate::Limit::Unbounded;
446        config.max_file_size = crate::Limit::Bounded(crate::non_zero!(5000));
447
448        // File exactly at limit should succeed
449        assert!(
450            tracker.reserve(5000, &config).is_ok(),
451            "file exactly at limit should succeed"
452        );
453
454        // File one byte over should fail
455        let result = tracker.reserve(5001, &config);
456        assert_matches!(
457            result,
458            Err(ArchiveError::QuotaExceeded {
459                resource: crate::QuotaResource::FileSize {
460                    size: 5001,
461                    max: 5000
462                }
463            }),
464            "file exceeding limit should fail"
465        );
466    }
467
468    #[test]
469    fn test_quota_off_by_one_file_count() {
470        let mut tracker = QuotaTracker::new();
471        let mut config = SecurityConfig::default();
472        config.max_file_count = crate::Limit::Bounded(crate::non_zero!(1));
473        config.max_total_size = crate::Limit::Unbounded;
474        config.max_file_size = crate::Limit::Unbounded;
475
476        // First file should succeed
477        assert!(tracker.reserve(100, &config).is_ok());
478
479        // Second file should fail (max is 1)
480        let result = tracker.reserve(100, &config);
481        assert_matches!(result, Err(ArchiveError::QuotaExceeded { .. }));
482    }
483
484    // OPT-C003: Test fast path for unlimited quotas
485    #[test]
486    fn test_quota_fast_path_unlimited() {
487        let mut tracker = QuotaTracker::new();
488        let mut config = SecurityConfig::default();
489        // Set all quotas to unlimited (MAX values)
490        config.max_file_size = crate::Limit::Unbounded;
491        config.max_file_count = crate::Limit::Unbounded;
492        config.max_total_size = crate::Limit::Unbounded;
493
494        for i in 1..=1000 {
495            assert!(
496                tracker.reserve(1000, &config).is_ok(),
497                "file {i} should succeed with unlimited quotas"
498            );
499        }
500
501        assert_eq!(tracker.files_extracted(), 1000);
502        assert_eq!(tracker.bytes_written(), 1_000_000);
503    }
504
505    // OPT-C003: Verify fast path still catches overflow
506    #[test]
507    fn test_quota_fast_path_overflow_detection() {
508        let mut tracker = QuotaTracker::new();
509        let mut config = SecurityConfig::default();
510        config.max_file_size = crate::Limit::Unbounded;
511        config.max_file_count = crate::Limit::Unbounded;
512        config.max_total_size = crate::Limit::Unbounded;
513
514        // Manually set bytes_written to near overflow
515        tracker.bytes_written = u64::MAX - 100;
516
517        // Adding 200 bytes should trigger overflow detection
518        let result = tracker.reserve(200, &config);
519        assert_matches!(
520            result,
521            Err(ArchiveError::QuotaExceeded {
522                resource: crate::QuotaResource::IntegerOverflow
523            }),
524            "fast path should still detect overflow"
525        );
526    }
527
528    #[test]
529    fn test_reserve_without_file_limit_skips_only_file_size() {
530        let mut tracker = QuotaTracker::new();
531        let mut config = SecurityConfig::default();
532        config.max_file_size = crate::Limit::Bounded(crate::non_zero!(10));
533        config.max_file_count = crate::Limit::Bounded(crate::non_zero!(2));
534        config.max_total_size = crate::Limit::Bounded(crate::non_zero!(1000));
535
536        assert_matches!(
537            tracker.reserve(500, &config),
538            Err(ArchiveError::QuotaExceeded {
539                resource: crate::QuotaResource::FileSize { size: 500, max: 10 }
540            })
541        );
542        assert!(tracker.reserve_without_file_limit(500, &config).is_ok());
543        assert_matches!(
544            tracker.reserve_without_file_limit(501, &config),
545            Err(ArchiveError::QuotaExceeded {
546                resource: crate::QuotaResource::TotalSize {
547                    current: 1001,
548                    max: 1000
549                }
550            })
551        );
552    }
553
554    #[test]
555    fn test_reserve_without_file_limit_enforces_file_count() {
556        let mut tracker = QuotaTracker::new();
557        let mut config = SecurityConfig::default();
558        config.max_file_size = crate::Limit::Bounded(crate::non_zero!(10));
559        config.max_file_count = crate::Limit::Bounded(crate::non_zero!(1));
560
561        assert!(tracker.reserve_without_file_limit(500, &config).is_ok());
562        assert_matches!(
563            tracker.reserve_without_file_limit(500, &config),
564            Err(ArchiveError::QuotaExceeded {
565                resource: crate::QuotaResource::FileCount { current: 2, max: 1 }
566            })
567        );
568    }
569
570    #[test]
571    fn test_reserve_without_file_limit_fast_path_accepts_oversized_file() {
572        let mut tracker = QuotaTracker::new();
573        let mut config = SecurityConfig::default();
574        config.max_file_size = crate::Limit::Bounded(crate::non_zero!(10));
575        config.max_file_count = crate::Limit::Unbounded;
576        config.max_total_size = crate::Limit::Unbounded;
577
578        assert!(tracker.reserve(500, &config).is_err());
579        assert!(tracker.reserve_without_file_limit(500, &config).is_ok());
580        assert_eq!(tracker.files_extracted(), 1);
581        assert_eq!(tracker.bytes_written(), 500);
582    }
583
584    #[test]
585    fn test_reserve_without_file_limit_fast_path_detects_overflow() {
586        let mut tracker = QuotaTracker::new();
587        let mut config = SecurityConfig::default();
588        config.max_file_size = crate::Limit::Bounded(crate::non_zero!(10));
589        config.max_file_count = crate::Limit::Unbounded;
590        config.max_total_size = crate::Limit::Unbounded;
591
592        tracker.bytes_written = u64::MAX - 100;
593        assert_matches!(
594            tracker.reserve_without_file_limit(200, &config),
595            Err(ArchiveError::QuotaExceeded {
596                resource: crate::QuotaResource::IntegerOverflow
597            })
598        );
599    }
600
601    #[test]
602    fn test_charge_adds_bytes_without_counting_again() {
603        let mut tracker = QuotaTracker::new();
604        let config = SecurityConfig::default();
605
606        let count = tracker.reserve_count(&config).expect("count");
607        assert_eq!(tracker.files_extracted(), 1);
608        assert_eq!(tracker.bytes_written(), 0);
609
610        drop(tracker.charge(count, 40, &config).expect("charge"));
611        assert_eq!(tracker.files_extracted(), 1);
612        assert_eq!(tracker.bytes_written(), 40);
613    }
614
615    #[test]
616    fn test_reserve_count_exceeds_file_count() {
617        let mut tracker = QuotaTracker::new();
618        let mut config = SecurityConfig::default();
619        config.max_file_count = crate::Limit::Bounded(crate::non_zero!(1));
620
621        let _first = tracker.reserve_count(&config).expect("first");
622        assert_matches!(
623            tracker.reserve_count(&config),
624            Err(ArchiveError::QuotaExceeded {
625                resource: crate::QuotaResource::FileCount { current: 2, max: 1 }
626            })
627        );
628    }
629
630    #[test]
631    fn test_charge_enforces_file_and_total_size() {
632        let mut tracker = QuotaTracker::new();
633        let mut config = SecurityConfig::default();
634        config.max_file_size = crate::Limit::Bounded(crate::non_zero!(100));
635        config.max_total_size = crate::Limit::Bounded(crate::non_zero!(150));
636
637        let a = tracker.reserve_count(&config).expect("a");
638        let b = tracker.reserve_count(&config).expect("b");
639        let c = tracker.reserve_count(&config).expect("c");
640
641        assert_matches!(
642            tracker.charge(a, 101, &config),
643            Err(ArchiveError::QuotaExceeded {
644                resource: crate::QuotaResource::FileSize { .. }
645            })
646        );
647        drop(tracker.charge(b, 100, &config).expect("within budget"));
648        assert_matches!(
649            tracker.charge(c, 100, &config),
650            Err(ArchiveError::QuotaExceeded {
651                resource: crate::QuotaResource::TotalSize { .. }
652            })
653        );
654    }
655}