Cotton code
145 lines · 5.8 KB · RustRaw
//! The data key and the keys derived from it (plan §2.1).//!//! ```text//! dk_enc  = v2(VMK, "seal_key:dk", vmk_version, DK)                    the seal_key{dk} row//! TK(t,v) = HKDF-SHA256(ikm=DK, salt=database_id, info="cotton-table-v1:" t ":" v)//! BK(t)   = HKDF-SHA256(ikm=DK, salt=database_id, info="cotton-blind-v1:" t)//! ```//!//! TK and BK are derived, never stored: a new version is a new key for free,//! and there is nothing to sync. Versions start at 1.use hkdf::Hkdf;use rand::RngCore;use sha2::Sha256;use zeroize::{Zeroizing, ZeroizeOnDrop};use super::{plain_field, SealError, NONCE_LEN};use crate::vault::seal::{open as vault_open, seal_with as vault_seal_with, Vmk};/// The id the DK is sealed under in `seal_key.dk_enc` (the aad's first half).pub const DK_SEAL_ID: &str = "seal_key:dk";/// HKDF info prefix of a table key.pub const TABLE_INFO: &str = "cotton-table-v1:";/// HKDF info prefix of a blind key.pub const BLIND_INFO: &str = "cotton-blind-v1:";/// FR's HKDF info: the root a person's own files' keys are made under (R6).pub const FILE_INFO: &str = "cotton-file-v1";/// HKDF info prefix for a table's own files root ([`table_file_root`]), then the table.pub const TABLE_FILE_INFO: &str = "cotton-table-file-v1:";/// A derived 32-byte key, wiped when it drops.pub type Key32 = Zeroizing<[u8; 32]>;/// The data key, held in memory and wiped when dropped. Not `Clone`, not/// `Serialize`; its `Debug` prints nothing of it.#[derive(ZeroizeOnDrop)]pub struct DataKey([u8; 32]);impl DataKey {    /// A fresh DK from the OS: minted ONCE per database (plan §7 step 1).    pub fn mint() -> DataKey {        let mut bytes = [0u8; 32];        rand::rngs::OsRng.fill_bytes(&mut bytes);        DataKey(bytes)    }    /// The key as it came out of `dk_enc` or a device's key store.    pub fn from_bytes(bytes: [u8; 32]) -> DataKey {        DataKey(bytes)    }    /// The bytes, borrowed, for a key store write and nothing else.    pub fn expose(&self) -> &[u8; 32] {        &self.0    }}impl std::fmt::Debug for DataKey {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.write_str("DataKey(…)")    }}/// TK(t, v): the key that wraps a row's DEK in table `t` at version `v`.pub fn table_key(dk: &DataKey, database_id: &str, table: &str, v: u32) -> Result<Key32, SealError> {    plain_field("database", database_id)?;    plain_field("table", table)?;    if v == 0 {        return Err(SealError::BadInput("seal_v starts at 1".into()));    }    hkdf(dk, database_id, &format!("{TABLE_INFO}{table}:{v}"))}/// BK(t): the key a table's blind tokens are made under.pub fn blind_key(dk: &DataKey, database_id: &str, table: &str) -> Result<Key32, SealError> {    plain_field("database", database_id)?;    plain_field("table", table)?;    hkdf(dk, database_id, &format!("{BLIND_INFO}{table}"))}/// FR: the root every file key of a person's own files is made under/// ([`super::file::person_file_key`]). Its own domain, apart from every TK and/// BK, so no unlock window (which hands TKs and BKs) ever carries it.pub fn file_root(dk: &DataKey, database_id: &str) -> Result<Key32, SealError> {    plain_field("database", database_id)?;    hkdf(dk, database_id, FILE_INFO)}/// TFR(t): the root the files a sealed table's rows keep are made under, apart from [`file_root`]:/// a message's kept chat pictures (`<database>/messages/…`, owner's decision, 22 Nov 2026). Its own/// domain, apart from every TK, BK and FR, so an unlock window that opens `t` may carry it/// ([`super::grant`] `files`) and open those files, and never a photo or any other table's.pub fn table_file_root(dk: &DataKey, database_id: &str, table: &str) -> Result<Key32, SealError> {    plain_field("database", database_id)?;    plain_field("table", table)?;    hkdf(dk, database_id, &format!("{TABLE_FILE_INFO}{table}"))}/// The table whose window opens the person's files of `kind` (`<database>/<kind>/…`), if any: only/// a message's kept pictures. Every other kind is opened under [`file_root`], which no window carries.pub fn table_of_file_kind(kind: &str) -> Option<&'static str> {    match kind {        "messages" => Some("message"),        // A person's picture (AVATAR SEAL, 27 Nov 2026): a window over people opens it.        "people" => Some("person"),        _ => None,    }}/// Whether a window over `table` hands the object that table's files root (TFR): the tables [`table_of_file_kind`]/// names, and no other.pub fn table_opens_files(table: &str) -> bool {    matches!(table, "message" | "person")}pub(super) fn hkdf(dk: &DataKey, salt: &str, info: &str) -> Result<Key32, SealError> {    let mut out = Zeroizing::new([0u8; 32]);    Hkdf::<Sha256>::new(Some(salt.as_bytes()), dk.expose())        .expand(info.as_bytes(), out.as_mut_slice())        .map_err(|_| SealError::Failed)?;    Ok(out)}/// `seal_key.dk_enc`: the DK sealed under the VMK at `vmk_version`.pub fn seal_dk(vmk: &Vmk, vmk_version: u32, dk: &DataKey) -> Result<String, SealError> {    let mut nonce = [0u8; NONCE_LEN];    rand::rngs::OsRng.fill_bytes(&mut nonce);    seal_dk_with(&nonce, vmk, vmk_version, dk)}/// [`seal_dk`] with the nonce supplied.pub fn seal_dk_with(nonce: &[u8; NONCE_LEN], vmk: &Vmk, vmk_version: u32, dk: &DataKey) -> Result<String, SealError> {    vault_seal_with(nonce, vmk, DK_SEAL_ID, vmk_version, dk.expose()).ok_or(SealError::Failed)}/// Open `dk_enc` under the VMK at the row's `vmk_version`.pub fn open_dk(vmk: &Vmk, vmk_version: u32, dk_enc: &str) -> Result<DataKey, SealError> {    let bytes = Zeroizing::new(vault_open(vmk, DK_SEAL_ID, vmk_version, dk_enc).ok_or(SealError::DoesNotOpen)?);    let array: [u8; 32] = bytes.as_slice().try_into().map_err(|_| SealError::DoesNotOpen)?;    Ok(DataKey::from_bytes(array))}#[cfg(test)]#[path = "keys_tests.rs"]mod tests;