vcon_server/envelope/
column.rs1use std::fmt;
12
13use aws_lc_rs::hmac;
14
15use super::locked::LockedPage;
16use super::{
17 FORMAT, KEY_LEN, Key, KeyError, LABEL, NONCE_LEN, TAG_LEN, gcm_open, gcm_seal, hkdf_sha256,
18};
19use crate::ids::TenantId;
20
21const COLUMN_LABEL: &[u8] = b"vcon-server/v1 columns";
23
24const INDEX_LABEL: &[u8] = b"vcon-server/v1 index";
26
27const COLUMN_KIND: u8 = 3;
30
31pub const REGISTRY: TenantId = TenantId([0; 16]);
34
35pub const SEALED_COLUMN_OVERHEAD: usize = 1 + NONCE_LEN + TAG_LEN;
38
39pub struct ColumnKeys {
42 column: Key,
43 index: Key,
44}
45
46impl fmt::Debug for ColumnKeys {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 f.debug_struct("ColumnKeys").finish_non_exhaustive()
50 }
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub struct ColumnContext<'a> {
59 pub tenant: TenantId,
61 pub table: &'a str,
63 pub column: &'a str,
65 pub row: &'a [u8],
67}
68
69impl ColumnKeys {
70 pub fn derive(catalog: &Key) -> Result<ColumnKeys, KeyError> {
76 Ok(ColumnKeys {
77 column: derive_key(catalog.bytes(), COLUMN_LABEL)?,
78 index: derive_key(catalog.bytes(), INDEX_LABEL)?,
79 })
80 }
81}
82
83fn field(out: &mut Vec<u8>, bytes: &[u8]) {
86 let len = u32::try_from(bytes.len()).expect("a table, column or row key is under 4 GiB");
87 out.extend(len.to_be_bytes());
88 out.extend(bytes);
89}
90
91fn derive_key(parent: &[u8], info: &[u8]) -> Result<Key, KeyError> {
94 let mut page = LockedPage::new().map_err(KeyError::Memory)?;
95 hkdf_sha256(&[], parent, info, &mut page.bytes_mut()[..KEY_LEN]);
96 Ok(Key { page })
97}
98
99fn subkey_info(ctx: &ColumnContext<'_>) -> Vec<u8> {
102 let mut info = Vec::new();
103 field(&mut info, ctx.table.as_bytes());
104 field(&mut info, ctx.column.as_bytes());
105 field(&mut info, ctx.row);
106 info
107}
108
109fn associated_data(ctx: &ColumnContext<'_>, format: u8) -> Vec<u8> {
113 let mut ad = LABEL.to_vec();
114 ad.push(format);
115 ad.push(COLUMN_KIND);
116 ad.extend(ctx.tenant.0);
117 ad.extend(subkey_info(ctx));
118 ad
119}
120
121fn subkey(keys: &ColumnKeys, ctx: &ColumnContext<'_>) -> Result<Key, KeyError> {
124 derive_key(keys.column.bytes(), &subkey_info(ctx))
125}
126
127pub fn seal_column(
138 keys: &ColumnKeys,
139 ctx: &ColumnContext<'_>,
140 plaintext: &[u8],
141) -> Result<Vec<u8>, KeyError> {
142 let nonce: [u8; NONCE_LEN] = aws_lc_rs::rand::generate(&aws_lc_rs::rand::SystemRandom::new())
144 .expect("AWS-LC aborts instead of failing")
145 .expose();
146 seal_column_with_nonce(keys, ctx, nonce, plaintext)
147}
148
149fn seal_column_with_nonce(
150 keys: &ColumnKeys,
151 ctx: &ColumnContext<'_>,
152 nonce: [u8; NONCE_LEN],
153 plaintext: &[u8],
154) -> Result<Vec<u8>, KeyError> {
155 let key = subkey(keys, ctx)?;
156 let mut blob = Vec::with_capacity(SEALED_COLUMN_OVERHEAD + plaintext.len());
157 blob.push(FORMAT);
158 blob.extend(nonce);
159 blob.extend(plaintext);
160 let ad = associated_data(ctx, FORMAT);
161 let tag = gcm_seal(key.bytes(), nonce, &ad, &mut blob[1 + NONCE_LEN..]);
162 blob.extend(tag);
163 Ok(blob)
164}
165
166pub fn open_column(
175 keys: &ColumnKeys,
176 ctx: &ColumnContext<'_>,
177 blob: &[u8],
178) -> Result<Vec<u8>, KeyError> {
179 let (&format, rest) = blob.split_first().ok_or(KeyError::Damaged)?;
180 let (nonce, sealed) = rest
181 .split_first_chunk::<NONCE_LEN>()
182 .ok_or(KeyError::Damaged)?;
183 if sealed.len() < TAG_LEN {
184 return Err(KeyError::Damaged);
185 }
186 let key = subkey(keys, ctx)?;
187 let mut text = sealed.to_vec();
188 let len = gcm_open(
189 key.bytes(),
190 *nonce,
191 &associated_data(ctx, format),
192 &mut text,
193 )
194 .map_err(|_| KeyError::Damaged)?;
195 text.truncate(len);
196 Ok(text)
197}
198
199#[must_use]
203pub fn mac(keys: &ColumnKeys, value: &[u8]) -> [u8; 32] {
204 hmac_sha256(keys.index.bytes(), value)
205}
206
207fn hmac_sha256(key: &[u8], value: &[u8]) -> [u8; 32] {
208 let key = hmac::Key::new(hmac::HMAC_SHA256, key);
209 hmac::sign(&key, value)
210 .as_ref()
211 .try_into()
212 .expect("HMAC-SHA256 is 32 bytes")
213}
214
215#[cfg(test)]
216mod tests;