voided-core 0.2.1

Core cryptographic primitives for the Voided encryption library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Compression module providing Brotli and Gzip compression.

use crate::{Error, Result, MAGIC_COMPRESSED};
use alloc::vec::Vec;
use serde::{Deserialize, Serialize};

/// Maximum output produced by one in-memory decompression operation.
pub const MAX_DECOMPRESSED_SIZE: usize = 512 * 1024 * 1024;

/// Maximum expansion accepted by the default in-memory decompressor.
pub const MAX_COMPRESSION_RATIO: usize = 256;

/// Supported compression algorithms
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum CompressionAlgorithm {
    /// No compression
    None = 0x00,
    /// Gzip compression
    Gzip = 0x01,
    /// Brotli compression
    Brotli = 0x02,
}

impl CompressionAlgorithm {
    /// Get algorithm from byte identifier
    pub fn from_byte(byte: u8) -> Result<Self> {
        match byte {
            0x00 => Ok(CompressionAlgorithm::None),
            0x01 => Ok(CompressionAlgorithm::Gzip),
            0x02 => Ok(CompressionAlgorithm::Brotli),
            _ => Err(Error::UnsupportedAlgorithm(byte)),
        }
    }

    /// Get algorithm name as string
    pub fn name(&self) -> &'static str {
        match self {
            CompressionAlgorithm::None => "none",
            CompressionAlgorithm::Gzip => "gzip",
            CompressionAlgorithm::Brotli => "brotli",
        }
    }

    /// Parse from string name
    pub fn from_name(name: &str) -> Result<Self> {
        match name.to_lowercase().as_str() {
            "none" => Ok(CompressionAlgorithm::None),
            "gzip" => Ok(CompressionAlgorithm::Gzip),
            "brotli" => Ok(CompressionAlgorithm::Brotli),
            _ => Err(Error::UnsupportedAlgorithm(0)),
        }
    }
}

/// Result of a compression operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompressionResult {
    /// Compressed data
    pub compressed: Vec<u8>,
    /// Algorithm used
    pub algorithm: CompressionAlgorithm,
    /// Original size in bytes
    pub original_size: usize,
    /// Compressed size in bytes
    pub compressed_size: usize,
    /// Compression ratio (compressed / original)
    pub compression_ratio: f64,
}

/// Compression options
#[derive(Debug, Clone)]
pub struct CompressionOptions {
    /// Preferred algorithm (auto selects best)
    pub algorithm: CompressionAlgorithm,
    /// Minimum size threshold for compression (skip for smaller data)
    pub min_size_threshold: usize,
    /// Compression level (1-9 for gzip, 1-11 for brotli)
    pub level: u32,
}

impl Default for CompressionOptions {
    fn default() -> Self {
        Self {
            algorithm: CompressionAlgorithm::Brotli,
            min_size_threshold: 100,
            level: 6,
        }
    }
}

/// Compress data using the specified algorithm
pub fn compress(data: &[u8], options: Option<CompressionOptions>) -> Result<CompressionResult> {
    let opts = options.unwrap_or_default();
    validate_compression_level(opts.algorithm, opts.level)?;
    let original_size = data.len();

    // Skip compression for small data
    if original_size < opts.min_size_threshold {
        return Ok(CompressionResult {
            compressed: data.to_vec(),
            algorithm: CompressionAlgorithm::None,
            original_size,
            compressed_size: original_size,
            compression_ratio: 1.0,
        });
    }

    // Skip if explicitly set to none
    if opts.algorithm == CompressionAlgorithm::None {
        return Ok(CompressionResult {
            compressed: data.to_vec(),
            algorithm: CompressionAlgorithm::None,
            original_size,
            compressed_size: original_size,
            compression_ratio: 1.0,
        });
    }

    let (compressed, algorithm) = match opts.algorithm {
        CompressionAlgorithm::Brotli => compress_brotli(data, opts.level)?,
        CompressionAlgorithm::Gzip => compress_gzip(data, opts.level)?,
        CompressionAlgorithm::None => (data.to_vec(), CompressionAlgorithm::None),
    };

    let compressed_size = compressed.len();
    let compression_ratio = compressed_size as f64 / original_size as f64;

    // Only use compression if it saves at least 10% and remains within the
    // expansion policy enforced by the matching decompressor.
    let within_expansion_policy = compressed_size > 0
        && original_size <= compressed_size.saturating_mul(MAX_COMPRESSION_RATIO);
    if compression_ratio < 0.9 && within_expansion_policy {
        Ok(CompressionResult {
            compressed,
            algorithm,
            original_size,
            compressed_size,
            compression_ratio,
        })
    } else {
        Ok(CompressionResult {
            compressed: data.to_vec(),
            algorithm: CompressionAlgorithm::None,
            original_size,
            compressed_size: original_size,
            compression_ratio: 1.0,
        })
    }
}

fn validate_compression_level(algorithm: CompressionAlgorithm, level: u32) -> Result<()> {
    let valid = match algorithm {
        CompressionAlgorithm::None => level == 0 || level == CompressionOptions::default().level,
        CompressionAlgorithm::Gzip => level <= 9,
        CompressionAlgorithm::Brotli => level <= 11,
    };
    if valid {
        Ok(())
    } else {
        Err(Error::InvalidConfiguration(format!(
            "invalid compression level {level} for {}",
            algorithm.name()
        )))
    }
}

