Cotton code
164 lines · 9.0 KB · RustRaw
//! SEALED AT ARRIVAL (e2e rulings R2, 15 Nov 2026): what the//! object writes into a sealed table itself (an assistant's MCP write, a pull//! it fetched, a lookup it filled) is sealed the moment it arrives, to a//! seal-only public key whose private half only the person's devices hold.//! The object never seals with a key it can open later, and never falls back//! to clear.//!//! ```text//! arrival secret = HKDF-SHA256(ikm=DK, salt=database_id, info="cotton-arrival-v1")  (an X25519 scalar)//! arrival public = X25519(arrival secret, 9)       the object holds it: seal_key row "arrival", { pub }//! sealed_enc     = "s1:" the row's sealed columns under a fresh DEK, exactly as a device seals them//! dek_enc        = "a1:" + the w1 wrap of (DEK || table "\n" id) to the arrival public key, its "w1:" dropped//! seal_v         = 0   (no table key wraps it yet)//! ```//!//! A change the object makes to a row it holds sealed (a pull bringing an//! event's new title) cannot be merged into the sealed half it cannot read://! it is kept beside the row as an arrival patch, the changed columns alone//! sealed exactly as above (`{"sealed_enc", "dek_enc"}`, bound to the row's//! table and id), appended to `arrival_patches` in order. A device opening the//! row folds each over its sealed half, later over earlier ([`fold_patches`]),//! and seals the row again, which drops them. A patch marked `"fill": true`//! (a lookup's details) fills only the columns the row leaves empty.//!//! A device opens such a row with the secret its DK derives, and its sweep//! seals it again under the table's key (`d1:`, the table's version), so a//! window opens it as it opens every other row. The Worker's twin is//! apps/business/src/arrival.ts; both answer//! `crates/cotton-conformance/vectors/seal/arrival.json`.use serde_json::{Map, Value};use super::keys::{hkdf, DataKey};use super::row::{self, Dek, DEK_ENC, SEALED_ENC, SEAL_V};use super::share::{open_shared_dek, wrap_dek_for_with};use super::{plain_field, SealError, NONCE_LEN};use crate::definitions::seal::SealSpec;use crate::vault::wrap::{public_of, WRAP_PREFIX};/// The HKDF info the arrival key is derived under.pub const ARRIVAL_INFO: &str = "cotton-arrival-v1";/// The prefix of an arrival row's `dek_enc`.pub const ARRIVAL_PREFIX: &str = "a1:";/// The `seal_key` row that holds the arrival public key.pub const ARRIVAL_ROW: &str = "arrival";/// An arrival row's `seal_v`: no table key wraps its DEK yet.pub const ARRIVAL_V: u32 = 0;/// Where a sealed row keeps the object's changes to it until a device folds them in.pub const ARRIVAL_PATCHES: &str = "arrival_patches";/// This person's arrival key, its secret half, from their DK.pub fn arrival_secret(dk: &DataKey, database_id: &str) -> Result<[u8; 32], SealError> {    plain_field("database", database_id)?;    Ok(*hkdf(dk, database_id, ARRIVAL_INFO)?)}/// This person's arrival key, its public half: what their object seals to.pub fn arrival_public(dk: &DataKey, database_id: &str) -> Result<[u8; 32], SealError> {    Ok(public_of(&arrival_secret(dk, database_id)?))}/// Is this stored row one the object sealed at arrival?pub fn is_arrival(data: &Map<String, Value>) -> bool {    data.get(DEK_ENC).and_then(Value::as_str).is_some_and(|dek| dek.starts_with(ARRIVAL_PREFIX))}/// `row` sealed at arrival to `arrival_pub`, with the randomness supplied:/// what the object stores (the Worker does this in TypeScript; this is the/// vectors' and the tests' twin).#[allow(clippy::too_many_arguments)]pub fn seal_arrival_with(dek: &Dek, body_nonce: &[u8; NONCE_LEN], ephemeral: &[u8; 32], wrap_nonce: &[u8; NONCE_LEN], arrival_pub: &[u8; 32], database_id: &str, table: &str, id: &str, spec: &SealSpec, data: &Map<String, Value>) -> Result<Map<String, Value>, SealError> {    let (mut clear, sealed) = row::split(spec, data)?;    let body = row::seal_body_with(body_nonce, dek, database_id, table, id, &sealed)?;    let wrapped = wrap_dek_for_with(ephemeral, wrap_nonce, arrival_pub, dek, table, id)?;    let wrapped = wrapped.strip_prefix(WRAP_PREFIX).ok_or(SealError::BadInput("a wrap without its prefix".into()))?;    clear.insert(SEALED_ENC.into(), body.into());    clear.insert(DEK_ENC.into(), format!("{ARRIVAL_PREFIX}{wrapped}").into());    clear.insert(SEAL_V.into(), ARRIVAL_V.into());    Ok(clear)}/// An arrival row's DEK, opened with the arrival secret its DK derives; refused/// unless the wrap names this table and row.pub fn arrival_dek(dk: &DataKey, database_id: &str, table: &str, id: &str, data: &Map<String, Value>) -> Result<Dek, SealError> {    let dek_enc = data.get(DEK_ENC).and_then(Value::as_str).ok_or(SealError::ColumnMissing(DEK_ENC))?;    let wrapped = dek_enc.strip_prefix(ARRIVAL_PREFIX).ok_or(SealError::DoesNotOpen)?;    open_shared_dek(&arrival_secret(dk, database_id)?, &format!("{WRAP_PREFIX}{wrapped}"), table, id)}/// An arrival row opened: its clear columns and its sealed ones as one row,/// without the blobs. A column both clear and sealed is refused by name.pub fn open_arrival(dk: &DataKey, database_id: &str, table: &str, id: &str, data: &Map<String, Value>) -> Result<Map<String, Value>, SealError> {    let dek = arrival_dek(dk, 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 = row::open_body(&dek, database_id, table, id, sealed_enc)?;    let mut out: Map<String, Value> = data.iter().filter(|(key, _)| !row::RESERVED.contains(&key.as_str())).map(|(key, value)| (key.clone(), value.clone())).collect();    for (key, value) in sealed {        if out.contains_key(&key) {            return Err(SealError::ColumnClash(format!("{key} is both clear and sealed")));        }        out.insert(key, value);    }    Ok(out)}/// A password's value saved over MCP, sealed by the object to the arrival key (keys DECISIONS.md S3, 25 Nov 2026):/// `a2:<sealed_enc>|<dek_enc>`, the value as the one sealed column `payload` of an arrival row of [`VALUE_TABLE`]/// bound to the secret's id. The object cannot open it; a device opens it here and moves it under the vault key.pub const VALUE_PREFIX: &str = "a2:";/// The table an arrival-sealed value is bound to: never a row's table, so a value never opens as a row.pub const VALUE_TABLE: &str = "secret_value";/// Is this `sealed` column a value sealed at arrival?pub fn is_arrival_value(sealed: &str) -> bool {    sealed.starts_with(VALUE_PREFIX)}/// An arrival-sealed value (`a2:`) of the secret `id`, opened: the payload text the object sealed.pub fn open_arrival_value(dk: &DataKey, database_id: &str, id: &str, sealed: &str) -> Result<String, SealError> {    let rest = sealed.strip_prefix(VALUE_PREFIX).ok_or(SealError::DoesNotOpen)?;    let (body, dek) = rest.split_once('|').ok_or(SealError::DoesNotOpen)?;    let mut data = Map::new();    data.insert(SEALED_ENC.into(), body.into());    data.insert(DEK_ENC.into(), dek.into());    data.insert(SEAL_V.into(), ARRIVAL_V.into());    let opened = open_arrival(dk, database_id, VALUE_TABLE, id, &data)?;    opened.get("payload").and_then(Value::as_str).map(str::to_string).ok_or(SealError::DoesNotOpen)}/// Does this stored row carry arrival patches a device has not folded in yet?pub fn has_patches(data: &Map<String, Value>) -> bool {    data.get(ARRIVAL_PATCHES).and_then(Value::as_array).is_some_and(|patches| !patches.is_empty())}/// `opened` (a sealed row opened: its clear and sealed columns) with the/// stored row's arrival patches folded over it, in order, later over earlier,/// and without the patches themselves. Each patch opens with the arrival/// secret, and is refused unless its wrap names this table and row.pub fn fold_patches(dk: &DataKey, database_id: &str, table: &str, id: &str, data: &Map<String, Value>, opened: Map<String, Value>) -> Result<Map<String, Value>, SealError> {    let mut out = opened;    out.remove(ARRIVAL_PATCHES);    let Some(patches) = data.get(ARRIVAL_PATCHES).and_then(Value::as_array) else { return Ok(out) };    for patch in patches {        let patch = patch.as_object().ok_or_else(|| SealError::BadInput("an arrival patch is not an object".into()))?;        let dek = arrival_dek(dk, database_id, table, id, patch)?;        let sealed_enc = patch.get(SEALED_ENC).and_then(Value::as_str).ok_or(SealError::ColumnMissing(SEALED_ENC))?;        // A fill patch (a lookup's details) fills only what the row leaves empty, never over what the person wrote.        let fill = patch.get("fill") == Some(&Value::Bool(true));        for (key, value) in row::open_body(&dek, database_id, table, id, sealed_enc)? {            if key == "id" || row::RESERVED.contains(&key.as_str()) || key == ARRIVAL_PATCHES {                return Err(SealError::ColumnClash(format!("an arrival patch carries {key}")));            }            if fill && !out.get(&key).is_none_or(|held| held.is_null() || held.as_str().is_some_and(|text| text.trim().is_empty())) {                continue;            }            out.insert(key, value);        }    }    Ok(out)}#[cfg(test)]#[path = "arrival_tests.rs"]mod tests;