1use 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#[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 pub(crate) const fn into_bytes(self) -> u64 {
43 self.bytes.0
44 }
45
46 pub(crate) const fn into_admitted(self) -> AdmittedSize {
49 AdmittedSize(self.bytes.0)
50 }
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
72pub struct AdmittedSize(u64);
73
74impl AdmittedSize {
75 #[must_use]
77 pub const fn get(self) -> u64 {
78 self.0
79 }
80}
81
82#[derive(Debug)]
95#[must_use]
96pub struct EntryCount(PhantomData<()>);
97
98#[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 #[must_use]
121 pub fn new() -> Self {
122 Self::default()
123 }
124
125 #[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 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 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 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 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 #[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 #[cfg(any(test, feature = "testing"))]
297 #[must_use]
298 pub fn files_extracted(&self) -> usize {
299 self.files_extracted
300 }
301
302 #[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 #[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 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 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 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 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 assert!(
450 tracker.reserve(5000, &config).is_ok(),
451 "file exactly at limit should succeed"
452 );
453
454 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 assert!(tracker.reserve(100, &config).is_ok());
478
479 let result = tracker.reserve(100, &config);
481 assert_matches!(result, Err(ArchiveError::QuotaExceeded { .. }));
482 }
483
484 #[test]
486 fn test_quota_fast_path_unlimited() {
487 let mut tracker = QuotaTracker::new();
488 let mut config = SecurityConfig::default();
489 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 #[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 tracker.bytes_written = u64::MAX - 100;
516
517 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}