Skip to main content

oxabl_cache_format/
record.rs

1//! `OXER` sealed record: the outer header.
2
3use crate::cursor::Cursor;
4use crate::error::{FormatError, Result};
5use crate::frame::VERSION;
6use crate::limits::{RECORD_ALIGN, SEALED_RECORD_BYTES};
7use crate::writer::Writer;
8
9const MAGIC: [u8; 4] = *b"OXER";
10const ALG_AES256GCM: u8 = 1;
11
12/// Length of the record header.
13pub const RECORD_HEADER_LEN: usize = 72;
14/// Length of the authentication tag that ends a record.
15pub const RECORD_TAG_LEN: usize = 16;
16
17/// A sealed record: header fields and the ciphertext with its tag. A valid record is a
18/// multiple of 256 bytes long, at most 4,096, and large enough for the smallest `OXEP`.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct SealedRecord<'a> {
21    pub salt: [u8; 32],
22    pub k_commit: [u8; 32],
23    /// AES-256-GCM output: ciphertext then the 16-byte tag.
24    pub ciphertext: &'a [u8],
25}
26
27/// Sealed length of a record whose plaintext is `plaintext_len` bytes before padding.
28pub(crate) fn padded_plaintext_len(plaintext_len: usize) -> usize {
29    let sealed = RECORD_HEADER_LEN + plaintext_len + RECORD_TAG_LEN;
30    sealed.next_multiple_of(RECORD_ALIGN) - RECORD_HEADER_LEN - RECORD_TAG_LEN
31}
32
33impl<'a> SealedRecord<'a> {
34    fn check_len(total: usize) -> Result<()> {
35        if total > SEALED_RECORD_BYTES {
36            return Err(FormatError::LimitExceeded("sealed record"));
37        }
38        if !total.is_multiple_of(RECORD_ALIGN)
39            || total < crate::entry_payload::MIN_SEALED_RECORD_LEN
40        {
41            return Err(FormatError::Invalid("sealed record length"));
42        }
43        Ok(())
44    }
45
46    pub fn encode(&self) -> Result<Vec<u8>> {
47        Self::check_len(RECORD_HEADER_LEN + self.ciphertext.len())?;
48        let mut w = Writer::with_capacity(RECORD_HEADER_LEN + self.ciphertext.len());
49        w.bytes(&MAGIC);
50        w.u8(VERSION);
51        w.u8(ALG_AES256GCM);
52        w.u16(0);
53        w.bytes(&self.salt);
54        w.bytes(&self.k_commit);
55        w.bytes(self.ciphertext);
56        Ok(w.into_vec())
57    }
58
59    pub fn decode(bytes: &'a [u8]) -> Result<Self> {
60        let mut c = Cursor::new(bytes);
61        if c.array::<4>()? != MAGIC {
62            return Err(FormatError::BadMagic);
63        }
64        let version = c.u8()?;
65        if version != VERSION {
66            return Err(FormatError::UnsupportedVersion(version));
67        }
68        if c.u8()? != ALG_AES256GCM {
69            return Err(FormatError::Invalid("record algorithm"));
70        }
71        c.reserved_u16()?;
72        let salt = c.array()?;
73        let k_commit = c.array()?;
74        Self::check_len(bytes.len())?;
75        let ciphertext = c.take(c.remaining())?;
76        Ok(Self {
77            salt,
78            k_commit,
79            ciphertext,
80        })
81    }
82}