Files
CustosPublic/crates/custos-vault/src/lib.rs
T

715 lines
27 KiB
Rust

//! The Custos vault: one `.custos` file, Argon2id + XChaCha20-Poly1305, documented in docs/FORMAT.md
//! (version 1) and docs/FACTORS.md (version 2: any two factors).
//!
//! ```
//! use custos_vault::{FactorKind, Item, ItemType, KdfParams, SecretString, Unlock, Vault};
//! let password = SecretString::from("Orbit7-Fable3-Quartz9-Lumen2");
//! let device_key = [7u8; 32]; // in the app: a key file only this Windows account can read
//! # let kdf = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
//! let mut vault = Vault::create_with(
//! Unlock::Password(&password), "Master password",
//! Unlock::Material(FactorKind::Device, &device_key), "This PC", kdf)?;
//! vault.add(Item::new(ItemType::WebLogin, "GitHub", custos_vault::now_ms()));
//! let bytes = vault.to_bytes()?;
//! let back = Vault::open_with(&bytes, Unlock::Password(&password), Unlock::Material(FactorKind::Device, &device_key))?;
//! assert_eq!(back.items().len(), 1);
//! # Ok::<(), custos_vault::Error>(())
//! ```
mod crypto;
mod device;
mod format;
mod item;
mod save;
mod secret;
pub use item::{Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms};
pub use save::{CrashPoint, save_atomic, save_atomic_crashing};
pub use secret::SecretString;
use crypto::KEY_LEN;
use format::{
FactorSlot, Header, ID_LEN, MAX_FACTORS, PairSlot, PasswordSlot, RawSlot, SALT_LEN, SLOT_FACTOR, SLOT_PAIR,
SLOT_PASSWORD, SingleSlot, VERSION, VERSION_2,
};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::path::Path;
use zeroize::Zeroizing;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("not a Custos vault file")]
NotAVault,
#[error("vault format version {0} is not supported by this version of Custos")]
UnsupportedVersion(u16),
#[error("the vault file is malformed")]
Malformed,
#[error("the vault's key-derivation parameters are not supported")]
UnsupportedKdf,
#[error("wrong password")]
WrongPassword,
#[error("the vault file was changed or damaged after it was written")]
Corrupted,
#[error("this device's unlock key no longer opens the vault; use the master password")]
DeviceKeyRejected,
#[error("this vault opens with two different factors")]
NeedTwoFactors,
#[error("this factor does not open the vault")]
FactorRejected,
#[error("a vault has at most 8 factors and one master password")]
TooManyFactors,
#[error("{0}")]
Io(#[from] std::io::Error),
}
/// Argon2id parameters, stored per vault (docs/FORMAT.md, "Limits").
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct KdfParams {
pub m_cost_kib: u32,
pub t_cost: u32,
pub p_cost: u32,
}
impl KdfParams {
/// 64 MiB, 20 passes, 1 lane: about 0.75 s per unlock on the dev machine (2026, release build;
/// measure with `cargo run --release -p custos-vault --example kdf_timing`).
pub const DEFAULT: KdfParams = KdfParams { m_cost_kib: 65_536, t_cost: 20, p_cost: 1 };
pub const MAX_M_COST_KIB: u32 = 2 * 1024 * 1024;
pub const MAX_T_COST: u32 = 64;
pub const MAX_P_COST: u32 = 16;
/// Refuses parameters outside the limits before any Argon2 work.
pub fn check(&self) -> Result<(), Error> {
let ok = (1..=Self::MAX_P_COST).contains(&self.p_cost)
&& (1..=Self::MAX_T_COST).contains(&self.t_cost)
&& (8 * self.p_cost..=Self::MAX_M_COST_KIB).contains(&self.m_cost_kib);
if ok { Ok(()) } else { Err(Error::UnsupportedKdf) }
}
}
impl Default for KdfParams {
fn default() -> Self {
Self::DEFAULT
}
}
/// What kind of secret a factor is (docs/FACTORS.md, "Factor KEKs").
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FactorKind {
/// The master password.
Password,
/// A key one device keeps (a DPAPI-protected key file, a key in the phone's storage).
Device,
/// A share the TOTP service releases after a valid code.
Totp,
/// A secret another paired device sends after you approve there.
Approval,
/// A WebAuthn PRF output (Face ID, Touch ID, Windows Hello passkey).
Passkey,
}
impl FactorKind {
fn code(self) -> u8 {
match self {
FactorKind::Password => 1,
FactorKind::Device => 2,
FactorKind::Totp => 3,
FactorKind::Approval => 4,
FactorKind::Passkey => 5,
}
}
fn from_code(c: u8) -> Option<Self> {
Some(match c {
1 => FactorKind::Password,
2 => FactorKind::Device,
3 => FactorKind::Totp,
4 => FactorKind::Approval,
5 => FactorKind::Passkey,
_ => return None,
})
}
}
/// One factor given to open a vault. `Debug` never prints the password or the material.
#[derive(Clone, Copy)]
pub enum Unlock<'a> {
Password(&'a SecretString),
/// Any other factor: its kind and 32..=64 bytes of material.
Material(FactorKind, &'a [u8]),
}
impl Unlock<'_> {
fn kind(&self) -> FactorKind {
match self {
Unlock::Password(_) => FactorKind::Password,
Unlock::Material(k, _) => *k,
}
}
/// Material for types 2..5 must be 32..=64 bytes, and a password is never passed as material.
fn check(&self) -> Result<(), Error> {
match self {
Unlock::Password(_) => Ok(()),
Unlock::Material(FactorKind::Password, _) => Err(Error::FactorRejected),
Unlock::Material(_, m) if (32..=64).contains(&m.len()) => Ok(()),
Unlock::Material(..) => Err(Error::FactorRejected),
}
}
}
impl fmt::Debug for Unlock<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Unlock::Password(_) => f.write_str("Password([redacted])"),
Unlock::Material(k, _) => write!(f, "Material({k:?}, [redacted])"),
}
}
}
/// A factor of an unlocked vault, as the app lists it. Never carries the factor key.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FactorInfo {
/// 32 hex digits.
pub id: String,
pub kind: FactorKind,
pub label: String,
pub created: i64,
}
/// A factor as the body keeps it: its key `F` is what lets an unlocked vault add pairs.
#[derive(Clone)]
struct FactorRec {
id: [u8; ID_LEN],
kind: FactorKind,
label: String,
created: i64,
key: Zeroizing<[u8; KEY_LEN]>,
}
#[derive(Serialize, Deserialize)]
struct FactorJson {
id: String,
#[serde(rename = "type")]
kind: FactorKind,
label: String,
created: i64,
key: SecretString,
}
fn hex(b: &[u8]) -> String {
b.iter().map(|x| format!("{x:02x}")).collect()
}
fn unhex<const N: usize>(s: &str) -> Option<[u8; N]> {
if s.len() != 2 * N {
return None;
}
let mut out = [0u8; N];
for (i, o) in out.iter_mut().enumerate() {
*o = u8::from_str_radix(s.get(2 * i..2 * i + 2)?, 16).ok()?;
}
Some(out)
}
impl FactorRec {
fn json(&self) -> FactorJson {
FactorJson {
id: hex(&self.id),
kind: self.kind,
label: self.label.clone(),
created: self.created,
key: SecretString::new(hex(self.key.as_ref())),
}
}
fn from_json(j: &FactorJson) -> Option<FactorRec> {
Some(FactorRec {
id: unhex(&j.id)?,
kind: j.kind,
label: j.label.clone(),
created: j.created,
key: Zeroizing::new(unhex(j.key.expose())?),
})
}
}
const BODY_FORMAT: u32 = 1;
const BODY_FORMAT_2: u32 = 2;
const INFO_FACTOR: &[u8] = b"custos factor v2";
const INFO_PAIR: &[u8] = b"custos pair v2";
const INFO_SINGLE: &[u8] = b"custos single v2";
#[derive(Deserialize)]
struct Body {
format: u32,
items: Vec<Item>,
#[serde(default)]
factors: Vec<FactorJson>,
}
/// What `to_bytes` serializes: borrows the items instead of cloning every secret.
#[derive(Serialize)]
struct BodyRef<'a> {
format: u32,
items: &'a [Item],
#[serde(skip_serializing_if = "Vec::is_empty")]
factors: Vec<FactorJson>,
}
/// An unlocked vault: the vault key and the decrypted items, both wiped on drop.
pub struct Vault {
key: Zeroizing<[u8; KEY_LEN]>,
version: u16,
slots: Vec<RawSlot>,
items: Vec<Item>,
/// Version 2 only.
factors: Vec<FactorRec>,
/// Argon2 parameters for a password factor added later.
kdf_new: KdfParams,
}
impl fmt::Debug for Vault {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Vault")
.field("version", &self.version)
.field("items", &self.items.len())
.field("factors", &self.factors.len())
.finish_non_exhaustive()
}
}
fn password_slot(key: &[u8; KEY_LEN], password: &SecretString, kdf: KdfParams) -> Result<PasswordSlot, Error> {
kdf.check()?;
let mut salt = [0u8; SALT_LEN];
crypto::fill_random(&mut salt);
let mut slot = PasswordSlot { kdf, salt, nonce: crypto::random_nonce(), wrapped: Vec::new() };
let kek = crypto::derive_kek(password.expose().as_bytes(), &slot.salt, kdf)?;
slot.wrapped = crypto::seal(&kek, &slot.nonce, key, &slot.aad());
Ok(slot)
}
/// The KEK a factor's material gives for one factor slot.
fn factor_kek(u: &Unlock, salt: &[u8], kdf: Option<KdfParams>) -> Result<Zeroizing<[u8; KEY_LEN]>, Error> {
match (u, kdf) {
(Unlock::Password(p), Some(k)) => crypto::derive_kek(p.expose().as_bytes(), salt, k),
(Unlock::Material(_, m), None) => Ok(crypto::hkdf(m, salt, INFO_FACTOR)),
_ => Err(Error::FactorRejected),
}
}
/// A new factor slot wrapping `key` (the factor key `F`) with `u`'s material.
fn factor_slot(id: [u8; ID_LEN], key: &[u8; KEY_LEN], u: &Unlock, kdf: KdfParams) -> Result<FactorSlot, Error> {
u.check()?;
let kdf = matches!(u, Unlock::Password(_)).then_some(kdf);
if let Some(k) = kdf {
k.check()?;
}
let mut salt = [0u8; SALT_LEN];
crypto::fill_random(&mut salt);
let mut slot = FactorSlot { id, kind: u.kind().code(), kdf, salt, nonce: crypto::random_nonce(), wrapped: Vec::new() };
let kek = factor_kek(u, &slot.salt, slot.kdf)?;
slot.wrapped = crypto::seal(&kek, &slot.nonce, key, &slot.aad());
Ok(slot)
}
fn pair_kek(a: &FactorRec, b: &FactorRec) -> Zeroizing<[u8; KEY_LEN]> {
let (x, y) = if a.id < b.id { (a, b) } else { (b, a) };
let mut ikm = Zeroizing::new([0u8; 2 * KEY_LEN]);
ikm[..KEY_LEN].copy_from_slice(x.key.as_ref());
ikm[KEY_LEN..].copy_from_slice(y.key.as_ref());
let mut salt = [0u8; 2 * ID_LEN];
salt[..ID_LEN].copy_from_slice(&x.id);
salt[ID_LEN..].copy_from_slice(&y.id);
crypto::hkdf(ikm.as_ref(), &salt, INFO_PAIR)
}
fn pair_slot(vault_key: &[u8; KEY_LEN], a: &FactorRec, b: &FactorRec) -> PairSlot {
let (x, y) = if a.id < b.id { (a.id, b.id) } else { (b.id, a.id) };
let mut slot = PairSlot { a: x, b: y, nonce: crypto::random_nonce(), wrapped: Vec::new() };
slot.wrapped = crypto::seal(&pair_kek(a, b), &slot.nonce, vault_key, &slot.aad());
slot
}
fn single_kek(f: &FactorRec) -> Zeroizing<[u8; KEY_LEN]> {
crypto::hkdf(f.key.as_ref(), &f.id, INFO_SINGLE)
}
fn key32(k: Zeroizing<Vec<u8>>) -> Result<Zeroizing<[u8; KEY_LEN]>, Error> {
Ok(Zeroizing::new(k.as_slice().try_into().map_err(|_| Error::Malformed)?))
}
/// The first factor slot of `u`'s kind that `u` unwraps: its id and factor key.
fn unwrap_factor(header: &Header, u: &Unlock) -> Result<FactorRec, Error> {
u.check()?;
for slot in header.factor_slots().into_iter().filter(|s| s.kind == u.kind().code()) {
let kek = factor_kek(u, &slot.salt, slot.kdf)?;
if let Some(k) = crypto::open(&kek, &slot.nonce, &slot.wrapped, &slot.aad()) {
return Ok(FactorRec { id: slot.id, kind: u.kind(), label: String::new(), created: 0, key: key32(k)? });
}
}
Err(if matches!(u, Unlock::Password(_)) { Error::WrongPassword } else { Error::FactorRejected })
}
impl Vault {
/// A new, empty version-1 vault with a fresh random vault key wrapped by `password`.
pub fn create(password: &SecretString, kdf: KdfParams) -> Result<Vault, Error> {
let key = crypto::random_key();
let slot = password_slot(&key, password, kdf)?;
Ok(Vault { key, version: VERSION, slots: vec![slot.raw()], items: Vec::new(), factors: Vec::new(), kdf_new: kdf })
}
/// A new, empty version-2 vault that opens with these two factors together (docs/FACTORS.md).
pub fn create_with(a: Unlock, label_a: &str, b: Unlock, label_b: &str, kdf: KdfParams) -> Result<Vault, Error> {
if a.kind() == FactorKind::Password && b.kind() == FactorKind::Password {
return Err(Error::NeedTwoFactors);
}
let mut v = Vault {
key: crypto::random_key(),
version: VERSION_2,
slots: Vec::new(),
items: Vec::new(),
factors: Vec::new(),
kdf_new: kdf,
};
v.add_factor(a, label_a)?;
v.add_factor(b, label_b)?;
Ok(v)
}
/// A machine store: a separate vault that one device key opens alone, for a program that must
/// open it unattended (the Claude Code store). Never for the user's own secrets.
pub fn create_machine_store(material: &[u8], label: &str) -> Result<Vault, Error> {
let u = Unlock::Material(FactorKind::Device, material);
u.check()?;
let key = crypto::random_key();
let mut id = [0u8; ID_LEN];
crypto::fill_random(&mut id);
let rec = FactorRec { id, kind: FactorKind::Device, label: label.into(), created: now_ms(), key: crypto::random_key() };
let fslot = factor_slot(id, &rec.key, &u, KdfParams::DEFAULT)?;
let mut single = SingleSlot { id, nonce: crypto::random_nonce(), wrapped: Vec::new() };
single.wrapped = crypto::seal(&single_kek(&rec), &single.nonce, key.as_ref(), &single.aad());
Ok(Vault {
key,
version: VERSION_2,
slots: vec![fslot.raw(), single.raw()],
items: Vec::new(),
factors: vec![rec],
kdf_new: KdfParams::DEFAULT,
})
}
pub fn open_file(path: &Path, password: &SecretString) -> Result<Vault, Error> {
Vault::open(&std::fs::read(path)?, password)
}
/// Unlocks a version-1 vault with its password. A version-2 vault needs [`Vault::open_with`].
/// Returns no data at all unless both the key slot and the body authenticate.
pub fn open(bytes: &[u8], password: &SecretString) -> Result<Vault, Error> {
let (header, body_at) = Header::parse(bytes)?;
if header.version == VERSION_2 {
return Err(Error::NeedTwoFactors);
}
let pw_slots: Vec<PasswordSlot> = header
.slots
.iter()
.filter(|s| s.kind == SLOT_PASSWORD)
.map(|s| PasswordSlot::parse(&s.payload))
.collect::<Result<_, _>>()?;
if pw_slots.is_empty() {
return Err(Error::Malformed);
}
for slot in &pw_slots {
let kek = crypto::derive_kek(password.expose().as_bytes(), &slot.salt, slot.kdf)?;
if let Some(k) = crypto::open(&kek, &slot.nonce, &slot.wrapped, &slot.aad()) {
let kdf = slot.kdf;
let mut v = Vault::open_body(bytes, header, body_at, key32(k)?)?;
v.kdf_new = kdf;
return Ok(v);
}
}
Err(Error::WrongPassword)
}
/// Unlocks a version-2 vault with two different factors, in any order (docs/FACTORS.md, "Opening").
pub fn open_with(bytes: &[u8], a: Unlock, b: Unlock) -> Result<Vault, Error> {
let (header, body_at) = Header::parse(bytes)?;
if header.version != VERSION_2 || header.is_machine_store() {
return Err(Error::NeedTwoFactors);
}
// Refuse bad material before any Argon2 work.
a.check()?;
b.check()?;
let fa = unwrap_factor(&header, &a)?;
let fb = unwrap_factor(&header, &b)?;
if fa.id == fb.id {
return Err(Error::NeedTwoFactors);
}
let (x, y) = if fa.id < fb.id { (fa.id, fb.id) } else { (fb.id, fa.id) };
let slot = header.pair_slots().into_iter().find(|p| p.a == x && p.b == y).ok_or(Error::Corrupted)?;
let k = crypto::open(&pair_kek(&fa, &fb), &slot.nonce, &slot.wrapped, &slot.aad()).ok_or(Error::Corrupted)?;
Vault::open_body(bytes, header, body_at, key32(k)?)
}
/// Opens a machine store with its one device key. A user vault is never opened this way.
pub fn open_machine_store(bytes: &[u8], material: &[u8]) -> Result<Vault, Error> {
let (header, body_at) = Header::parse(bytes)?;
if header.version != VERSION_2 || !header.is_machine_store() {
return Err(Error::NeedTwoFactors);
}
let f = unwrap_factor(&header, &Unlock::Material(FactorKind::Device, material))?;
let slot = header.single_slot().filter(|s| s.id == f.id).ok_or(Error::Corrupted)?;
let k = crypto::open(&single_kek(&f), &slot.nonce, &slot.wrapped, &slot.aad()).ok_or(Error::Corrupted)?;
Vault::open_body(bytes, header, body_at, key32(k)?)
}
/// The format version of a vault file (1 or 2), from its header alone.
pub fn version_of(bytes: &[u8]) -> Result<u16, Error> {
Ok(Header::parse(bytes)?.0.version)
}
/// The kinds of factor a vault opens with, from its header alone: what the unlock screen offers.
pub fn factor_kinds(bytes: &[u8]) -> Result<Vec<FactorKind>, Error> {
let (header, _) = Header::parse(bytes)?;
if header.version == VERSION {
return Ok(vec![FactorKind::Password]);
}
Ok(header.factor_slots().iter().filter_map(|s| FactorKind::from_code(s.kind)).collect())
}
/// The factors a vault file has, from its header (no key needed): id (32 hex digits) and type. The app
/// asks the TOTP service and paired devices for a factor by this id.
pub fn factor_ids(bytes: &[u8]) -> Result<Vec<(String, FactorKind)>, Error> {
let (header, _) = Header::parse(bytes)?;
if header.version == VERSION {
return Ok(Vec::new());
}
Ok(header.factor_slots().iter().filter_map(|s| Some((hex(&s.id), FactorKind::from_code(s.kind)?))).collect())
}
pub fn is_machine_store(bytes: &[u8]) -> Result<bool, Error> {
Ok(Header::parse(bytes)?.0.is_machine_store())
}
fn open_body(bytes: &[u8], header: Header, body_at: usize, key: Zeroizing<[u8; KEY_LEN]>) -> Result<Vault, Error> {
let json =
crypto::open(&key, &header.body_nonce, &bytes[body_at..], &bytes[..body_at]).ok_or(Error::Corrupted)?;
let body: Body = serde_json::from_slice(&json).map_err(|_| Error::Corrupted)?;
let want = if header.version == VERSION_2 { BODY_FORMAT_2 } else { BODY_FORMAT };
if body.format != want {
return Err(Error::Corrupted);
}
let factors: Vec<FactorRec> = body.factors.iter().map(FactorRec::from_json).collect::<Option<_>>().ok_or(Error::Corrupted)?;
// Every factor slot in the header has its key in the body, and the other way round.
if header.version == VERSION_2 {
let mut in_header: Vec<_> = header.factor_slots().iter().map(|s| s.id).collect();
let mut in_body: Vec<_> = factors.iter().map(|f| f.id).collect();
in_header.sort();
in_body.sort();
if in_header != in_body {
return Err(Error::Corrupted);
}
}
let kdf_new = header.factor_slots().iter().find_map(|s| s.kdf).unwrap_or(KdfParams::DEFAULT);
Ok(Vault { key, version: header.version, slots: header.slots, items: body.items, factors, kdf_new })
}
/// Wraps the vault key for device unlock with key material only this device can produce (e.g. a
/// Windows Hello signature). Version 1 only: a version-2 vault never opens with one secret.
pub fn wrap_for_device(&self, material: &[u8]) -> Result<Vec<u8>, Error> {
if self.version == VERSION_2 {
return Err(Error::NeedTwoFactors);
}
Ok(device::wrap(&self.key, material))
}
/// Unlocks with a device blob instead of the password (version 1). Fails with `DeviceKeyRejected`
/// when the material is wrong or the blob was changed, and with `Corrupted` when it belongs to another vault.
pub fn open_with_device(bytes: &[u8], blob: &[u8], material: &[u8]) -> Result<Vault, Error> {
let (header, body_at) = Header::parse(bytes)?;
if header.version == VERSION_2 {
return Err(Error::NeedTwoFactors);
}
let key = device::unwrap(blob, material)?;
Vault::open_body(bytes, header, body_at, key)
}
/// The encrypted file contents, with a fresh body nonce.
pub fn to_bytes(&self) -> Result<Vec<u8>, Error> {
let body_nonce = crypto::random_nonce();
let mut out = Header { version: self.version, slots: self.slots.clone(), body_nonce }.to_bytes();
let mut json = Zeroizing::new(Vec::with_capacity(4096 + 1024 * self.items.len()));
let v2 = self.version == VERSION_2;
let body = BodyRef {
format: if v2 { BODY_FORMAT_2 } else { BODY_FORMAT },
items: &self.items,
factors: self.factors.iter().map(FactorRec::json).collect(),
};
serde_json::to_writer(&mut *json, &body).map_err(|e| Error::Io(std::io::Error::other(e.to_string())))?;
let sealed = crypto::seal(&self.key, &body_nonce, &json, &out);
out.extend_from_slice(&sealed);
Ok(out)
}
/// Encrypts and writes the vault atomically (see [`save_atomic`]).
pub fn save(&self, path: &Path) -> Result<(), Error> {
save_atomic(path, &self.to_bytes()?)
}
/// Changes the master password. Version 1: a new password slot. Version 2: the password factor's
/// key is rewrapped, so its pairs keep working (also after a forgotten password: open with two
/// other factors, then set a new one). The old password stops working at the next save.
pub fn change_password(&mut self, new_password: &SecretString, kdf: KdfParams) -> Result<(), Error> {
if self.version == VERSION {
let slot = password_slot(&self.key, new_password, kdf)?;
self.slots.retain(|s| s.kind != SLOT_PASSWORD);
self.slots.insert(0, slot.raw());
self.kdf_new = kdf;
return Ok(());
}
if self.is_store() {
return Err(Error::FactorRejected);
}
self.kdf_new = kdf;
let Some(rec) = self.factors.iter().find(|f| f.kind == FactorKind::Password).cloned() else {
self.add_factor(Unlock::Password(new_password), "Master password")?;
return Ok(());
};
let slot = factor_slot(rec.id, &rec.key, &Unlock::Password(new_password), kdf)?;
let at = self.factor_slot_index(&rec.id).ok_or(Error::Corrupted)?;
self.slots[at] = slot.raw();
Ok(())
}
fn is_store(&self) -> bool {
self.slots.iter().any(|s| s.kind == format::SLOT_SINGLE)
}
fn factor_slot_index(&self, id: &[u8; ID_LEN]) -> Option<usize> {
self.slots.iter().position(|s| s.kind == SLOT_FACTOR && s.payload.get(..ID_LEN) == Some(&id[..]))
}
/// Adds a factor to a version-2 vault: only the new factor's material is needed (docs/FACTORS.md).
/// Returns its id. A second master password is refused; use [`Vault::change_password`].
pub fn add_factor(&mut self, u: Unlock, label: &str) -> Result<String, Error> {
if self.version != VERSION_2 {
return Err(Error::NeedTwoFactors);
}
if self.is_store() {
return Err(Error::FactorRejected);
}
u.check()?;
if self.factors.len() >= MAX_FACTORS
|| (u.kind() == FactorKind::Password && self.factors.iter().any(|f| f.kind == FactorKind::Password))
{
return Err(Error::TooManyFactors);
}
let mut id = [0u8; ID_LEN];
crypto::fill_random(&mut id);
let rec = FactorRec { id, kind: u.kind(), label: label.into(), created: now_ms(), key: crypto::random_key() };
let slot = factor_slot(id, &rec.key, &u, self.kdf_new)?;
self.slots.push(slot.raw());
for other in &self.factors {
self.slots.push(pair_slot(&self.key, &rec, other).raw());
}
self.factors.push(rec);
Ok(hex(&id))
}
/// Removes a factor (a lost phone, an old PC) and every pair it is part of. A vault keeps at least two.
pub fn remove_factor(&mut self, id: &str) -> Result<(), Error> {
let id: [u8; ID_LEN] = unhex(id).ok_or(Error::FactorRejected)?;
if !self.factors.iter().any(|f| f.id == id) {
return Err(Error::FactorRejected);
}
if self.factors.len() <= 2 {
return Err(Error::NeedTwoFactors);
}
self.factors.retain(|f| f.id != id);
self.slots.retain(|s| match s.kind {
SLOT_FACTOR => s.payload.get(..ID_LEN) != Some(&id[..]),
SLOT_PAIR => s.payload.get(..ID_LEN) != Some(&id[..]) && s.payload.get(ID_LEN..2 * ID_LEN) != Some(&id[..]),
_ => true,
});
Ok(())
}
/// Turns an unlocked version-1 vault into version 2 with its password and a second factor.
/// The vault key and the items stay; from the next save on, the password alone opens nothing.
pub fn upgrade_to_two_factors(&mut self, password: &SecretString, kdf: KdfParams, second: Unlock, label: &str) -> Result<(), Error> {
if self.version != VERSION {
return Err(Error::UnsupportedVersion(self.version));
}
if second.kind() == FactorKind::Password {
return Err(Error::NeedTwoFactors);
}
second.check()?;
self.version = VERSION_2;
self.slots.clear();
self.factors.clear();
self.kdf_new = kdf;
self.add_factor(Unlock::Password(password), "Master password")?;
self.add_factor(second, label)?;
Ok(())
}
/// The factors of a version-2 vault, oldest first. Empty for version 1.
pub fn factors(&self) -> Vec<FactorInfo> {
self.factors
.iter()
.map(|f| FactorInfo { id: hex(&f.id), kind: f.kind, label: f.label.clone(), created: f.created })
.collect()
}
/// 1 or 2.
pub fn version(&self) -> u16 {
self.version
}
/// Whether two unlocked vaults share a vault key (tests: a password change keeps the key).
#[doc(hidden)]
pub fn same_key_as(&self, other: &Vault) -> bool {
self.key[..] == other.key[..]
}
/// The KDF parameters of the (first) password slot or password factor.
pub fn kdf(&self) -> Option<KdfParams> {
self.slots.iter().find_map(|s| match s.kind {
SLOT_PASSWORD => PasswordSlot::parse(&s.payload).ok().map(|p| p.kdf),
SLOT_FACTOR => FactorSlot::parse(&s.payload).ok().and_then(|f| f.kdf),
_ => None,
})
}
pub fn items(&self) -> &[Item] {
&self.items
}
pub fn item(&self, id: &str) -> Option<&Item> {
self.items.iter().find(|i| i.id == id)
}
pub fn item_mut(&mut self, id: &str) -> Option<&mut Item> {
self.items.iter_mut().find(|i| i.id == id)
}
pub fn add(&mut self, item: Item) {
self.items.push(item);
}
/// Replaces the item with the same id, or adds it.
pub fn put(&mut self, item: Item) {
match self.item_mut(&item.id) {
Some(slot) => *slot = item,
None => self.items.push(item),
}
}
pub fn remove(&mut self, id: &str) -> Option<Item> {
let i = self.items.iter().position(|it| it.id == id)?;
Some(self.items.remove(i))
}
}