tsdb-reader 0.3.0

Read-only, zero-copy Prometheus TSDB block reader: index v1-v3, all chunk encodings, integer histograms, postings and label matchers, tombstones
Documentation
//! Bounded decoding of chunk payloads.
//!
//! A chunk payload declares how many buckets and samples it contains. Those
//! numbers come straight from the file, so a corrupt or hostile chunk could
//! otherwise make the decoder allocate hundreds of megabytes for a 100-byte
//! record. [`DecodeLimits`] caps the four things a payload controls:
//!
//! | Limit | What it bounds |
//! |-------|----------------|
//! | [`max_buckets`](DecodeLimits::max_buckets) | positive + negative buckets of one histogram |
//! | [`max_spans`](DecodeLimits::max_spans) | span entries of one histogram layout |
//! | [`max_custom_values`](DecodeLimits::max_custom_values) | custom bucket bounds |
//! | [`max_samples`](DecodeLimits::max_samples) | samples in one chunk |
//!
//! The defaults are generous enough for anything Prometheus writes (a chunk
//! holds at most 120 samples and at most a few thousand buckets) and small
//! enough that a hostile payload fails immediately instead of exhausting
//! memory.

use crate::error::{Error, Result};

/// Caps applied while decoding one chunk.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DecodeLimits {
    /// Maximum number of buckets across the positive and negative spans.
    pub max_buckets: usize,
    /// Maximum number of spans in the positive or negative span list.
    pub max_spans: usize,
    /// Maximum number of custom bucket bounds.
    pub max_custom_values: usize,
    /// Maximum number of samples a chunk may declare.
    pub max_samples: u64,
}

impl Default for DecodeLimits {
    fn default() -> Self {
        Self {
            max_buckets: 1 << 20,
            max_spans: 1 << 16,
            max_custom_values: 1 << 16,
            max_samples: 1 << 20,
        }
    }
}

impl DecodeLimits {
    /// No practical ceiling. Only for trusted data; a 16 MiB histogram chunk
    /// can still legitimately expand to hundreds of megabytes of buckets.
    pub const UNLIMITED: Self = Self {
        max_buckets: usize::MAX,
        max_spans: usize::MAX,
        max_custom_values: usize::MAX,
        max_samples: u64::MAX,
    };

    /// Checks a declared bucket count against the limit.
    pub fn check_buckets(&self, buckets: usize) -> Result<()> {
        if buckets > self.max_buckets {
            return Err(Error::decode(format!(
                "histogram declares {buckets} buckets, limit is {}",
                self.max_buckets
            )));
        }
        Ok(())
    }

    /// Checks a declared span count against the limit.
    pub fn check_spans(&self, spans: u64) -> Result<()> {
        if spans > self.max_spans as u64 {
            return Err(Error::decode(format!(
                "histogram declares {spans} spans, limit is {}",
                self.max_spans
            )));
        }
        Ok(())
    }

    /// Checks a declared custom-bucket count against the limit.
    pub fn check_custom_values(&self, values: u64) -> Result<()> {
        if values > self.max_custom_values as u64 {
            return Err(Error::decode(format!(
                "histogram declares {values} custom bounds, limit is {}",
                self.max_custom_values
            )));
        }
        Ok(())
    }

    /// Checks a chunk's declared sample count against the limit.
    pub fn check_samples(&self, samples: u64) -> Result<()> {
        if samples > self.max_samples {
            return Err(Error::decode(format!(
                "chunk declares {samples} samples, limit is {}",
                self.max_samples
            )));
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn defaults_accept_normal_payloads() {
        let limits = DecodeLimits::default();
        limits.check_samples(120).unwrap();
        limits.check_buckets(2000).unwrap();
        limits.check_spans(64).unwrap();
        limits.check_custom_values(100).unwrap();
    }

    #[test]
    fn declared_counts_above_the_limit_are_rejected() {
        let limits = DecodeLimits {
            max_buckets: 4,
            max_spans: 2,
            max_custom_values: 3,
            max_samples: 10,
        };
        assert!(limits.check_buckets(5).unwrap_err().is_corruption());
        assert!(limits.check_spans(3).is_err());
        assert!(limits.check_custom_values(4).is_err());
        assert!(limits.check_samples(11).is_err());
        limits.check_buckets(4).unwrap();
        limits.check_samples(10).unwrap();
    }

    #[test]
    fn unlimited_accepts_everything() {
        DecodeLimits::UNLIMITED.check_buckets(usize::MAX).unwrap();
        DecodeLimits::UNLIMITED.check_samples(u64::MAX).unwrap();
    }
}