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
//! Decode limits and malformed-payload handling.
//!
//! The counts a chunk declares are attacker-controlled: these tests make sure a
//! payload cannot turn a small file into a large allocation, and that truncation
//! is reported instead of panicking.

use tsdb_reader::chunkenc::{
    self, DecodeLimits, FloatHistogramSample, IntHistogramSample, SampleSink,
};
use tsdb_reader::Error;

struct NullSink;

impl SampleSink for NullSink {
    fn push_float(&mut self, _ts: i64, _value: f64) {}
    fn push_int_histogram(&mut self, _h: &IntHistogramSample<'_>) {}
    fn push_float_histogram(&mut self, _h: &FloatHistogramSample<'_>) {}
}

#[derive(serde::Deserialize)]
struct ChunkFixture {
    name: String,
    encoding: String,
    bytes_hex: String,
}

fn fixtures() -> Vec<(String, u8, Vec<u8>)> {
    let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data/chunks.json");
    let raw = std::fs::read_to_string(path).unwrap();
    let parsed: Vec<ChunkFixture> = serde_json::from_str(&raw).unwrap();
    parsed
        .into_iter()
        .map(|fx| {
            let enc = match fx.encoding.as_str() {
                "XOR" => chunkenc::ENC_XOR,
                "histogram" => chunkenc::ENC_HISTOGRAM,
                "floathistogram" => chunkenc::ENC_FLOAT_HISTOGRAM,
                "XOR2" => chunkenc::ENC_XOR2,
                "histogramST" => chunkenc::ENC_HISTOGRAM_ST,
                "floathistogramST" => chunkenc::ENC_FLOAT_HISTOGRAM_ST,
                other => panic!("unknown encoding {other}"),
            };
            let bytes = (0..fx.bytes_hex.len() / 2)
                .map(|i| u8::from_str_radix(&fx.bytes_hex[i * 2..i * 2 + 2], 16).unwrap())
                .collect();
            (fx.name, enc, bytes)
        })
        .collect()
}

#[test]
fn a_sample_limit_below_the_declared_count_is_rejected() {
    let limits = DecodeLimits {
        max_samples: 1,
        ..DecodeLimits::default()
    };
    for (name, enc, bytes) in fixtures() {
        let error = chunkenc::decode_with_limits(enc, &bytes, &limits, &mut NullSink).unwrap_err();
        assert!(
            error.to_string().contains("samples"),
            "{name}: unexpected error {error}"
        );
        assert!(
            error.is_corruption(),
            "{name}: should be classified as corrupt"
        );
    }
}

#[test]
fn a_bucket_limit_is_enforced_for_histograms() {
    let limits = DecodeLimits {
        max_buckets: 1,
        ..DecodeLimits::default()
    };
    let mut checked = 0;
    for (name, enc, bytes) in fixtures() {
        if chunkenc::encoding_histogram_kind(enc).is_none() {
            continue;
        }
        let error = chunkenc::decode_with_limits(enc, &bytes, &limits, &mut NullSink).unwrap_err();
        assert!(
            error.to_string().contains("buckets"),
            "{name}: unexpected error {error}"
        );
        checked += 1;
    }
    assert_eq!(checked, 4, "all histogram encodings must be covered");
}

#[test]
fn a_span_limit_is_enforced_for_histograms() {
    let limits = DecodeLimits {
        max_spans: 0,
        ..DecodeLimits::default()
    };
    let (_, enc, bytes) = fixtures()
        .into_iter()
        .find(|(_, enc, _)| chunkenc::encoding_histogram_kind(*enc).is_some())
        .expect("a histogram fixture");
    let error = chunkenc::decode_with_limits(enc, &bytes, &limits, &mut NullSink).unwrap_err();
    assert!(error.to_string().contains("spans"), "{error}");
}

#[test]
fn unlimited_decoding_still_reads_the_fixtures() {
    for (name, enc, bytes) in fixtures() {
        chunkenc::decode_with_limits(enc, &bytes, &DecodeLimits::UNLIMITED, &mut NullSink)
            .unwrap_or_else(|e| panic!("{name}: {e}"));
    }
}

#[test]
fn a_header_that_claims_more_samples_than_the_payload_holds_fails() {
    // XOR chunk: two-byte header claims 65535 samples, no data follows.
    let error = chunkenc::decode(chunkenc::ENC_XOR, &[0xff, 0xff], &mut NullSink).unwrap_err();
    assert!(error.is_corruption(), "{error}");

    // XOR2: same, plus the mandatory ST header byte.
    let error =
        chunkenc::decode(chunkenc::ENC_XOR2, &[0xff, 0xff, 0x00], &mut NullSink).unwrap_err();
    assert!(error.is_corruption(), "{error}");

    // Histogram: 3-byte header only.
    let error =
        chunkenc::decode(chunkenc::ENC_HISTOGRAM, &[0x00, 0x05, 0x00], &mut NullSink).unwrap_err();
    assert!(error.is_corruption(), "{error}");
}

#[test]
fn every_truncation_of_every_fixture_is_an_error_not_a_panic() {
    for (name, enc, bytes) in fixtures() {
        for len in 0..bytes.len() {
            match chunkenc::decode(enc, &bytes[..len], &mut NullSink) {
                Ok(_) => panic!("{name}: {len}/{} bytes decoded successfully", bytes.len()),
                Err(e) => assert!(e.is_corruption(), "{name} at {len}: {e}"),
            }
        }
    }
}

#[test]
fn unknown_encodings_are_reported_as_unsupported() {
    for enc in [7u8, 42, 0xff] {
        let error = chunkenc::decode(enc, &[0, 0, 0], &mut NullSink).unwrap_err();
        assert!(matches!(error, Error::Unsupported(_)), "{error}");
        assert!(!error.is_corruption());
    }
}