ionic/ion/decoder/utilities/
decompression_limit.rs1use crate::ion::{IonError, IonResult};
2
3pub const DEFAULT_MAX_UNCOMPRESSED_SIZE: u64 = 1 << 31;
4pub const MAX_COMPRESSION_RATIO: u64 = 32768;
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub struct DecompressionLimit {
8 pub max_uncompressed_size: u64,
9}
10
11impl Default for DecompressionLimit {
12 fn default() -> Self {
13 Self {
14 max_uncompressed_size: DEFAULT_MAX_UNCOMPRESSED_SIZE,
15 }
16 }
17}
18
19impl DecompressionLimit {
20 pub fn new(max_uncompressed_size: u64) -> Self {
21 Self {
22 max_uncompressed_size,
23 }
24 }
25
26 pub fn validate(&self, compressed_len: usize, uncompressed_len: usize) -> IonResult<()> {
27 let uncompressed = uncompressed_len as u64;
28
29 if uncompressed > self.max_uncompressed_size {
30 return Err(IonError::from(format!(
31 "decompression rejected: uncompressed size {uncompressed} exceeds limit {}",
32 self.max_uncompressed_size
33 )));
34 }
35
36 let largest_plausible = (compressed_len as u64).saturating_mul(MAX_COMPRESSION_RATIO);
37 if uncompressed > largest_plausible {
38 return Err(IonError::from(format!(
39 "decompression rejected: declared uncompressed size {uncompressed} is implausible for {compressed_len} compressed bytes (max ratio {MAX_COMPRESSION_RATIO})"
40 )));
41 }
42
43 Ok(())
44 }
45}
46
47#[cfg(test)]
48mod tests {
49 use super::*;
50
51 #[test]
52 fn allows_high_ratio_within_cap() {
53 let limit = DecompressionLimit::default();
54 assert!(limit.validate(270, 2 * 1024 * 1024).is_ok());
55 }
56
57 #[test]
58 fn rejects_over_max_size() {
59 let limit = DecompressionLimit::new(1_024);
60 assert!(limit.validate(1, 1_025).is_err());
61 assert!(limit.validate(1, 1_024).is_ok());
62 }
63
64 #[test]
65 fn cap_applies_regardless_of_compressed_len() {
66 let limit = DecompressionLimit::new(4_096);
67 assert!(limit.validate(1_000_000, 4_096).is_ok());
68 assert!(limit.validate(1_000_000, 4_097).is_err());
69 }
70
71 #[test]
72 fn rejects_ratio_above_format_maximum() {
73 let limit = DecompressionLimit::default();
74 assert!(limit.validate(4, 4 * 32768).is_ok());
75 assert!(limit.validate(4, 4 * 32768 + 1).is_err());
76 }
77
78 #[test]
79 fn rejects_nonzero_size_with_no_compressed_bytes() {
80 let limit = DecompressionLimit::default();
81 assert!(limit.validate(0, 1).is_err());
82 assert!(limit.validate(0, 0).is_ok());
83 }
84}