//! The one rule for a value a device seals into a row of the object. //! //! ```text //! seal (vmk, row_id, vmk_version, bytes) → "v2:…" the column's text; the row's vmk_version beside it //! open (row, row_id, vmk, column) → bytes opened under the row's OWN vmk_version //! ``` //! //! The scheme is the vault's `v2` ([`crate::vault::seal`]): the row id and the //! key version are the associated data, so a sealed value copied into another //! row, or left behind by a rotation, does not open. The version is the row's //! own `vmk_version` column, written beside the sealed one, so the opener never //! guesses it, and a row without it is refused by name rather than opened //! under a version picked for it. //! //! A passkey's private scalar ([`super::passkey_row`], `private_key_enc`) and //! a password's payload ([`super::password_row`], `value_enc`) are both sealed //! by this rule: one rule, so the two can never drift apart. Only a device //! holding the VMK seals or opens; the Worker stores the sealed text and holds //! no key that opens it. use serde_json::{Map, Value}; use zeroize::Zeroizing; use crate::vault::seal::{open as open_sealed, seal as seal_value, Vmk}; /// The column a sealed row keeps its key version in. pub const VMK_VERSION: &str = "vmk_version"; /// Why a sealed column did not seal or open, in words. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum SealedError { #[error("the value could not be sealed")] NotSealed, #[error("the value does not open with this vault key")] DoesNotOpen, #[error("the row has no {0}")] MissingColumn(&'static str), } /// Seal `bytes` for the row `row_id` under the VMK at `vmk_version`: the /// `v2:` text the sealed column holds. pub fn seal(vmk: &Vmk, row_id: &str, vmk_version: u32, bytes: &[u8]) -> Result { seal_value(vmk, row_id, vmk_version, bytes).ok_or(SealedError::NotSealed) } /// The row's own key version: a whole number, required. pub fn version_of(row: &Map) -> Result { let value = row.get(VMK_VERSION).filter(|value| !value.is_null()).ok_or(SealedError::MissingColumn(VMK_VERSION))?; value .as_u64() .or_else(|| value.as_f64().filter(|n| n.fract() == 0.0 && *n >= 0.0).map(|n| n as u64)) .and_then(|n| u32::try_from(n).ok()) .ok_or(SealedError::MissingColumn(VMK_VERSION)) } /// Open the sealed `column` of the row `row_id` under the VMK at the row's /// own version. The bytes are wiped when the answer drops. pub fn open(row: &Map, row_id: &str, vmk: &Vmk, column: &'static str) -> Result>, SealedError> { let version = version_of(row)?; let sealed = row.get(column).and_then(Value::as_str).ok_or(SealedError::MissingColumn(column))?; open_sealed(vmk, row_id, version, sealed).map(Zeroizing::new).ok_or(SealedError::DoesNotOpen) } #[cfg(test)] #[path = "sealed_row_tests.rs"] mod tests;