oxabl_cache_crypto/
segment_open.rs1use 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
18pub struct SegmentExpectation<'a> {
20 pub id: SegmentId,
21 pub sealed_len: u64,
23 pub plain_len: u64,
25 pub dictionary: Option<&'a Dictionary>,
27}
28
29pub(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
57pub(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
65pub 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}