Skip to main content

oxabl_cache_format/
entry_payload.rs

1//! `OXEP` plaintext of a sealed record.
2
3use crate::cursor::Cursor;
4use crate::error::{FormatError, Result};
5use crate::frame::{read_header, write_header};
6use crate::ids::{PublicKey, SegmentId, Signature};
7use crate::limits::{FILES_PER_SET, Limits, PACK_BYTES, PATH_BYTES, SET_PATH_BYTES};
8use crate::record::{RECORD_HEADER_LEN, RECORD_TAG_LEN, padded_plaintext_len};
9use crate::segment::MIN_SEGMENT_LEN;
10use crate::writer::Writer;
11
12const MAGIC: [u8; 4] = *b"OXEP";
13const FIXED_LEN: usize = 132;
14const SIGNATURE_LEN: usize = 64;
15const FILE_MIN: usize = 2 + 8;
16const ZERO_ID: [u8; 32] = [0; 32];
17
18/// Smallest sealed record: header, tag, the fixed `OXEP` fields and the signature.
19pub(crate) const MIN_SEALED_RECORD_LEN: usize =
20    RECORD_HEADER_LEN + RECORD_TAG_LEN + FIXED_LEN + SIGNATURE_LEN;
21
22/// One file of an artifact set.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct EntryFile<'a> {
25    /// Relative path: not empty, not absolute, no `..` component, no NUL.
26    pub path: &'a str,
27    pub size: u64,
28}
29
30/// The signed content of a record. [`EntryPayload::signed_bytes`] is the part the signature
31/// covers, after the caller's domain-separated prefix.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct EntryPayload<'a> {
34    pub segment_id: SegmentId,
35    pub segment_len: u32,
36    pub dict_id: Option<SegmentId>,
37    /// Sum of the file sizes.
38    pub plain_len: u64,
39    pub created_at: i64,
40    pub roster_version: u64,
41    pub signer: PublicKey,
42    pub files: Vec<EntryFile<'a>>,
43    pub signature: Signature,
44}
45
46fn check_path(path: &str) -> Result<()> {
47    if path.is_empty()
48        || path.starts_with('/')
49        || path.contains('\0')
50        || path.split('/').any(|part| part == "..")
51    {
52        return Err(FormatError::Invalid("path"));
53    }
54    if path.len() > PATH_BYTES {
55        return Err(FormatError::LimitExceeded("path length"));
56    }
57    Ok(())
58}
59
60impl<'a> EntryPayload<'a> {
61    fn check(&self, limits: &Limits) -> Result<()> {
62        if self.files.len() > FILES_PER_SET {
63            return Err(FormatError::LimitExceeded("files per set"));
64        }
65        let mut total_paths = 0usize;
66        let mut total_size = 0u64;
67        for (i, f) in self.files.iter().enumerate() {
68            check_path(f.path)?;
69            if self.files[..i].iter().any(|g| g.path == f.path) {
70                return Err(FormatError::Invalid("duplicate path"));
71            }
72            total_paths += f.path.len();
73            total_size = total_size
74                .checked_add(f.size)
75                .ok_or(FormatError::LimitExceeded("plaintext per artifact set"))?;
76        }
77        if total_paths > SET_PATH_BYTES {
78            return Err(FormatError::LimitExceeded("path bytes per set"));
79        }
80        if total_size != self.plain_len {
81            return Err(FormatError::Invalid(
82                "plain_len differs from the file sizes",
83            ));
84        }
85        if self.plain_len > limits.plaintext_bytes() {
86            return Err(FormatError::LimitExceeded("plaintext per artifact set"));
87        }
88        let len = u64::from(self.segment_len);
89        if len < MIN_SEGMENT_LEN as u64 || len > PACK_BYTES {
90            return Err(FormatError::Invalid("segment_len"));
91        }
92        if self.dict_id.is_some_and(|d| d.0 == ZERO_ID) {
93            return Err(FormatError::Invalid("zero dict_id"));
94        }
95        Ok(())
96    }
97
98    fn write_signed(&self, w: &mut Writer) -> Result<()> {
99        write_header(w, MAGIC, 0);
100        w.bytes(&self.segment_id.0);
101        w.u32(self.segment_len);
102        w.bytes(&self.dict_id.map_or(ZERO_ID, |d| d.0));
103        w.u64(self.plain_len);
104        w.i64(self.created_at);
105        w.u64(self.roster_version);
106        w.bytes(&self.signer);
107        w.u16(self.files.len() as u16);
108        for f in &self.files {
109            w.str16(f.path)?;
110            w.u64(f.size);
111        }
112        Ok(())
113    }
114
115    /// Every byte before the signature.
116    pub fn signed_bytes(&self, limits: &Limits) -> Result<Vec<u8>> {
117        self.check(limits)?;
118        let mut w = Writer::default();
119        self.write_signed(&mut w)?;
120        Ok(w.into_vec())
121    }
122
123    /// The plaintext of the record: signed bytes, signature, zero padding so that the sealed
124    /// record is a multiple of 256 bytes.
125    pub fn encode(&self, limits: &Limits) -> Result<Vec<u8>> {
126        self.check(limits)?;
127        let mut w = Writer::default();
128        self.write_signed(&mut w)?;
129        w.bytes(&self.signature);
130        let padded = padded_plaintext_len(w.len());
131        w.zeros(padded - w.len());
132        Ok(w.into_vec())
133    }
134
135    pub fn decode(bytes: &'a [u8], limits: &Limits) -> Result<Self> {
136        let mut c = Cursor::new(bytes);
137        read_header(&mut c, MAGIC, 0)?;
138        let segment_id = SegmentId(c.array()?);
139        let segment_len = c.u32()?;
140        let dict: [u8; 32] = c.array()?;
141        let plain_len = c.u64()?;
142        let created_at = c.i64()?;
143        let roster_version = c.u64()?;
144        let signer = c.array()?;
145        let file_count = c.count16(FILES_PER_SET, "files per set", FILE_MIN)?;
146        let mut files = Vec::with_capacity(file_count);
147        for _ in 0..file_count {
148            files.push(EntryFile {
149                path: c.str16()?,
150                size: c.u64()?,
151            });
152        }
153        let signature = c.array()?;
154        let payload = Self {
155            segment_id,
156            segment_len,
157            dict_id: (dict != ZERO_ID).then_some(SegmentId(dict)),
158            plain_len,
159            created_at,
160            roster_version,
161            signer,
162            files,
163            signature,
164        };
165        payload.check(limits)?;
166        let used = bytes.len() - c.remaining();
167        if bytes.len() != padded_plaintext_len(used) {
168            return Err(FormatError::Invalid("padding length"));
169        }
170        if c.take(c.remaining())?.iter().any(|&b| b != 0) {
171            return Err(FormatError::Invalid("padding is not zero"));
172        }
173        Ok(payload)
174    }
175}