Skip to main content

oxabl_cache_crypto/
segment_open.rs

1//! Opening: id, header and commitment checks, STREAM decryption, then bounded decompression.
2
3use std::io::Write;
4
5use oxabl_cache_format::segment::{
6    CHUNK_PLAINTEXT_LEN, CHUNK_TAG_LEN, SEGMENT_HEADER_LEN, SealedSegment, plaintext_len,
7};
8use oxabl_cache_format::{Codec, Limits, SegmentId, SegmentPlaintext};
9use zeroize::Zeroizing;
10
11use crate::aead::Cipher;
12use crate::compress::decompress;
13use crate::dictionary::Dictionary;
14use crate::error::{Error, Result};
15use crate::keys::SegmentKey;
16use crate::nonce::chunk_nonce;
17
18/// What a caller already knows about a segment from its signed record.
19pub struct SegmentExpectation<'a> {
20    pub id: SegmentId,
21    /// Exact length of the sealed bytes.
22    pub sealed_len: u64,
23    /// Exact length of the decompressed bytes.
24    pub plain_len: u64,
25    /// The verified dictionary the record names, if any.
26    pub dictionary: Option<&'a Dictionary>,
27}
28
29/// Decrypts every chunk of `sealed` and returns the `OXSP` plaintext. Authenticates the
30/// whole stream before returning, so no byte of an altered segment is released.
31pub(crate) fn decrypt_segment(key: &SegmentKey, sealed: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
32    let segment = SealedSegment::decode(sealed)?;
33    let keys = key.object_keys(&segment.header.salt);
34    if !keys.commits_to(&segment.header.k_commit) {
35        return Err(Error::KeyCommitment);
36    }
37    let aad = blake3::hash(&sealed[..SEGMENT_HEADER_LEN]);
38    let cipher = Cipher::new(keys.enc())?;
39    let total = plaintext_len(segment.body.len())?;
40    let mut plaintext = Zeroizing::new(Vec::with_capacity(total as usize));
41    let mut scratch = Zeroizing::new(Vec::with_capacity(CHUNK_PLAINTEXT_LEN + CHUNK_TAG_LEN));
42    let chunks = segment.body.chunks(CHUNK_PLAINTEXT_LEN + CHUNK_TAG_LEN);
43    let last = chunks.len() - 1;
44    for (i, chunk) in chunks.enumerate() {
45        scratch.clear();
46        scratch.extend_from_slice(chunk);
47        let opened = cipher.open(
48            chunk_nonce(i as u64, i == last),
49            aad.as_bytes(),
50            &mut scratch,
51        )?;
52        plaintext.extend_from_slice(opened);
53    }
54    Ok(plaintext)
55}
56
57/// Checks `BLAKE3(sealed)` against the signed segment id.
58pub(crate) fn verify_id(sealed: &[u8], id: &SegmentId) -> Result<()> {
59    if blake3::hash(sealed).as_bytes() != &id.0 {
60        return Err(Error::SegmentId);
61    }
62    Ok(())
63}
64
65/// Verifies and opens an artifact segment, writing the concatenated files to `out`.
66///
67/// Nothing is written unless every chunk authenticates; the decompressed output is then
68/// bounded by the signed `plain_len`. A failure while writing leaves `out` partial, so the
69/// caller discards it on any error.
70pub fn open_segment(
71    key: &SegmentKey,
72    sealed: &[u8],
73    expect: &SegmentExpectation<'_>,
74    limits: &Limits,
75    out: impl Write,
76) -> Result<()> {
77    if expect.plain_len > limits.plaintext_bytes() {
78        return Err(Error::Limit("plaintext per artifact set"));
79    }
80    if sealed.len() as u64 != expect.sealed_len {
81        return Err(Error::Mismatch("sealed length"));
82    }
83    verify_id(sealed, &expect.id)?;
84    let plaintext = decrypt_segment(key, sealed)?;
85    let body = SegmentPlaintext::decode(&plaintext)?;
86    match (body.codec, expect.dictionary) {
87        (Codec::Zstd, None) | (Codec::ZstdDictionary, Some(_)) => {}
88        _ => return Err(Error::Mismatch("codec and dictionary")),
89    }
90    decompress(body.compressed, expect.dictionary, expect.plain_len, out)
91}