//! The retired-key chain: how a value sealed under an older version of the //! vault master key still opens after a rotation. //! //! **A ROTATION SEALS NOTHING AGAIN.** It mints version v+1, and writes ONE //! fact: key v, sealed under key v+1 ([`retire`]). A value stays at the version //! it was sealed at until it is next written, so a device that sealed at v //! while offline — and whose row arrives after the step — is not locked out of //! its own password. Re-sealing every row at the step could not cover that //! row: it did not exist yet. //! //! ```text //! kcv(key, workspace, version) //! = base64url_nopad( HKDF-SHA256(ikm = key, salt = "cotton vault kcv", //! info = workspace || 0x00 || version_be32)[..16] ) //! //! retire(old @ v, new @ v') //! under_kcv = kcv(new, workspace, v') //! wrapped = seal(new, "retired-key:" || workspace || ":" || v || ":" || under_kcv, v', old) //! ``` //! //! **A LINK IS PICKED BY THE KEY IN HAND, NEVER BY VERSION ARITHMETIC.** The //! key check value names the wrapping key without revealing it, so two //! retirements of one version under two different keys are two facts with two //! ids, and the walk follows only the one whose `under_version` and //! `under_kcv` match a key it actually holds. //! //! **A RETIRED KEY OPENS AND DOES NOTHING ELSE.** [`RetiredKeys`] has one //! method, [`RetiredKeys::open`], and no accessor that returns a [`Vmk`]: a //! retired key can never seal a new value, wrap for a device or derive a token //! key, because nothing outside this file can reach it. use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine as _; use hkdf::Hkdf; use sha2::Sha256; use zeroize::Zeroize; use super::seal::{open, seal, Vmk}; const KCV_SALT: &[u8] = b"cotton vault kcv"; const KCV_LEN: usize = 16; /// The key check value: 16 bytes that name one master key at one version of /// one workspace without revealing it. pub fn kcv(key: &Vmk, workspace_id: &str, version: u32) -> String { let mut info = Vec::with_capacity(workspace_id.len() + 5); info.extend_from_slice(workspace_id.as_bytes()); info.push(0); info.extend_from_slice(&version.to_be_bytes()); let mut out = [0u8; KCV_LEN]; Hkdf::::new(Some(KCV_SALT), key.expose()) .expand(&info, &mut out) // HKDF-SHA256 refuses only an output longer than 255 hashes. .expect("HKDF-SHA256 gives 16 bytes for any input material"); URL_SAFE_NO_PAD.encode(out) } /// One `cotton_vault_retired_keys` fact: key `version`, sealed under the key at /// `under_version` whose check value is `under_kcv`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RetiredLink { pub version: u32, pub under_version: u32, pub under_kcv: String, pub wrapped: String, } impl RetiredLink { /// The natural key the fact's id is derived from, as stored: the retired /// version and the wrapping key's check value. Two retirements of one /// version under two keys never share it. pub fn id_parts(&self, workspace_id: &str) -> [String; 3] { [ workspace_id.to_string(), self.version.to_string(), self.under_kcv.clone(), ] } } /// Retire `old` under `new`: the one fact a rotation writes. /// /// `None` only when the versions do not step forward — a link that pointed /// sideways or backwards could make the walk loop. pub fn retire( old: &Vmk, old_version: u32, new: &Vmk, new_version: u32, workspace_id: &str, ) -> Option { if new_version <= old_version { return None; } let under_kcv = kcv(new, workspace_id, new_version); let wrapped = seal( new, &link_label(workspace_id, old_version, &under_kcv), new_version, old.expose(), )?; Some(RetiredLink { version: old_version, under_version: new_version, under_kcv, wrapped, }) } /// What a link's seal is bound to: the workspace, the retired version and the /// wrapping key's check value (the wrapping version is the seal's own). fn link_label(workspace_id: &str, version: u32, under_kcv: &str) -> String { format!("retired-key:{workspace_id}:{version}:{under_kcv}") } /// Every older key a holder of the current one can reach. /// /// Built by [`RetiredKeys::walk`], and good for exactly one thing. #[derive(Default)] pub struct RetiredKeys { keys: Vec<(u32, Vmk)>, } impl std::fmt::Debug for RetiredKeys { /// The versions, never the bytes. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let versions: Vec = self.keys.iter().map(|(version, _)| *version).collect(); write!(f, "RetiredKeys({versions:?})") } } impl RetiredKeys { /// No retired key — a vault that has never rotated. pub fn none() -> RetiredKeys { RetiredKeys::default() } /// Follow the links from the key in hand to every older key it reaches. /// /// The links are a SET: each step takes every link whose `under_version` /// and `under_kcv` name a key already reached, so a chain of any length /// and a version retired under two keys both resolve. A link that does not /// open, or that does not step to an OLDER version, is skipped. pub fn walk( current: &Vmk, version: u32, workspace_id: &str, links: &[RetiredLink], ) -> RetiredKeys { let mut reached = RetiredKeys::default(); let mut frontier: Vec<(u32, Vmk)> = vec![(version, Vmk::from_bytes(*current.expose()))]; let mut taken = vec![false; links.len()]; while let Some((held_version, held)) = frontier.pop() { let held_kcv = kcv(&held, workspace_id, held_version); for (index, link) in links.iter().enumerate() { if taken[index] || link.under_version != held_version || link.under_kcv != held_kcv || link.version >= held_version { continue; } let label = link_label(workspace_id, link.version, &link.under_kcv); let Some(mut bytes) = open(&held, &label, held_version, &link.wrapped) else { continue; }; let key: Option<[u8; 32]> = bytes.as_slice().try_into().ok(); bytes.zeroize(); let Some(mut key) = key else { continue; }; taken[index] = true; frontier.push((link.version, Vmk::from_bytes(key))); reached.keys.push((link.version, Vmk::from_bytes(key))); key.zeroize(); } } reached } /// Open a value sealed at an older version. `None` when the chain holds no /// key at that version, or none of them opens it. pub fn open(&self, secret_id: &str, version: u32, sealed: &str) -> Option> { self.keys .iter() .filter(|(held, _)| *held == version) .find_map(|(_, key)| open(key, secret_id, version, sealed)) } /// Whether the chain reaches any key at this version — what a screen asks /// to tell "sealed under an older key" from "under a key this vault no /// longer has". pub fn reaches(&self, version: u32) -> bool { self.keys.iter().any(|(held, _)| *held == version) } } /// Open a value at whatever version it was sealed: the key in hand for its own /// version, the chain for an older one. pub fn open_at( current: &Vmk, held_version: u32, retired: &RetiredKeys, secret_id: &str, version: u32, sealed: &str, ) -> Option> { if version == held_version { open(current, secret_id, version, sealed) } else { retired.open(secret_id, version, sealed) } } #[cfg(test)] #[path = "chain_tests.rs"] mod tests;