oxabl_cache_crypto/
segment_seal.rs1use std::io::{Read, Write};
4
5use oxabl_cache_format::limits::PACK_BYTES;
6use oxabl_cache_format::segment::{CHUNK_PLAINTEXT_LEN, CHUNK_TAG_LEN, SegmentHeader};
7use oxabl_cache_format::{Codec, Limits, SegmentId, SegmentPlaintext};
8use zeroize::Zeroizing;
9
10use crate::aead::Cipher;
11use crate::compress::compress;
12use crate::dictionary::Dictionary;
13use crate::error::{Error, Result};
14use crate::keys::SegmentKey;
15use crate::nonce::chunk_nonce;
16use crate::random;
17use crate::segment_info::{SegmentSeal, sealed_segment_len};
18
19pub const DEFAULT_ZSTD_LEVEL: i32 = 3;
21
22#[derive(Clone, Copy)]
24pub struct SealOptions<'a> {
25 pub level: i32,
27 pub dictionary: Option<&'a Dictionary>,
28}
29
30impl Default for SealOptions<'_> {
31 fn default() -> Self {
32 Self {
33 level: DEFAULT_ZSTD_LEVEL,
34 dictionary: None,
35 }
36 }
37}
38
39pub fn seal_segment(
42 key: &SegmentKey,
43 input: impl Read,
44 options: &SealOptions<'_>,
45 limits: &Limits,
46 out: impl Write,
47) -> Result<SegmentSeal> {
48 let (compressed, plain_len) = compress(
49 input,
50 options.level,
51 options.dictionary,
52 limits.plaintext_bytes(),
53 )?;
54 let codec = if options.dictionary.is_some() {
55 Codec::ZstdDictionary
56 } else {
57 Codec::Zstd
58 };
59 let seal = seal_compressed(key, codec, &compressed, out)?;
60 Ok(SegmentSeal { plain_len, ..seal })
61}
62
63pub fn seal_compressed(
66 key: &SegmentKey,
67 codec: Codec,
68 compressed: &[u8],
69 mut out: impl Write,
70) -> Result<SegmentSeal> {
71 let sealed_len = sealed_segment_len(compressed.len() as u64)?;
72 if sealed_len > PACK_BYTES {
73 return Err(Error::Limit("segment size"));
74 }
75 let plaintext = Zeroizing::new(SegmentPlaintext { codec, compressed }.encode()?);
76
77 let salt = random::array()?;
78 let keys = key.object_keys(&salt);
79 let header = SegmentHeader {
80 salt,
81 k_commit: keys.commit(),
82 }
83 .encode();
84 let aad = blake3::hash(&header);
85 let cipher = Cipher::new(keys.enc())?;
86
87 let mut hasher = blake3::Hasher::new();
88 out.write_all(&header)?;
89 hasher.update(&header);
90 let mut written = header.len() as u64;
91
92 let chunks = plaintext.chunks(CHUNK_PLAINTEXT_LEN);
93 let last = chunks.len() - 1;
94 let mut buf = Zeroizing::new(Vec::with_capacity(CHUNK_PLAINTEXT_LEN + CHUNK_TAG_LEN));
95 for (i, chunk) in chunks.enumerate() {
96 buf.clear();
97 buf.extend_from_slice(chunk);
98 cipher.seal(chunk_nonce(i as u64, i == last), aad.as_bytes(), &mut buf)?;
99 out.write_all(&buf)?;
100 hasher.update(&buf);
101 written += buf.len() as u64;
102 }
103 out.flush()?;
104 debug_assert_eq!(written, sealed_len);
105 Ok(SegmentSeal {
106 id: SegmentId(hasher.finalize().into()),
107 sealed_len: written,
108 plain_len: 0,
109 compressed_len: compressed.len() as u64,
110 })
111}