Skip to main content

tsdb_reader/chunkenc/
decode_limits.rs

1//! Bounded decoding of chunk payloads.
2//!
3//! A chunk payload declares how many buckets and samples it contains. Those
4//! numbers come straight from the file, so a corrupt or hostile chunk could
5//! otherwise make the decoder allocate hundreds of megabytes for a 100-byte
6//! record. [`DecodeLimits`] caps the four things a payload controls:
7//!
8//! | Limit | What it bounds |
9//! |-------|----------------|
10//! | [`max_buckets`](DecodeLimits::max_buckets) | positive + negative buckets of one histogram |
11//! | [`max_spans`](DecodeLimits::max_spans) | span entries of one histogram layout |
12//! | [`max_custom_values`](DecodeLimits::max_custom_values) | custom bucket bounds |
13//! | [`max_samples`](DecodeLimits::max_samples) | samples in one chunk |
14//!
15//! The defaults are generous enough for anything Prometheus writes (a chunk
16//! holds at most 120 samples and at most a few thousand buckets) and small
17//! enough that a hostile payload fails immediately instead of exhausting
18//! memory.
19
20use crate::error::{Error, Result};
21
22/// Caps applied while decoding one chunk.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct DecodeLimits {
25    /// Maximum number of buckets across the positive and negative spans.
26    pub max_buckets: usize,
27    /// Maximum number of spans in the positive or negative span list.
28    pub max_spans: usize,
29    /// Maximum number of custom bucket bounds.
30    pub max_custom_values: usize,
31    /// Maximum number of samples a chunk may declare.
32    pub max_samples: u64,
33}
34
35impl Default for DecodeLimits {
36    fn default() -> Self {
37        Self {
38            max_buckets: 1 << 20,
39            max_spans: 1 << 16,
40            max_custom_values: 1 << 16,
41            max_samples: 1 << 20,
42        }
43    }
44}
45
46impl DecodeLimits {
47    /// No practical ceiling. Only for trusted data; a 16 MiB histogram chunk
48    /// can still legitimately expand to hundreds of megabytes of buckets.
49    pub const UNLIMITED: Self = Self {
50        max_buckets: usize::MAX,
51        max_spans: usize::MAX,
52        max_custom_values: usize::MAX,
53        max_samples: u64::MAX,
54    };
55
56    /// Checks a declared bucket count against the limit.
57    pub fn check_buckets(&self, buckets: usize) -> Result<()> {
58        if buckets > self.max_buckets {
59            return Err(Error::decode(format!(
60                "histogram declares {buckets} buckets, limit is {}",
61                self.max_buckets
62            )));
63        }
64        Ok(())
65    }
66
67    /// Checks a declared span count against the limit.
68    pub fn check_spans(&self, spans: u64) -> Result<()> {
69        if spans > self.max_spans as u64 {
70            return Err(Error::decode(format!(
71                "histogram declares {spans} spans, limit is {}",
72                self.max_spans
73            )));
74        }
75        Ok(())
76    }
77
78    /// Checks a declared custom-bucket count against the limit.
79    pub fn check_custom_values(&self, values: u64) -> Result<()> {
80        if values > self.max_custom_values as u64 {
81            return Err(Error::decode(format!(
82                "histogram declares {values} custom bounds, limit is {}",
83                self.max_custom_values
84            )));
85        }
86        Ok(())
87    }
88
89    /// Checks a chunk's declared sample count against the limit.
90    pub fn check_samples(&self, samples: u64) -> Result<()> {
91        if samples > self.max_samples {
92            return Err(Error::decode(format!(
93                "chunk declares {samples} samples, limit is {}",
94                self.max_samples
95            )));
96        }
97        Ok(())
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104
105    #[test]
106    fn defaults_accept_normal_payloads() {
107        let limits = DecodeLimits::default();
108        limits.check_samples(120).unwrap();
109        limits.check_buckets(2000).unwrap();
110        limits.check_spans(64).unwrap();
111        limits.check_custom_values(100).unwrap();
112    }
113
114    #[test]
115    fn declared_counts_above_the_limit_are_rejected() {
116        let limits = DecodeLimits {
117            max_buckets: 4,
118            max_spans: 2,
119            max_custom_values: 3,
120            max_samples: 10,
121        };
122        assert!(limits.check_buckets(5).unwrap_err().is_corruption());
123        assert!(limits.check_spans(3).is_err());
124        assert!(limits.check_custom_values(4).is_err());
125        assert!(limits.check_samples(11).is_err());
126        limits.check_buckets(4).unwrap();
127        limits.check_samples(10).unwrap();
128    }
129
130    #[test]
131    fn unlimited_accepts_everything() {
132        DecodeLimits::UNLIMITED.check_buckets(usize::MAX).unwrap();
133        DecodeLimits::UNLIMITED.check_samples(u64::MAX).unwrap();
134    }
135}