/// Decompress data using the specified algorithm
pub fn decompress(data: &[u8], algorithm: CompressionAlgorithm) -> Result<Vec<u8>> {
    decompress_with_limits(
        data,
        algorithm,
        MAX_DECOMPRESSED_SIZE,
        MAX_COMPRESSION_RATIO,
    )
}

/// Decompress with explicit output and expansion bounds.
pub fn decompress_with_limits(
    data: &[u8],
    algorithm: CompressionAlgorithm,
    max_output_size: usize,
    max_ratio: usize,
) -> Result<Vec<u8>> {
    if max_ratio == 0 {
        return Err(Error::InvalidConfiguration(
            "decompression ratio limit must be greater than zero".to_string(),
        ));
    }

    let ratio_limit = data.len().saturating_mul(max_ratio);
    let effective_limit = max_output_size.min(ratio_limit);
    match algorithm {
        CompressionAlgorithm::None => {
            if data.len() > max_output_size {
                return Err(Error::PayloadTooLarge {
                    size: data.len(),
                    limit: max_output_size,
                });
            }
            Ok(data.to_vec())
        }
        CompressionAlgorithm::Gzip => decompress_gzip(data, effective_limit),
        CompressionAlgorithm::Brotli => decompress_brotli(data, effective_limit),
    }
}

/// Decompress into an authenticated expected size while retaining global and
/// ratio bounds. The expected size is checked before any output allocation.
pub fn decompress_exact(
    data: &[u8],
    algorithm: CompressionAlgorithm,
    expected_size: usize,
) -> Result<Vec<u8>> {
    if expected_size > MAX_DECOMPRESSED_SIZE {
        return Err(Error::PayloadTooLarge {
            size: expected_size,
            limit: MAX_DECOMPRESSED_SIZE,
        });
    }
    let output = decompress_with_limits(data, algorithm, expected_size, MAX_COMPRESSION_RATIO)?;
    if output.len() != expected_size {
        return Err(Error::SizeMismatch {
            expected: expected_size,
            actual: output.len(),
        });
    }
    Ok(output)
}

fn read_decompressed_with_limit<R: std::io::Read>(
    reader: R,
    max_output_size: usize,
) -> Result<Vec<u8>> {
    use std::io::Read;

    let read_limit = max_output_size.saturating_add(1) as u64;
    let mut limited = reader.take(read_limit);
    let mut output = Vec::with_capacity(max_output_size.min(64 * 1024));
    limited
        .read_to_end(&mut output)
        .map_err(|e| Error::DecompressionFailed(e.to_string()))?;
    if output.len() > max_output_size {
        return Err(Error::PayloadTooLarge {
            size: output.len(),
            limit: max_output_size,
        });
    }
    Ok(output)
}

/// Compress data with Brotli
fn compress_brotli(data: &[u8], level: u32) -> Result<(Vec<u8>, CompressionAlgorithm)> {
    use brotli::enc::BrotliEncoderParams;

    let mut output = Vec::new();
    let mut params = BrotliEncoderParams::default();
    params.quality = level as i32;

    brotli::BrotliCompress(&mut std::io::Cursor::new(data), &mut output, &params)
        .map_err(|e| Error::CompressionFailed(e.to_string()))?;

    Ok((output, CompressionAlgorithm::Brotli))
}

/// Decompress Brotli data
fn decompress_brotli(data: &[u8], max_output_size: usize) -> Result<Vec<u8>> {
    let decoder = brotli::Decompressor::new(std::io::Cursor::new(data), 4096);
    read_decompressed_with_limit(decoder, max_output_size)
}

/// Compress data with Gzip
fn compress_gzip(data: &[u8], level: u32) -> Result<(Vec<u8>, CompressionAlgorithm)> {
    use flate2::write::GzEncoder;
    use flate2::Compression;
    use std::io::Write;

    let mut encoder = GzEncoder::new(Vec::new(), Compression::new(level));
    encoder
        .write_all(data)
        .map_err(|e| Error::CompressionFailed(e.to_string()))?;

    let output = encoder
        .finish()
        .map_err(|e| Error::CompressionFailed(e.to_string()))?;

    Ok((output, CompressionAlgorithm::Gzip))
}

/// Decompress Gzip data
fn decompress_gzip(data: &[u8], max_output_size: usize) -> Result<Vec<u8>> {
    use flate2::read::GzDecoder;

    read_decompressed_with_limit(GzDecoder::new(data), max_output_size)
}

/// Serialize compression result with header
pub fn serialize_with_header(result: &CompressionResult) -> Result<Vec<u8>> {
    let original_size =
        u32::try_from(result.original_size).map_err(|_| Error::PayloadTooLarge {
            size: result.original_size,
            limit: u32::MAX as usize,
        })?;
    let mut output = Vec::with_capacity(7 + result.compressed.len());

    // Magic bytes "VC"
    output.extend_from_slice(MAGIC_COMPRESSED);
    // Algorithm
    output.push(result.algorithm as u8);
    // Original size (big-endian)
    output.extend_from_slice(&original_size.to_be_bytes());
    // Compressed data
    output.extend_from_slice(&result.compressed);

    Ok(output)
}

