//! A login's earlier passwords, and how long the bin keeps a secret. //! //! ```text //! History::open(row, id, vmk) / history.seal(vmk, id, version) history_enc, sealed v2 as value_enc is //! history.push(old_password, until) the newest first, at most ten, no repeat //! trash_due(trashed_at, now) binned more than thirty days ago //! ``` //! //! The history is sealed by [`super::sealed_row`]'s rule into the row's own //! `history_enc` column, beside `value_enc`, under the same vault key and //! version, so it opens wherever the password does and nowhere else. use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use zeroize::Zeroizing; use super::sealed_row::{self, SealedError}; use crate::vault::seal::Vmk; /// The column a login keeps its earlier passwords in. pub const HISTORY_ENC: &str = "history_enc"; /// How many earlier passwords a login keeps. pub const HISTORY_MAX: usize = 10; /// How many days the bin keeps a secret before it is gone. pub const TRASH_DAYS: u64 = 30; /// One earlier password and when it stopped being the password. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Past { pub password: String, /// ISO-8601, when it was replaced. pub until: String, } /// A login's earlier passwords, newest first. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct History(pub Vec); impl History { /// The history a row holds; none when the row has no `history_enc`. pub fn open(row: &Map, row_id: &str, vmk: &Vmk) -> Result { match row.get(HISTORY_ENC).and_then(Value::as_str) { None | Some("") => Ok(History::default()), Some(_) => { let opened = sealed_row::open(row, row_id, vmk, HISTORY_ENC)?; serde_json::from_slice(&opened).map_err(|_| SealedError::DoesNotOpen) } } } /// Sealed for the row, at the vault's version. pub fn seal(&self, vmk: &Vmk, row_id: &str, vmk_version: u32) -> Result { let json = Zeroizing::new(serde_json::to_vec(self).map_err(|_| SealedError::NotSealed)?); sealed_row::seal(vmk, row_id, vmk_version, &json) } /// Keep `old` as replaced at `until`: newest first, the oldest past ten /// dropped. An empty password, or the one already newest, is not kept twice. pub fn push(&mut self, old: &str, until: &str) { if old.is_empty() || self.0.first().is_some_and(|newest| newest.password == old) { return; } self.0.insert(0, Past { password: old.to_string(), until: until.to_string() }); self.0.truncate(HISTORY_MAX); } } /// Whether a secret binned at `trashed_at` (UNIX seconds) is past the bin's keeping at `now`. pub fn trash_due(trashed_at: u64, now: u64) -> bool { now.saturating_sub(trashed_at) > TRASH_DAYS * 86_400 } #[cfg(test)] #[path = "history_tests.rs"] mod tests;