//! Sealed tables: the row seal, the blind index and the keys a time-boxed//! unlock hands the Worker (the build plan "Sealed tables with a time-boxed//! unlock", §2-§6).//!//! ```text//! VMK (vault master key, presence-gated, never in a window)//! └─ DK data key, 32 B per database seal_key{dk}.dk_enc = v2(VMK, "seal_key:dk", vmk_version, DK)//! ├─ TK(t,v) = HKDF(DK, salt=database_id, "cotton-table-v1:" t ":" v) wraps each row's DEK//! ├─ BK(t) = HKDF(DK, salt=database_id, "cotton-blind-v1:" t) makes blind tokens//! └─ DEK 32 B random per row seals the row's sealed columns as one padded blob//! ```//!//! **This module is PURE**, as [`crate::vault`] is: bytes in, bytes out. Every//! call that reaches for the OS random source has a `*_with` sibling that takes//! the bytes, so the vectors under `crates/cotton-conformance/vectors/seal`//! are exact text the TypeScript twin reads too.//!//! **No fallback to clear.** A missing key, a missing version or a blob that//! does not open is a [`SealError`] with a name ([`SealError::code`]), never an//! empty row and never the row's clear half passed off as the whole of it.pubmod agent;pubmod allowlist;pubmod arrival;pubmod arrival_file;pubmod blind;pubmod file;mod canonical;pubmod grant;pubmod keys;pubmod row;pubmod rule;pubmod set;pubmod share;pubmod shared_album;pubmod shared_roster;pubmod shared_list;pubuse canonical::canonical_json;pubuse keys::{blind_key, open_dk, seal_dk, table_key, DataKey};pubuse row::{open_row, seal_row, Dek};/// Why something did not seal or open, by name. The code is what a Worker/// answer, a parked row or a log line carries.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pubenumSealError {/// No key for this: the DK is not cached, a window holds no TK for the/// table's version, or no BK for the table. #[error("seal_key_missing: no key for {0}")]KeyMissing(String),/// A wrong key, a wrong row, a wrong version, a wrong database or a/// tampered blob. Deliberately one answer: telling them apart is an oracle. #[error("seal_does_not_open")]DoesNotOpen,/// A sealed row without its `seal_v`, `sealed_enc` or `dek_enc`. #[error("seal_column_missing: the row has no {0}")]ColumnMissing(&'static str),/// A row handed to the sealer already carries a column only the sealer/// writes, or opens to a column its clear half also holds. #[error("seal_column_clash: {0}")]ColumnClash(String),/// An input the format cannot carry unambiguously (a table name with a/// separator in it, minutes outside 1..=15, a version of 0). #[error("seal_bad_input: {0}")]BadInput(String),/// The cipher refused (it never does for 32-byte keys; named anyway). #[error("seal_failed")]Failed,}implSealError {/// The refusal's name, without its detail.pubfn code(&self) -> &'static str {matchself {SealError::KeyMissing(_) => "seal_key_missing",SealError::DoesNotOpen => "seal_does_not_open",SealError::ColumnMissing(_) => "seal_column_missing",SealError::ColumnClash(_) => "seal_column_clash",SealError::BadInput(_) => "seal_bad_input",SealError::Failed => "seal_failed", } }}/// AES-256-GCM's nonce length, everywhere in this module.pubconst NONCE_LEN: usize = 12;/// The object's table that holds the DK wrap (`dk`) and each sealed table's/// current `seal_v` (`v:<table>`): every app pulls it, whatever its kit.pubconst SEAL_KEY_TABLE: &str = "seal_key";const TAG_LEN: usize = 16;/// `nonce || AES-256-GCM(key, nonce, msg, aad)`.fn gcm_seal(key: &[u8; 32], nonce: &[u8; NONCE_LEN], msg: &[u8], aad: &[u8]) -> Result<Vec<u8>, SealError> {use aes_gcm::aead::{Aead, Payload};use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce};let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key));let ct = cipher.encrypt(Nonce::from_slice(nonce), Payload { msg, aad }).map_err(|_| SealError::Failed)?;letmut out = Vec::with_capacity(NONCE_LEN + ct.len()); out.extend_from_slice(nonce); out.extend_from_slice(&ct);Ok(out)}/// Open `nonce || ciphertext` sealed by [`gcm_seal`].fn gcm_open(key: &[u8; 32], body: &[u8], aad: &[u8]) -> Result<Vec<u8>, SealError> {use aes_gcm::aead::{Aead, Payload};use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce};if body.len() < NONCE_LEN + TAG_LEN {returnErr(SealError::DoesNotOpen); }let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key)); cipher .decrypt(Nonce::from_slice(&body[..NONCE_LEN]), Payload { msg: &body[NONCE_LEN..], aad }) .map_err(|_| SealError::DoesNotOpen)}/// Lowercase hex of SHA-256.fn sha256_hex(bytes: &[u8]) -> String {use sha2::{Digest, Sha256}; hex::encode(Sha256::digest(bytes))}fn b64(bytes: &[u8]) -> String {use base64::Engineas _; base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)}fn unb64(text: &str) -> Option<Vec<u8>> {use base64::Engineas _; base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(text).ok()}/// A field of a newline-joined statement or a `|`-joined aad may not hold the/// separators, or two different inputs would make the same bytes.fn plain_field(what: &str, value: &str) -> Result<(), SealError> {if value.is_empty() || value.contains(['\n', '|', ',']) {returnErr(SealError::BadInput(format!("{what} {value:?} is empty or holds a separator"))); }Ok(())}#[cfg(test)]#[path = "fixtures_tests.rs"]mod fixtures_tests;#[cfg(test)]#[path = "vectors_tests.rs"]mod vectors_tests;