/// Deserialize compression result with header
pub fn deserialize_with_header(data: &[u8]) -> Result<(Vec<u8>, CompressionAlgorithm, usize)> {
    if data.len() < 7 {
        return Err(Error::TruncatedPayload {
            expected: 7,
            actual: data.len(),
        });
    }

    // Check magic
    if &data[0..2] != MAGIC_COMPRESSED {
        return Err(Error::InvalidFormat);
    }

    // Parse algorithm
    let algorithm = CompressionAlgorithm::from_byte(data[2])?;

    // Parse original size
    let original_size = u32::from_be_bytes([data[3], data[4], data[5], data[6]]) as usize;

    // Extract compressed data
    let compressed = data[7..].to_vec();

    Ok((compressed, algorithm, original_size))
}

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

    #[test]
    fn test_gzip_roundtrip() {
        let data = b"Hello, World! This is a test message that should be compressed.";

        let result = compress(
            data,
            Some(CompressionOptions {
                algorithm: CompressionAlgorithm::Gzip,
                min_size_threshold: 10,
                level: 6,
            }),
        )
        .unwrap();

        let decompressed = decompress(&result.compressed, result.algorithm).unwrap();
        assert_eq!(data, &decompressed[..]);
    }

    #[test]
    fn test_brotli_roundtrip() {
        let data = b"Hello, World! This is a test message that should be compressed with Brotli.";

        let result = compress(
            data,
            Some(CompressionOptions {
                algorithm: CompressionAlgorithm::Brotli,
                min_size_threshold: 10,
                level: 6,
            }),
        )
        .unwrap();

        let decompressed = decompress(&result.compressed, result.algorithm).unwrap();
        assert_eq!(data, &decompressed[..]);
    }

    #[test]
    fn test_skip_small_data() {
        let data = b"tiny";

        let result = compress(
            data,
            Some(CompressionOptions {
                algorithm: CompressionAlgorithm::Brotli,
                min_size_threshold: 100, // Data is smaller than threshold
                level: 6,
            }),
        )
        .unwrap();

        assert_eq!(result.algorithm, CompressionAlgorithm::None);
        assert_eq!(result.compressed, data);
    }

    #[test]
    fn test_header_serialization() {
        let data = b"Test data for header serialization test with enough content.";

        let result = compress(
            data,
            Some(CompressionOptions {
                algorithm: CompressionAlgorithm::Gzip,
                min_size_threshold: 10,
                level: 6,
            }),
        )
        .unwrap();

        let serialized = serialize_with_header(&result).unwrap();
        let (compressed, algorithm, original_size) = deserialize_with_header(&serialized).unwrap();

        assert_eq!(algorithm, result.algorithm);
        assert_eq!(original_size, result.original_size);
        assert_eq!(compressed, result.compressed);
    }

    #[test]
    fn test_decompression_rejects_bomb_before_full_expansion() {
        let plaintext = vec![0u8; 2 * 1024 * 1024];
        let (compressed, _) = compress_gzip(&plaintext, 6).unwrap();
        assert!(compressed.len().saturating_mul(MAX_COMPRESSION_RATIO) < plaintext.len());
        assert!(matches!(
            decompress(&compressed, CompressionAlgorithm::Gzip),
            Err(Error::PayloadTooLarge { .. })
        ));
    }

    #[test]
    fn test_decompression_exact_enforces_expected_size() {
        let plaintext = b"bounded decompression".repeat(64);
        let (compressed, _) = compress_gzip(&plaintext, 6).unwrap();
        assert_eq!(
            decompress_exact(&compressed, CompressionAlgorithm::Gzip, plaintext.len()).unwrap(),
            plaintext
        );
        assert!(matches!(
            decompress_exact(&compressed, CompressionAlgorithm::Gzip, plaintext.len() - 1),
            Err(Error::PayloadTooLarge { .. }) | Err(Error::SizeMismatch { .. })
        ));
    }

    #[test]
    fn test_none_decompression_obeys_output_bound() {
        assert!(matches!(
            decompress_with_limits(&[0u8; 9], CompressionAlgorithm::None, 8, 256),
            Err(Error::PayloadTooLarge { size: 9, limit: 8 })
        ));
    }

    #[test]
    fn test_compression_rejects_invalid_levels_before_processing() {
        assert!(matches!(
            compress(
                b"small",
                Some(CompressionOptions {
                    algorithm: CompressionAlgorithm::Gzip,
                    min_size_threshold: usize::MAX,
                    level: 10,
                })
            ),
            Err(Error::InvalidConfiguration(_))
        ));
        assert!(matches!(
            compress(
                b"small",
                Some(CompressionOptions {
                    algorithm: CompressionAlgorithm::Brotli,
                    min_size_threshold: usize::MAX,
                    level: 12,
                })
            ),
            Err(Error::InvalidConfiguration(_))
        ));
    }
}