Skip to main content

oxabl_cache_format/
segment.rs

1//! `OXSG` sealed segment: the outer header and the chunk structure of the body.
2
3use crate::cursor::Cursor;
4use crate::error::{FormatError, Result};
5use crate::frame::VERSION;
6use crate::limits::PACK_BYTES;
7use crate::writer::Writer;
8
9const MAGIC: [u8; 4] = *b"OXSG";
10const ALG_AES256GCM_STREAM: u8 = 1;
11const CHUNK_LOG2: u8 = 16;
12
13/// Length of the segment header.
14pub const SEGMENT_HEADER_LEN: usize = 72;
15/// Plaintext bytes in a full chunk.
16pub const CHUNK_PLAINTEXT_LEN: usize = 1 << CHUNK_LOG2;
17/// Length of the authentication tag that ends every chunk.
18pub const CHUNK_TAG_LEN: usize = 16;
19/// Smallest segment: a header and one chunk holding the 14-byte plaintext header.
20pub const MIN_SEGMENT_LEN: usize = SEGMENT_HEADER_LEN + 14 + CHUNK_TAG_LEN;
21
22/// The unsealed header of a segment. Its bytes are the AEAD associated data's input.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct SegmentHeader {
25    pub salt: [u8; 32],
26    pub k_commit: [u8; 32],
27}
28
29impl SegmentHeader {
30    pub fn encode(&self) -> [u8; SEGMENT_HEADER_LEN] {
31        let mut w = Writer::with_capacity(SEGMENT_HEADER_LEN);
32        w.bytes(&MAGIC);
33        w.u8(VERSION);
34        w.u8(ALG_AES256GCM_STREAM);
35        w.u8(CHUNK_LOG2);
36        w.u8(0);
37        w.bytes(&self.salt);
38        w.bytes(&self.k_commit);
39        let mut out = [0u8; SEGMENT_HEADER_LEN];
40        out.copy_from_slice(&w.into_vec());
41        out
42    }
43
44    fn read(c: &mut Cursor<'_>) -> Result<Self> {
45        if c.array::<4>()? != MAGIC {
46            return Err(FormatError::BadMagic);
47        }
48        let version = c.u8()?;
49        if version != VERSION {
50            return Err(FormatError::UnsupportedVersion(version));
51        }
52        if c.u8()? != ALG_AES256GCM_STREAM {
53            return Err(FormatError::Invalid("segment algorithm"));
54        }
55        if c.u8()? != CHUNK_LOG2 {
56            return Err(FormatError::Invalid("chunk size"));
57        }
58        c.reserved_u8()?;
59        Ok(Self {
60            salt: c.array()?,
61            k_commit: c.array()?,
62        })
63    }
64
65    /// Decodes exactly one header.
66    pub fn decode(bytes: &[u8]) -> Result<Self> {
67        let mut c = Cursor::new(bytes);
68        let header = Self::read(&mut c)?;
69        c.finish()?;
70        Ok(header)
71    }
72}
73
74/// A sealed segment: header and body. The body is chunks of ciphertext and tags, opaque here.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct SealedSegment<'a> {
77    pub header: SegmentHeader,
78    pub body: &'a [u8],
79}
80
81impl<'a> SealedSegment<'a> {
82    pub fn encode(&self) -> Result<Vec<u8>> {
83        plaintext_len(self.body.len())?;
84        let mut out = Vec::with_capacity(SEGMENT_HEADER_LEN + self.body.len());
85        out.extend_from_slice(&self.header.encode());
86        out.extend_from_slice(self.body);
87        Ok(out)
88    }
89
90    pub fn decode(bytes: &'a [u8]) -> Result<Self> {
91        let mut c = Cursor::new(bytes);
92        let header = SegmentHeader::read(&mut c)?;
93        let body = c.take(c.remaining())?;
94        plaintext_len(body.len())?;
95        Ok(Self { header, body })
96    }
97}
98
99/// Plaintext length of a body of `body_len` bytes: every chunk but the last is full and
100/// the last holds at least one plaintext byte.
101pub fn plaintext_len(body_len: usize) -> Result<u64> {
102    if body_len as u64 > PACK_BYTES {
103        return Err(FormatError::LimitExceeded("segment size"));
104    }
105    let full = CHUNK_PLAINTEXT_LEN + CHUNK_TAG_LEN;
106    let chunks = body_len.div_ceil(full);
107    let last = body_len - chunks.saturating_sub(1) * full;
108    if chunks == 0 || last <= CHUNK_TAG_LEN {
109        return Err(FormatError::Invalid("chunk structure"));
110    }
111    Ok((body_len - chunks * CHUNK_TAG_LEN) as u64)
112}