//! The unlock grant (plan §3.1, §3.2 step 4-5): the keys a phone hands the //! Worker for one window, wrapped to the request's ephemeral key and signed by //! the person key. //! //! ```text //! bundle = canonical JSON {"blind": {t: b64url BK(t)}, //! "keys": {t: {"": b64url TK(t,v)} for every v in 1..=seal_v(t)}, //! "request_id": …, "token_id": …, //! "files": {t: b64url TFR(t)} only for a table whose rows keep files a //! window opens: "message", "person" (keys::table_opens_files)} //! wrapped = w1(worker_pub, bundle) (crate::vault::wrap) //! statement = "cotton-unlock-v1\n" database_id "\n" request_id "\n" token_id "\n" //! sorted(tables) joined "," "\n" minutes "\n" hex(sha256(wrapped)) //! sig = b64url Ed25519(person key, statement); signer = the person key's fingerprint //! ``` //! //! `blind` sits beside `keys`, not inside it, so a table named `blind` cannot //! collide with it. Minutes are one of [`DURATIONS`] (15 minutes, an hour, a //! day, or 0: [`STANDING`], until the person turns it off; ruling R4, 15 Nov //! 2026); the Worker stamps `ends_at` on its own clock from them, a standing //! grant the far sentinel. use std::collections::BTreeMap; use rand::RngCore; use serde_json::{json, Map, Value}; use zeroize::Zeroizing; use super::keys::{blind_key, table_file_root, table_key, DataKey, Key32}; use super::{b64, canonical_json, plain_field, sha256_hex, unb64, SealError, NONCE_LEN}; use crate::keys::person::{self, PersonKey}; use crate::vault::wrap::{unwrap, wrap_with}; pub const UNLOCK_CONTEXT: &str = "cotton-unlock-v1"; /// The windows a person may allow, in minutes: 15 minutes, an hour, a day, /// and [`STANDING`]. pub const DURATIONS: [u32; 4] = [15, 60, 1440, 0]; /// A standing grant: open until the person ends it. pub const STANDING: u32 = 0; /// The longest timed window, in minutes (a day). pub const MAX_MINUTES: u32 = 1440; /// The opened bundle: what the Worker holds for the window. Its `Debug` names /// tables and versions, never a key. pub struct GrantBundle { pub request_id: String, pub token_id: String, /// TK by table, then by version. pub keys: BTreeMap>, /// BK by table. pub blind: BTreeMap, /// TFR by table, for the tables whose kept files a window opens (a message's chat pictures). pub files: BTreeMap, } impl std::fmt::Debug for GrantBundle { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let versions: BTreeMap<&String, Vec<&u32>> = self.keys.iter().map(|(t, vs)| (t, vs.keys().collect())).collect(); f.debug_struct("GrantBundle").field("request_id", &self.request_id).field("token_id", &self.token_id).field("versions", &versions).field("files", &self.files.keys().collect::>()).finish() } } impl GrantBundle { /// The tables this bundle opens, sorted. pub fn tables(&self) -> Vec { self.keys.keys().cloned().collect() } } /// What the phone posts as `unlock_grant`'s key fields. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Grant { /// Sorted, de-duplicated. pub tables: Vec, pub minutes: u32, pub wrapped: String, pub signer: String, pub sig: String, } /// The sorted, de-duplicated tables, each checked. fn sorted_tables(tables: impl IntoIterator>) -> Result, SealError> { let mut out: Vec = Vec::new(); for table in tables { plain_field("table", table.as_ref())?; out.push(table.as_ref().to_string()); } out.sort(); out.dedup(); if out.is_empty() { return Err(SealError::BadInput("a grant names at least one table".into())); } Ok(out) } fn check_minutes(minutes: u32) -> Result<(), SealError> { if !DURATIONS.contains(&minutes) { return Err(SealError::BadInput(format!("minutes {minutes} is not one of {DURATIONS:?}"))); } Ok(()) } /// The bytes the person key signs. pub fn unlock_statement(database_id: &str, request_id: &str, token_id: &str, tables: &[String], minutes: u32, wrapped: &str) -> Result, SealError> { plain_field("database", database_id)?; plain_field("request", request_id)?; plain_field("token", token_id)?; check_minutes(minutes)?; let tables = sorted_tables(tables)?; Ok(format!("{UNLOCK_CONTEXT}\n{database_id}\n{request_id}\n{token_id}\n{}\n{minutes}\n{}", tables.join(","), sha256_hex(wrapped.as_bytes())).into_bytes()) } /// The bundle for `tables`, each with its CURRENT `seal_v`: every TK from 1 up /// to it (older rows stay sealed under older versions), and the BK. pub fn bundle(dk: &DataKey, database_id: &str, request_id: &str, token_id: &str, tables: &[(String, u32)]) -> Result { let mut keys = BTreeMap::new(); let mut blind = BTreeMap::new(); let mut files = BTreeMap::new(); for (table, current) in tables { if *current == 0 { return Err(SealError::BadInput(format!("{table} has seal_v 0; versions start at 1"))); } let versions = (1..=*current).map(|v| Ok((v, table_key(dk, database_id, table, v)?))).collect::, SealError>>()?; keys.insert(table.clone(), versions); blind.insert(table.clone(), blind_key(dk, database_id, table)?); if super::keys::table_opens_files(table) { files.insert(table.clone(), table_file_root(dk, database_id, table)?); } } Ok(GrantBundle { request_id: request_id.into(), token_id: token_id.into(), keys, blind, files }) } /// The bundle's canonical text: what is wrapped. pub fn bundle_json(bundle: &GrantBundle) -> Zeroizing { let keys: Map = bundle .keys .iter() .map(|(t, vs)| (t.clone(), Value::Object(vs.iter().map(|(v, k)| (v.to_string(), Value::String(b64(k.as_slice())))).collect()))) .collect(); let blind: Map = bundle.blind.iter().map(|(t, k)| (t.clone(), Value::String(b64(k.as_slice())))).collect(); let mut whole = json!({ "request_id": bundle.request_id, "token_id": bundle.token_id, "keys": keys, "blind": blind }); // Said only when there are any, so a grant for other tables is byte for byte what it was. if !bundle.files.is_empty() { whole["files"] = Value::Object(bundle.files.iter().map(|(t, k)| (t.clone(), Value::String(b64(k.as_slice())))).collect()); } Zeroizing::new(canonical_json(&whole)) } fn key32(value: &Value) -> Result { let bytes = Zeroizing::new(value.as_str().and_then(unb64).ok_or(SealError::DoesNotOpen)?); let array: [u8; 32] = bytes.as_slice().try_into().map_err(|_| SealError::DoesNotOpen)?; Ok(Zeroizing::new(array)) } /// Read a bundle's text back. pub fn parse_bundle(text: &[u8]) -> Result { let value: Value = serde_json::from_slice(text).map_err(|_| SealError::DoesNotOpen)?; let field = |k: &str| value.get(k).and_then(Value::as_str).map(str::to_string).ok_or(SealError::DoesNotOpen); let mut keys = BTreeMap::new(); for (table, versions) in value.get("keys").and_then(Value::as_object).ok_or(SealError::DoesNotOpen)? { let mut by_v = BTreeMap::new(); for (v, key) in versions.as_object().ok_or(SealError::DoesNotOpen)? { by_v.insert(v.parse::().map_err(|_| SealError::DoesNotOpen)?, key32(key)?); } keys.insert(table.clone(), by_v); } let mut blind = BTreeMap::new(); for (table, key) in value.get("blind").and_then(Value::as_object).ok_or(SealError::DoesNotOpen)? { blind.insert(table.clone(), key32(key)?); } let mut files = BTreeMap::new(); for (table, key) in value.get("files").and_then(Value::as_object).into_iter().flatten() { files.insert(table.clone(), key32(key)?); } Ok(GrantBundle { request_id: field("request_id")?, token_id: field("token_id")?, keys, blind, files }) } /// Build the grant on the phone: bundle, wrap to the request's `worker_pub`, /// sign the statement. The ephemeral scalar and the nonce come from the OS. #[allow(clippy::too_many_arguments)] pub fn build_grant(dk: &DataKey, database_id: &str, request_id: &str, token_id: &str, tables: &[(String, u32)], minutes: u32, worker_pub: &[u8; 32], person: &PersonKey) -> Result { let mut ephemeral = Zeroizing::new([0u8; 32]); let mut nonce = [0u8; NONCE_LEN]; rand::rngs::OsRng.fill_bytes(ephemeral.as_mut_slice()); rand::rngs::OsRng.fill_bytes(&mut nonce); build_grant_with(&ephemeral, &nonce, dk, database_id, request_id, token_id, tables, minutes, worker_pub, person) } /// [`build_grant`] with the randomness supplied. #[allow(clippy::too_many_arguments)] pub fn build_grant_with(ephemeral: &[u8; 32], nonce: &[u8; NONCE_LEN], dk: &DataKey, database_id: &str, request_id: &str, token_id: &str, tables: &[(String, u32)], minutes: u32, worker_pub: &[u8; 32], person: &PersonKey) -> Result { check_minutes(minutes)?; let names = sorted_tables(tables.iter().map(|(t, _)| t))?; if names.len() != tables.len() { return Err(SealError::BadInput("a table is named twice".into())); } let bundle = bundle(dk, database_id, request_id, token_id, tables)?; let wrapped = wrap_with(ephemeral, nonce, worker_pub, bundle_json(&bundle).as_bytes()).ok_or(SealError::BadInput("worker_pub is not a usable X25519 key".into()))?; let statement = unlock_statement(database_id, request_id, token_id, &names, minutes, &wrapped)?; Ok(Grant { tables: names, minutes, wrapped, signer: person.fingerprint(), sig: b64(&person.sign(&statement)) }) } /// Does the grant verify as signed by `person_public_key` for this request /// and token? Checks the signer fingerprint too. pub fn verify_grant(person_public_key: &str, database_id: &str, request_id: &str, token_id: &str, grant: &Grant) -> bool { if person::fingerprint(person_public_key).as_deref() != Some(grant.signer.as_str()) { return false; } let Ok(statement) = unlock_statement(database_id, request_id, token_id, &grant.tables, grant.minutes, &grant.wrapped) else { return false; }; let Some(sig) = unb64(&grant.sig) else { return false; }; person::verify(person_public_key, &statement, &sig) } /// Open the wrapped bundle with the request's ephemeral private half, on the /// Worker. Refused unless it names this request and token and opens exactly /// the grant's tables. pub fn open_grant(worker_secret: &[u8; 32], request_id: &str, token_id: &str, tables: &[String], wrapped: &str) -> Result { let text = Zeroizing::new(unwrap(worker_secret, wrapped).ok_or(SealError::DoesNotOpen)?); let bundle = parse_bundle(&text)?; if bundle.request_id != request_id || bundle.token_id != token_id { return Err(SealError::DoesNotOpen); } let want = sorted_tables(tables)?; if bundle.tables() != want || bundle.blind.keys().cloned().collect::>() != want { return Err(SealError::DoesNotOpen); } Ok(bundle) } #[cfg(test)] #[path = "grant_tests.rs"] mod tests;