//! The row seal (plan §2.2).//!//! ```text//! sealed_enc = "s1:" b64url(nonce12 || AES-256-GCM(DEK, pad(canonical JSON of every sealed column), aad))//! aad = "s1|" database_id "|" table "|" id//! dek_enc = "d1:" b64url(nonce12 || AES-256-GCM(TK(table, v), DEK, aad'))//! aad' = "d1|" database_id "|" table "|" id "|" v//! seal_v = v//! ```//!//! A column is SEALED unless the definition's `seal.clear` names it (fail//! closed: a column added later is sealed). `id` is the row's frame and never//! in `data`'s sealed half. All sealed columns go in ONE blob per row.//!//! **Padding.** The canonical JSON is padded with ASCII spaces to the next of//! 64, 256, 1024 or 4096 bytes, then to a multiple of 4096. Spaces are JSON//! whitespace, so the opener parses the padded text as it stands.use rand::RngCore;use serde_json::{Map, Value};use zeroize::Zeroizing;usesuper::keys::{table_key, DataKey, Key32};usesuper::{b64, canonical_json, gcm_open, gcm_seal, plain_field, unb64, SealError, NONCE_LEN};usecrate::definitions::SealSpec;pubconst BODY_PREFIX: &str = "s1:";pubconst DEK_PREFIX: &str = "d1:";/// The column the sealed blob is stored in.pubconst SEALED_ENC: &str = "sealed_enc";/// The column the row's wrapped DEK is stored in.pubconst DEK_ENC: &str = "dek_enc";/// The column naming the table-key version the DEK is wrapped under.pubconst SEAL_V: &str = "seal_v";/// Columns only the sealer writes.pubconst RESERVED: [&str; 3] = [SEALED_ENC, DEK_ENC, SEAL_V];/// The row's frame: never sealed, never a clash.pubconst FRAME: [&str; 1] = ["id"];/// One row's data key, wiped when it drops.pubstructDek(Zeroizing<[u8; 32]>);implDek {/// A fresh DEK from the OS, minted when a row is first sealed.pubfn mint() -> Dek {letmut bytes = Zeroizing::new([0u8; 32]); rand::rngs::OsRng.fill_bytes(bytes.as_mut_slice());Dek(bytes) }pubfn from_bytes(bytes: [u8; 32]) -> Dek {Dek(Zeroizing::new(bytes)) }pubfn expose(&self) -> &[u8; 32] { &self.0 }}impl std::fmt::DebugforDek {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("Dek(…)") }}/// The padded length for `len` bytes of plaintext.pubfn bucket(len: usize) -> usize {match [64, 256, 1024, 4096].into_iter().find(|b| len <= *b) {Some(b) => b,None => len.div_ceil(4096) * 4096, }}/// `bytes` padded with spaces to its bucket.pubfn pad(bytes: &[u8]) -> Vec<u8> {letmut out = Vec::with_capacity(bucket(bytes.len())); out.extend_from_slice(bytes); out.resize(bucket(bytes.len()), b' '); out}pubfn body_aad(database_id: &str, table: &str, id: &str) -> Result<String, SealError> { plain_field("database", database_id)?; plain_field("table", table)?; plain_field("id", id)?;Ok(format!("s1|{database_id}|{table}|{id}"))}pubfn dek_aad(database_id: &str, table: &str, id: &str, v: u32) -> Result<String, SealError> {Ok(format!("d1|{}|{v}", &body_aad(database_id, table, id)?[3..]))}/// Split a row into its clear half and its sealed half by the table's `seal`/// block. A row carrying a reserved column is refused: only the sealer writes/// those.pubfn split(spec: &SealSpec, row: &Map<String, Value>) -> Result<(Map<String, Value>, Map<String, Value>), SealError> {letmut clear = Map::new();letmut sealed = Map::new();for (column, value) in row {if RESERVED.contains(&column.as_str()) {returnErr(SealError::ColumnClash(format!("{column} is written by the sealer"))); }if FRAME.contains(&column.as_str()) || spec.clear.iter().any(|c| c == column) { clear.insert(column.clone(), value.clone()); } else { sealed.insert(column.clone(), value.clone()); } }Ok((clear, sealed))}/// `sealed_enc` for the sealed columns, with the nonce supplied.pubfn seal_body_with(nonce: &[u8; NONCE_LEN], dek: &Dek, database_id: &str, table: &str, id: &str, sealed: &Map<String, Value>) -> Result<String, SealError> {let aad = body_aad(database_id, table, id)?;let plain = Zeroizing::new(pad(canonical_json(&Value::Object(sealed.clone())).as_bytes()));Ok(format!("{BODY_PREFIX}{}", b64(&gcm_seal(dek.expose(), nonce, &plain, aad.as_bytes())?)))}/// The sealed columns back out of `sealed_enc`.pubfn open_body(dek: &Dek, database_id: &str, table: &str, id: &str, sealed_enc: &str) -> Result<Map<String, Value>, SealError> {let aad = body_aad(database_id, table, id)?;let body = unb64(sealed_enc.strip_prefix(BODY_PREFIX).ok_or(SealError::DoesNotOpen)?).ok_or(SealError::DoesNotOpen)?;let plain = Zeroizing::new(gcm_open(dek.expose(), &body, aad.as_bytes())?);match serde_json::from_slice::<Value>(&plain) {Ok(Value::Object(map)) => Ok(map), _ => Err(SealError::DoesNotOpen), }}/// `dek_enc`: the DEK wrapped under TK(table, v), with the nonce supplied.pubfn wrap_dek_with(nonce: &[u8; NONCE_LEN], tk: &Key32, database_id: &str, table: &str, id: &str, v: u32, dek: &Dek) -> Result<String, SealError> {let aad = dek_aad(database_id, table, id, v)?;Ok(format!("{DEK_PREFIX}{}", b64(&gcm_seal(tk, nonce, dek.expose(), aad.as_bytes())?)))}/// The DEK back out of `dek_enc`.pubfn open_dek(tk: &Key32, database_id: &str, table: &str, id: &str, v: u32, dek_enc: &str) -> Result<Dek, SealError> {let aad = dek_aad(database_id, table, id, v)?;let body = unb64(dek_enc.strip_prefix(DEK_PREFIX).ok_or(SealError::DoesNotOpen)?).ok_or(SealError::DoesNotOpen)?;let bytes = Zeroizing::new(gcm_open(tk, &body, aad.as_bytes())?);let array: [u8; 32] = bytes.as_slice().try_into().map_err(|_| SealError::DoesNotOpen)?;Ok(Dek::from_bytes(array))}/// Seal a row as it is stored in `rows.data`: the clear columns, then/// `sealed_enc`, `dek_enc` and `seal_v`. `dek` is the row's existing DEK on an/// edit (so a share of it keeps opening) and `None` on a create.pubfn seal_row(dk: &DataKey, database_id: &str, table: &str, id: &str, v: u32, spec: &SealSpec, row: &Map<String, Value>, dek: Option<&Dek>) -> Result<Map<String, Value>, SealError> {letmut body_nonce = [0u8; NONCE_LEN];letmut dek_nonce = [0u8; NONCE_LEN]; rand::rngs::OsRng.fill_bytes(&mut body_nonce); rand::rngs::OsRng.fill_bytes(&mut dek_nonce);let fresh;let dek = match dek {Some(dek) => dek,None => { fresh = Dek::mint(); &fresh } }; seal_row_with(&body_nonce, &dek_nonce, dek, dk, database_id, table, id, v, spec, row)}/// [`seal_row`] with every random input supplied.#[allow(clippy::too_many_arguments)]pubfn seal_row_with(body_nonce: &[u8; NONCE_LEN], dek_nonce: &[u8; NONCE_LEN], dek: &Dek, dk: &DataKey, database_id: &str, table: &str, id: &str, v: u32, spec: &SealSpec, row: &Map<String, Value>) -> Result<Map<String, Value>, SealError> {let tk = table_key(dk, database_id, table, v)?;let (mut stored, sealed) = split(spec, row)?; stored.insert(SEALED_ENC.into(), Value::String(seal_body_with(body_nonce, dek, database_id, table, id, &sealed)?)); stored.insert(DEK_ENC.into(), Value::String(wrap_dek_with(dek_nonce, &tk, database_id, table, id, v, dek)?)); stored.insert(SEAL_V.into(), Value::from(v));Ok(stored)}/// Is this stored row sealed (does it carry a blob)? An open row in a sealed/// table answers false: legacy, or written by the Worker outside a window.pubfn is_sealed(data: &Map<String, Value>) -> bool { data.get(SEALED_ENC).is_some_and(|v| !v.is_null())}/// The row's `seal_v`, required on a sealed row.pubfn version_of(data: &Map<String, Value>) -> Result<u32, SealError> { data.get(SEAL_V) .and_then(Value::as_u64) .and_then(|n| u32::try_from(n).ok()) .filter(|n| *n > 0) .ok_or(SealError::ColumnMissing(SEAL_V))}/// The row's DEK, opened with the TK of its own version.pubfn dek_of_with_table_key(tk: &Key32, database_id: &str, table: &str, id: &str, data: &Map<String, Value>) -> Result<Dek, SealError> {let v = version_of(data)?;let dek_enc = data.get(DEK_ENC).and_then(Value::as_str).ok_or(SealError::ColumnMissing(DEK_ENC))?; open_dek(tk, database_id, table, id, v, dek_enc)}/// The row's DEK, from the DK.pubfn dek_of(dk: &DataKey, database_id: &str, table: &str, id: &str, data: &Map<String, Value>) -> Result<Dek, SealError> {let tk = table_key(dk, database_id, table, version_of(data)?)?; dek_of_with_table_key(&tk, database_id, table, id, data)}/// Open a stored sealed row with the DK: its clear columns and its sealed/// ones, as one row, without the blobs. An open row is refused by name: the/// caller asks [`is_sealed`] first and reads an open row as it stands.pubfn open_row(dk: &DataKey, database_id: &str, table: &str, id: &str, data: &Map<String, Value>) -> Result<Map<String, Value>, SealError> {let tk = table_key(dk, database_id, table, version_of(data)?)?; open_row_with_table_key(&tk, database_id, table, id, data)}/// [`open_row`] with the table key of the row's own version, as a window/// holds it (the Worker never holds the DK).pubfn open_row_with_table_key(tk: &Key32, database_id: &str, table: &str, id: &str, data: &Map<String, Value>) -> Result<Map<String, Value>, SealError> {let dek = dek_of_with_table_key(tk, database_id, table, id, data)?;let sealed_enc = data.get(SEALED_ENC).and_then(Value::as_str).ok_or(SealError::ColumnMissing(SEALED_ENC))?;let sealed = open_body(&dek, database_id, table, id, sealed_enc)?;letmut out: Map<String, Value> = data.iter().filter(|(k, _)| !RESERVED.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();for (column, value) in sealed {if out.contains_key(&column) {returnErr(SealError::ColumnClash(format!("{column} is both clear and sealed"))); } out.insert(column, value); }Ok(out)}#[cfg(test)]#[path = "row_tests.rs"]mod tests;