zexc 1.2.1

zex native lossless compressor — CLI zexc, library zexc, files *.zex
Documentation
//! Security policy for ZEX — stronger defaults than typical bare LZ codecs.
//!
//! Compression formats are historically a **DoS surface** (zip bombs, huge
//! windows, unbounded allocations). ZEX hardens the decoder path:
//!
//! | Threat | Mitigation |
//! |--------|------------|
//! | Compression bomb | Hard absolute size caps (block + frame), not ratio |
//! | OOB match copy | Offset/length checked against decoded length |
//! | Huge alloc | `max_output`, `MAX_BLOCK_UNCOMPRESSED` |
//! | Silent corruption | CRC32 on by default (header flag) |
//! | Memory unsafety | Safe Rust; no `unsafe` in codec hot path |
//!
//! This is **integrity / robustness** security — not encryption. Encryption
//! can be layered later (AEAD) without changing the core LZ algorithm.

use crate::{Error, Result};

/// Hard maximum uncompressed size of a single block (16 MiB).
pub const MAX_BLOCK_UNCOMPRESSED: usize = 16 * 1024 * 1024;

/// Hard maximum compressed size of a single block payload (16 MiB + framing).
pub const MAX_BLOCK_COMPRESSED: usize = 16 * 1024 * 1024 + 64 * 1024;

/// Maximum match offset (window) — 8 MiB.
pub const MAX_OFFSET: usize = 8 * 1024 * 1024;

/// Maximum single match length.
pub const MAX_MATCH_LEN: usize = 1024 * 1024;

/// Minimum match length for the native codec.
pub const MIN_MATCH: usize = 4;

/// Default max total decompressed output (4 GiB).
pub const DEFAULT_MAX_OUTPUT: u64 = 4 * 1024 * 1024 * 1024;

/// Decoder / encoder security knobs.
#[derive(Debug, Clone)]
pub struct SecurityPolicy {
    /// Maximum total decompressed bytes.
    pub max_output: u64,
    /// Maximum single block uncompressed size.
    pub max_block_uncompressed: usize,
    /// Maximum single block compressed payload.
    pub max_block_compressed: usize,
    /// Require content checksum when flag present (always verify if present).
    pub verify_checksum: bool,
}

impl Default for SecurityPolicy {
    fn default() -> Self {
        Self {
            max_output: DEFAULT_MAX_OUTPUT,
            max_block_uncompressed: MAX_BLOCK_UNCOMPRESSED,
            max_block_compressed: MAX_BLOCK_COMPRESSED,
            verify_checksum: true,
        }
    }
}

impl SecurityPolicy {
    /// Strict preset: smaller caps, always verify.
    pub fn strict() -> Self {
        Self {
            max_output: 512 * 1024 * 1024,
            max_block_uncompressed: 4 * 1024 * 1024,
            max_block_compressed: 4 * 1024 * 1024 + 64 * 1024,
            verify_checksum: true,
        }
    }

    /// Validate block sizes before allocating / decoding payload.
    pub fn check_block(&self, compressed: usize, uncompressed: usize) -> Result<()> {
        if uncompressed > self.max_block_uncompressed {
            return Err(Error::InvalidParameter(format!(
                "block uncompressed {uncompressed} exceeds cap {}",
                self.max_block_uncompressed
            )));
        }
        if compressed > self.max_block_compressed {
            return Err(Error::InvalidParameter(format!(
                "block compressed {compressed} exceeds cap {}",
                self.max_block_compressed
            )));
        }
        Ok(())
    }

    /// Validate declared frame content size (DoS: refuse huge claimed outputs).
    ///
    /// Note: we do **not** limit compression ratio. Honest data (e.g. all zeros)
    /// can expand 100_000:1 from a tiny payload; that is not a bomb by itself.
    /// Nested archive bombs are out of scope of a single-frame codec — we cap
    /// absolute sizes instead.
    pub fn check_frame_size(&self, content_size: u64) -> Result<()> {
        if content_size != u64::MAX && content_size > self.max_output {
            return Err(Error::InvalidParameter(format!(
                "content size {content_size} exceeds max_output {}",
                self.max_output
            )));
        }
        Ok(())
    }
}

/// Validate a match copy will not go out of bounds (no dictionary).
#[inline]
pub fn check_match(offset: usize, match_len: usize, decoded_len: usize) -> Result<()> {
    check_match_with_history(offset, match_len, decoded_len, 0)
}

/// Validate a match when a dictionary of length `dict_len` is prefix history.
///
/// Virtual layout: `[dictionary | decoded_output…]`
/// Offset is measured from the current end of that virtual buffer.
#[inline]
pub fn check_match_with_history(
    offset: usize,
    match_len: usize,
    decoded_len: usize,
    dict_len: usize,
) -> Result<()> {
    if offset == 0 {
        return Err(Error::Decompression("security: match offset 0".into()));
    }
    if offset > MAX_OFFSET {
        return Err(Error::Decompression(format!(
            "security: offset {offset} > MAX_OFFSET"
        )));
    }
    let history = dict_len.saturating_add(decoded_len);
    if offset > history {
        return Err(Error::Decompression(format!(
            "security: offset {offset} > history {history} (dict={dict_len} out={decoded_len})"
        )));
    }
    if match_len == 0 || match_len > MAX_MATCH_LEN {
        return Err(Error::Decompression(format!(
            "security: bad match_len {match_len}"
        )));
    }
    Ok(())
}

/// Validate block sizes with default policy (used by native codec).
pub fn check_block_sizes(compressed: usize, uncompressed: usize) -> Result<()> {
    SecurityPolicy::default().check_block(compressed, uncompressed)
}