//! The wrap-writer: which devices wait to open the vault, and the approval //! that lets one in. //! //! Every device that wants the vault publishes a `cotton_vault_keys` row with //! its X25519 public half and no `wrapped_vmk` (`vault.publishKey`, or the Mac //! importer through the object). Such a row is PENDING. A device that already //! holds the vault master key approves it: the VMK is wrapped for the row's //! public key ([`cotton_core::vault::wrap::wrap`]) and `wrapped_vmk` + //! `vmk_version` are written through the ordinary write path, so the change //! syncs up to the object like any other and the waiting device finds it on its //! next pass. Refusing a pending device removes its row. //! //! **The VMK is lent, never kept.** [`approve`] borrows it for the one wrap; the //! caller got it from its own wrap with its own private key for this call, and //! drops it after. Nothing here stores, logs or answers a key. //! //! **Device-neutral**: a phone or a Mac runs the same code over its own copy. //! //! **Rotation is not here.** An approved device is refused by [`refuse`]: to //! take one out, every secret is sealed again under a new VMK and every other //! row re-wrapped, which is a rotation's job (`vmk_version` moves on). What //! this keeps for it: each wrap names its version, and an approver holding an //! older version than the vault's current one is refused rather than handing //! out a key the vault has moved past. use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine as _; use cotton_core::vault::{wrap, Vmk}; use cotton_store::Driver; use cotton_tools::mcp::dispatch::Ctx; use cotton_tools::mcp::handlers::common::{insert_row, update_row}; use cotton_tools::mcp::writer::Retract; use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; /// The table every device's key row lives in. pub const VAULT_KEYS: &str = "cotton_vault_keys"; const VAULT_STATE: &str = "cotton_vault_state"; /// One device's key row, as the Devices list draws it. Never a key. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DeviceKey { pub id: String, pub device_id: String, /// What the device calls itself, when its row says. pub name: Option, /// [`wrap::fingerprint`] of its public half. pub fingerprint: Option, /// Its public half itself, as the row holds it (what a device asking to be let in names). pub public_key: Option, /// Whether the vault master key has been wrapped for it. pub wrapped: bool, pub vmk_version: u32, pub created_at: Option, } impl DeviceKey { /// The row as a method answers it. pub fn json(&self) -> Value { json!({ "id": self.id, "deviceId": self.device_id, "name": self.name, "fingerprint": self.fingerprint, "pending": !self.wrapped, "vmkVersion": self.vmk_version, "createdAt": self.created_at, }) } } fn workspace(id: &str) -> SqlValue { SqlValue::Text(id.to_string()) } /// Whether this copy's key table carries a `name` column. The object serves it /// (the kit's `vault_key.name`) and a copy gains it on its first pull; a /// device's own build table has none, so a fresh local copy reads no names. pub fn has_name(db: &Driver) -> Result { Ok(db .all(&format!("PRAGMA table_info(\"{VAULT_KEYS}\")"), &[]) .map_err(|error| error.to_string())? .iter() .any(|row| row.text("name") == Some("name"))) } /// Every key row of the workspace: the pending ones first, oldest first, then /// the devices already let in. pub fn keys(db: &Driver, workspace_id: &str) -> Result, String> { let name = if has_name(db)? { "name" } else { "NULL AS name" }; let rows = db .all( &format!( "SELECT id, device_id, {name}, public_key, wrapped_vmk IS NOT NULL AS wrapped, vmk_version, created_at FROM {VAULT_KEYS} WHERE workspace_id = ? ORDER BY wrapped_vmk IS NOT NULL, created_at, id" ), &[workspace(workspace_id)], ) .map_err(|error| error.to_string())?; Ok(rows .iter() .map(|row| DeviceKey { id: row.text("id").unwrap_or_default().to_string(), device_id: row.text("device_id").unwrap_or_default().to_string(), name: row.text("name").map(str::to_string), fingerprint: row.text("public_key").and_then(wrap::fingerprint), public_key: row.text("public_key").map(str::to_string), wrapped: row.int("wrapped").unwrap_or(0) != 0, vmk_version: row.int("vmk_version").unwrap_or(0) as u32, created_at: row.text("created_at").map(str::to_string), }) .collect()) } /// The vault's current key version as this copy knows it: the workspace's /// state row where it holds one (the founding device does), else the highest /// version any device has been wrapped at (what every synced copy holds). /// `None` for a vault nobody has founded. pub fn current_version(db: &Driver, workspace_id: &str) -> Result, String> { let read = |sql: &str| -> Result, String> { Ok(db .get(sql, &[workspace(workspace_id)]) .map_err(|error| error.to_string())? .and_then(|row| row.int("v"))) }; let state = read(&format!("SELECT vmk_version AS v FROM {VAULT_STATE} WHERE workspace_id = ?"))?; let wrapped = read(&format!( "SELECT MAX(vmk_version) AS v FROM {VAULT_KEYS} WHERE workspace_id = ? AND wrapped_vmk IS NOT NULL" ))?; Ok(state.max(wrapped).map(|version| version as u32)) } /// Why an approval or a refusal did not happen. Each sentence starts with its /// code, as the vault's method refusals do, so a method splits it by name. pub mod refusal { pub const NO_SUCH_DEVICE: &str = "no_such_device: no device of this vault has that id"; pub const ALREADY_APPROVED: &str = "already_approved: this device already opens the vault"; pub const STALE: &str = "vault_stale: this device holds an older vault key than the vault's \ current one, so it cannot hand it out. Unlock again."; pub const UNWRAPPABLE: &str = "unwrappable_key: this device's published key cannot receive the vault key"; pub const APPROVED_STAYS: &str = "approved_stays: a device that already opens the vault is \ taken out by rotating the vault key, not by refusing it"; pub const FOUNDED: &str = "vault_founded: another device already holds this vault's key, so a \ second one is never minted"; pub const OTHER_KEY: &str = "other_key: this device's vault row names another key than the one \ its sign-in was approved with"; pub const KEY_TAKEN: &str = "key_taken: another device's vault row already names that key"; } struct Row { id: String, public_key: String, wrapped: bool, } fn row_of(ctx: &Ctx<'_>, device_id: &str) -> Result { let row = ctx .db() .get( &format!( "SELECT id, public_key, wrapped_vmk IS NOT NULL AS wrapped FROM {VAULT_KEYS} WHERE workspace_id = ? AND device_id = ?" ), &[workspace(ctx.workspace_id), SqlValue::Text(device_id.to_string())], ) .map_err(|error| error.to_string())? .ok_or_else(|| refusal::NO_SUCH_DEVICE.to_string())?; Ok(Row { id: row.text("id").unwrap_or_default().to_string(), public_key: row.text("public_key").unwrap_or_default().to_string(), wrapped: row.int("wrapped").unwrap_or(0) != 0, }) } /// Let one pending device in: wrap `vmk` (at `version`, the version of the /// wrap the approver opened it from) for the device's published key, and /// write the wrap through `ctx`. Answers `{id, deviceId, vmkVersion}`. pub fn approve( ctx: &mut Ctx<'_>, device_id: &str, vmk: &Vmk, version: u32, ) -> Result { let row = row_of(ctx, device_id)?; if row.wrapped { return Err(refusal::ALREADY_APPROVED.to_string()); } if let Some(current) = current_version(ctx.db(), ctx.workspace_id)? { if version < current { return Err(refusal::STALE.to_string()); } } let public: [u8; 32] = URL_SAFE_NO_PAD .decode(&row.public_key) .ok() .and_then(|bytes| bytes.try_into().ok()) .ok_or_else(|| refusal::UNWRAPPABLE.to_string())?; let wrapped = wrap::wrap(&public, vmk.expose()).ok_or_else(|| refusal::UNWRAPPABLE.to_string())?; let mut patch = Map::new(); patch.insert("wrapped_vmk".into(), Value::from(wrapped)); patch.insert("vmk_version".into(), Value::from(version)); update_row(ctx, VAULT_KEYS, &row.id, patch).map_err(|failure| failure.to_string())?; Ok(json!({ "id": row.id, "deviceId": device_id, "vmkVersion": version })) } /// Let a device in BEFORE it has published its key: the key its sign-in was /// approved with (`signin.approve`, the code both screens showed vouching for /// it), wrapped and written as that device's own row, so its first pull opens /// the vault. A row it already published under the same key is approved as /// [`approve`] would; a row under another key, or the key on another device's /// row, is refused, never overwritten. Answers `{id, deviceId, vmkVersion}`. pub fn admit( ctx: &mut Ctx<'_>, device_id: &str, public_key: &str, name: Option<&str>, vmk: &Vmk, version: u32, ) -> Result { match row_of(ctx, device_id) { Ok(row) if row.public_key != public_key => return Err(refusal::OTHER_KEY.to_string()), Ok(row) if row.wrapped => return Ok(json!({ "id": row.id, "deviceId": device_id, "vmkVersion": version })), Ok(_) => return approve(ctx, device_id, vmk, version), Err(_) => {} } let taken = ctx .db() .get( &format!("SELECT id FROM {VAULT_KEYS} WHERE workspace_id = ? AND public_key = ?"), &[workspace(ctx.workspace_id), SqlValue::Text(public_key.to_string())], ) .map_err(|error| error.to_string())?; if taken.is_some() { return Err(refusal::KEY_TAKEN.to_string()); } if let Some(current) = current_version(ctx.db(), ctx.workspace_id)? { if version < current { return Err(refusal::STALE.to_string()); } } let public: [u8; 32] = URL_SAFE_NO_PAD .decode(public_key) .ok() .and_then(|bytes| bytes.try_into().ok()) .ok_or_else(|| refusal::UNWRAPPABLE.to_string())?; let wrapped = wrap::wrap(&public, vmk.expose()).ok_or_else(|| refusal::UNWRAPPABLE.to_string())?; let id = ctx.new_uuid(); let mut patch = Map::new(); patch.insert("device_id".into(), Value::from(device_id)); patch.insert("public_key".into(), Value::from(public_key)); if let Some(name) = name.filter(|_| has_name(ctx.db()).unwrap_or(false)) { patch.insert("name".into(), Value::from(name)); } patch.insert("wrapped_vmk".into(), Value::from(wrapped)); patch.insert("vmk_version".into(), Value::from(version)); insert_row(ctx, VAULT_KEYS, &id, patch).map_err(|failure| failure.to_string())?; Ok(json!({ "id": id, "deviceId": device_id, "vmkVersion": version })) } /// The version a vault's first key is at. const FOUNDING_VERSION: u32 = 1; /// Make `device_id` the first device of a vault nobody has founded: mint the /// vault master key on this device, wrap it for the device's own published /// key, write the wrap through `ctx` and drop the key. Answers `{id, deviceId, /// vmkVersion, founded}`; a device that already opens the vault answers /// `founded: false` and nothing is written, so asking on every launch is safe. /// A vault another device holds is refused rather than given a rival key. /// /// A signed-in copy founds this way on its first need (cotton-ffi's /// `vault::found_on_need`); the object keeps the first founding of a vault and /// refuses a later one `vault_founded`. A local copy founds at its key's /// publish (`founding::personal`). pub fn found(ctx: &mut Ctx<'_>, device_id: &str) -> Result { let row = row_of(ctx, device_id)?; if row.wrapped { return Ok(json!({ "id": row.id, "deviceId": device_id, "founded": false })); } if current_version(ctx.db(), ctx.workspace_id)?.is_some() { return Err(refusal::FOUNDED.to_string()); } let public: [u8; 32] = URL_SAFE_NO_PAD .decode(&row.public_key) .ok() .and_then(|bytes| bytes.try_into().ok()) .ok_or_else(|| refusal::UNWRAPPABLE.to_string())?; let vmk = Vmk::mint(); let wrapped = wrap::wrap(&public, vmk.expose()).ok_or_else(|| refusal::UNWRAPPABLE.to_string())?; let mut patch = Map::new(); patch.insert("wrapped_vmk".into(), Value::from(wrapped)); patch.insert("vmk_version".into(), Value::from(FOUNDING_VERSION)); update_row(ctx, VAULT_KEYS, &row.id, patch).map_err(|failure| failure.to_string())?; Ok(json!({ "id": row.id, "deviceId": device_id, "vmkVersion": FOUNDING_VERSION, "founded": true })) } /// Turn one pending device away: its row goes, and with it the request. A /// device already let in is not refused here (see the module header). pub fn refuse(ctx: &mut Ctx<'_>, device_id: &str) -> Result { let row = row_of(ctx, device_id)?; if row.wrapped { return Err(refusal::APPROVED_STAYS.to_string()); } ctx.writer() .map_err(|failure| failure.to_string())? .retract(VAULT_KEYS, &row.id, Retract::Relation); ctx.commit().map_err(|failure| failure.to_string())?; Ok(json!({ "id": row.id, "deviceId": device_id, "removed": true })) } #[cfg(test)] #[path = "devices_tests.rs"] mod tests;