[core] Vault and generators: Argon2id key slot + XChaCha20-Poly1305 file, atomic save, item templates, memorable/nickname/random/PIN/strict generators

This commit is contained in:
2026-10-31 10:12:57 +01:00
parent 42ddcf0287
commit eb710c3135
21 changed files with 9710 additions and 4 deletions
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "custos-vault"
description = "Custos vault file format: Argon2id + XChaCha20-Poly1305, atomic save, item model"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
argon2.workspace = true
chacha20poly1305.workspace = true
zeroize.workspace = true
rand.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
[dev-dependencies]
tempfile = "3"
@@ -0,0 +1,19 @@
//! How long one unlock takes with given Argon2id parameters (default: `KdfParams::DEFAULT`):
//! `cargo run --release -p custos-vault --example kdf_timing [m_cost_kib t_cost]`
use custos_vault::{KdfParams, SecretString, Vault};
use std::time::Instant;
fn main() {
let args: Vec<u32> = std::env::args().skip(1).filter_map(|a| a.parse().ok()).collect();
let kdf = match args[..] {
[m, t] => KdfParams { m_cost_kib: m, t_cost: t, p_cost: 1 },
_ => KdfParams::DEFAULT,
};
let pw = SecretString::from("timing only");
let bytes = Vault::create(&pw, kdf).unwrap().to_bytes().unwrap();
for _ in 0..3 {
let t = Instant::now();
Vault::open(&bytes, &pw).unwrap();
println!("{kdf:?}: unlock in {:?}", t.elapsed());
}
}
+61
View File
@@ -0,0 +1,61 @@
//! The only module that calls the cryptographic crates.
use crate::{Error, KdfParams};
use argon2::{Algorithm, Argon2, Params, Version};
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
use rand::Rng;
use rand::rand_core::UnwrapErr;
use rand::rngs::SysRng;
use zeroize::Zeroizing;
pub const KEY_LEN: usize = 32;
pub const NONCE_LEN: usize = 24;
pub const TAG_LEN: usize = 16;
/// Fills `buf` from the OS CSPRNG. Panics only if the OS has no randomness to give, where going on
/// without it would be worse.
pub fn fill_random(buf: &mut [u8]) {
UnwrapErr(SysRng).fill_bytes(buf);
}
pub fn random_key() -> Zeroizing<[u8; KEY_LEN]> {
let mut k = Zeroizing::new([0u8; KEY_LEN]);
fill_random(k.as_mut());
k
}
pub fn random_nonce() -> [u8; NONCE_LEN] {
let mut n = [0u8; NONCE_LEN];
fill_random(&mut n);
n
}
/// Argon2id(password, salt) → key-encryption key. The caller has already checked `p` against the limits.
pub fn derive_kek(password: &[u8], salt: &[u8], p: KdfParams) -> Result<Zeroizing<[u8; KEY_LEN]>, Error> {
let params = Params::new(p.m_cost_kib, p.t_cost, p.p_cost, Some(KEY_LEN)).map_err(|_| Error::UnsupportedKdf)?;
let mut kek = Zeroizing::new([0u8; KEY_LEN]);
Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
.hash_password_into(password, salt, kek.as_mut())
.map_err(|_| Error::UnsupportedKdf)?;
Ok(kek)
}
fn cipher(key: &[u8; KEY_LEN]) -> XChaCha20Poly1305 {
XChaCha20Poly1305::new_from_slice(key).expect("32-byte key")
}
fn nonce(n: &[u8; NONCE_LEN]) -> XNonce {
XNonce::try_from(&n[..]).expect("24-byte nonce")
}
pub fn seal(key: &[u8; KEY_LEN], n: &[u8; NONCE_LEN], plaintext: &[u8], aad: &[u8]) -> Vec<u8> {
cipher(key)
.encrypt(&nonce(n), Payload { msg: plaintext, aad })
.expect("encryption cannot fail for in-memory buffers")
}
/// `None` when the tag does not verify: wrong key, or changed ciphertext, nonce or AAD.
pub fn open(key: &[u8; KEY_LEN], n: &[u8; NONCE_LEN], ciphertext: &[u8], aad: &[u8]) -> Option<Zeroizing<Vec<u8>>> {
cipher(key).decrypt(&nonce(n), Payload { msg: ciphertext, aad }).ok().map(Zeroizing::new)
}
+125
View File
@@ -0,0 +1,125 @@
//! Reading and writing the header of a `.custos` file (docs/FORMAT.md, "Layout").
use crate::crypto::{KEY_LEN, NONCE_LEN, TAG_LEN};
use crate::{Error, KdfParams};
pub const MAGIC: &[u8; 6] = b"CUSTOS";
pub const VERSION: u16 = 1;
pub const MAX_SLOTS: usize = 8;
pub const SLOT_PASSWORD: u8 = 1;
const KDF_ARGON2ID: u8 = 1;
pub const SALT_LEN: usize = 32;
/// kdf(1) m(4) t(4) p(4) salt(32) nonce(24): the part of a password slot that is its own AAD.
const PW_AAD_LEN: usize = 1 + 12 + SALT_LEN + NONCE_LEN;
const PW_PAYLOAD_LEN: usize = PW_AAD_LEN + KEY_LEN + TAG_LEN;
/// One key slot as stored. Unknown kinds are kept and written back unchanged.
#[derive(Clone)]
pub struct RawSlot {
pub kind: u8,
pub payload: Vec<u8>,
}
pub struct PasswordSlot {
pub kdf: KdfParams,
pub salt: [u8; SALT_LEN],
pub nonce: [u8; NONCE_LEN],
pub wrapped: Vec<u8>,
}
impl PasswordSlot {
/// The bytes the wrapped key is authenticated against: magic ‖ version ‖ kind ‖ payload before the key.
pub fn aad(&self) -> Vec<u8> {
let mut a = Vec::with_capacity(9 + PW_AAD_LEN);
a.extend_from_slice(MAGIC);
a.extend_from_slice(&VERSION.to_le_bytes());
a.push(SLOT_PASSWORD);
a.extend_from_slice(&self.payload()[..PW_AAD_LEN]);
a
}
pub fn payload(&self) -> Vec<u8> {
let mut p = Vec::with_capacity(PW_PAYLOAD_LEN);
p.push(KDF_ARGON2ID);
p.extend_from_slice(&self.kdf.m_cost_kib.to_le_bytes());
p.extend_from_slice(&self.kdf.t_cost.to_le_bytes());
p.extend_from_slice(&self.kdf.p_cost.to_le_bytes());
p.extend_from_slice(&self.salt);
p.extend_from_slice(&self.nonce);
p.extend_from_slice(&self.wrapped);
p
}
pub fn parse(payload: &[u8]) -> Result<Self, Error> {
if payload.len() != PW_PAYLOAD_LEN {
return Err(Error::Malformed);
}
if payload[0] != KDF_ARGON2ID {
return Err(Error::UnsupportedKdf);
}
let u32_at = |i: usize| u32::from_le_bytes(payload[i..i + 4].try_into().unwrap());
let kdf = KdfParams { m_cost_kib: u32_at(1), t_cost: u32_at(5), p_cost: u32_at(9) };
kdf.check()?;
Ok(PasswordSlot {
kdf,
salt: payload[13..13 + SALT_LEN].try_into().unwrap(),
nonce: payload[13 + SALT_LEN..PW_AAD_LEN].try_into().unwrap(),
wrapped: payload[PW_AAD_LEN..].to_vec(),
})
}
pub fn raw(&self) -> RawSlot {
RawSlot { kind: SLOT_PASSWORD, payload: self.payload() }
}
}
pub struct Header {
pub slots: Vec<RawSlot>,
pub body_nonce: [u8; NONCE_LEN],
}
impl Header {
pub fn to_bytes(&self) -> Vec<u8> {
let mut h = Vec::new();
h.extend_from_slice(MAGIC);
h.extend_from_slice(&VERSION.to_le_bytes());
h.push(self.slots.len() as u8);
for s in &self.slots {
h.push(s.kind);
h.extend_from_slice(&(s.payload.len() as u16).to_le_bytes());
h.extend_from_slice(&s.payload);
}
h.extend_from_slice(&self.body_nonce);
h
}
/// Parses the header; returns it and its length (where the body starts).
pub fn parse(bytes: &[u8]) -> Result<(Header, usize), Error> {
if bytes.len() < 9 || &bytes[..6] != MAGIC {
return Err(Error::NotAVault);
}
let version = u16::from_le_bytes([bytes[6], bytes[7]]);
if version != VERSION {
return Err(Error::UnsupportedVersion(version));
}
let count = bytes[8] as usize;
if count == 0 || count > MAX_SLOTS {
return Err(Error::Malformed);
}
let mut at = 9;
let mut slots = Vec::with_capacity(count);
for _ in 0..count {
let head = bytes.get(at..at + 3).ok_or(Error::Malformed)?;
let len = u16::from_le_bytes([head[1], head[2]]) as usize;
let payload = bytes.get(at + 3..at + 3 + len).ok_or(Error::Malformed)?;
slots.push(RawSlot { kind: head[0], payload: payload.to_vec() });
at += 3 + len;
}
let body_nonce = bytes.get(at..at + NONCE_LEN).ok_or(Error::Malformed)?.try_into().unwrap();
at += NONCE_LEN;
if bytes.len() < at + TAG_LEN {
return Err(Error::Malformed);
}
Ok((Header { slots, body_nonce }, at))
}
}
+184
View File
@@ -0,0 +1,184 @@
//! Typed items and their templates (docs/FORMAT.md, "Item types and their fields").
use crate::secret::SecretString;
use serde::{Deserialize, Serialize};
use std::fmt;
/// Previous values kept per item, oldest dropped first.
pub const HISTORY_LIMIT: usize = 20;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ItemType {
WebLogin,
ApiCredential,
LocalApp,
Wifi,
SecureNote,
Card,
}
impl ItemType {
pub const ALL: [ItemType; 6] = [
ItemType::WebLogin,
ItemType::ApiCredential,
ItemType::LocalApp,
ItemType::Wifi,
ItemType::SecureNote,
ItemType::Card,
];
pub fn label(self) -> &'static str {
match self {
ItemType::WebLogin => "Web login",
ItemType::ApiCredential => "API credential",
ItemType::LocalApp => "Local app credential",
ItemType::Wifi => "Wi-Fi",
ItemType::SecureNote => "Secure note",
ItemType::Card => "Card",
}
}
/// The template: field names in display order, and whether each is secret.
pub fn template(self) -> &'static [(&'static str, bool)] {
match self {
ItemType::WebLogin => &[
("username", false),
("password", true),
("url", false),
("totp", true),
("autotype-match", false),
("autotype-sequence", false),
],
ItemType::ApiCredential => {
&[("service", false), ("key-id", false), ("secret", true), ("endpoint", false), ("expires", false)]
}
ItemType::LocalApp => &[("target", false), ("username", false), ("password", true)],
ItemType::Wifi => &[("ssid", false), ("password", true), ("security", false), ("hidden", false)],
ItemType::SecureNote => &[],
ItemType::Card => {
&[("cardholder", false), ("number", true), ("expiry", false), ("cvv", true), ("pin", true)]
}
}
}
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Field {
pub name: String,
pub value: SecretString,
#[serde(default)]
pub secret: bool,
}
impl Field {
pub fn text(name: &str, value: &str) -> Self {
Self { name: name.into(), value: value.into(), secret: false }
}
pub fn secret(name: &str, value: &str) -> Self {
Self { name: name.into(), value: value.into(), secret: true }
}
}
impl fmt::Debug for Field {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Field").field("name", &self.name).field("secret", &self.secret).finish_non_exhaustive()
}
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HistoryEntry {
pub field: String,
pub value: SecretString,
pub changed: i64,
}
impl fmt::Debug for HistoryEntry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HistoryEntry")
.field("field", &self.field)
.field("changed", &self.changed)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Item {
pub id: String,
#[serde(rename = "type")]
pub kind: ItemType,
pub title: String,
#[serde(default)]
pub fields: Vec<Field>,
#[serde(default)]
pub tags: Vec<String>,
#[serde(default)]
pub notes: SecretString,
pub created: i64,
pub modified: i64,
#[serde(default)]
pub history: Vec<HistoryEntry>,
}
impl Item {
/// A new item with every template field present and empty. `now` is Unix milliseconds.
pub fn new(kind: ItemType, title: &str, now: i64) -> Self {
Item {
id: new_id(),
kind,
title: title.into(),
fields: kind
.template()
.iter()
.map(|&(name, secret)| Field { name: name.into(), value: SecretString::default(), secret })
.collect(),
tags: Vec::new(),
notes: SecretString::default(),
created: now,
modified: now,
history: Vec::new(),
}
}
/// The first field called `name`.
pub fn field(&self, name: &str) -> Option<&Field> {
self.fields.iter().find(|f| f.name == name)
}
/// Sets the first field called `name` (adding it if missing, secret if the template says so).
/// A changed secret field keeps its previous non-empty value in `history`.
pub fn set(&mut self, name: &str, value: &str, now: i64) {
let template_secret = self.kind.template().iter().any(|&(n, s)| n == name && s);
match self.fields.iter_mut().find(|f| f.name == name) {
Some(f) if f.value.expose() == value => return,
Some(f) => {
let old = std::mem::replace(&mut f.value, value.into());
if f.secret && !old.is_empty() {
self.history.push(HistoryEntry { field: name.into(), value: old, changed: now });
let excess = self.history.len().saturating_sub(HISTORY_LIMIT);
self.history.drain(..excess);
}
}
None => self.fields.push(Field { name: name.into(), value: value.into(), secret: template_secret }),
}
self.modified = now;
}
/// Appends a field, e.g. a second `url`.
pub fn add_field(&mut self, field: Field) {
self.fields.push(field);
}
}
/// 128 random bits as 32 hex digits.
pub fn new_id() -> String {
let mut b = [0u8; 16];
crate::crypto::fill_random(&mut b);
b.iter().map(|x| format!("{x:02x}")).collect()
}
/// Now, in Unix milliseconds.
pub fn now_ms() -> i64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0)
}
+232
View File
@@ -0,0 +1,232 @@
//! The Custos vault: one `.custos` file, Argon2id + XChaCha20-Poly1305, documented in docs/FORMAT.md.
//!
//! ```
//! use custos_vault::{Item, ItemType, KdfParams, SecretString, Vault};
//! let password = SecretString::from("Orbit7-Fable3-Quartz9-Lumen2");
//! # let kdf = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
//! let mut vault = Vault::create(&password, kdf)?;
//! vault.add(Item::new(ItemType::WebLogin, "GitHub", custos_vault::now_ms()));
//! let bytes = vault.to_bytes()?;
//! assert_eq!(Vault::open(&bytes, &password)?.items().len(), 1);
//! # Ok::<(), custos_vault::Error>(())
//! ```
mod crypto;
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::{Header, PasswordSlot, RawSlot, SALT_LEN, SLOT_PASSWORD};
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("{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
}
}
const BODY_FORMAT: u32 = 1;
#[derive(Deserialize)]
struct Body {
format: u32,
items: Vec<Item>,
}
/// What `to_bytes` serializes: borrows the items instead of cloning every secret.
#[derive(Serialize)]
struct BodyRef<'a> {
format: u32,
items: &'a [Item],
}
/// An unlocked vault: the vault key and the decrypted items, both wiped on drop.
pub struct Vault {
key: Zeroizing<[u8; KEY_LEN]>,
slots: Vec<RawSlot>,
items: Vec<Item>,
}
impl fmt::Debug for Vault {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Vault").field("items", &self.items.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)
}
impl Vault {
/// A new, empty 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, slots: vec![slot.raw()], items: Vec::new() })
}
pub fn open_file(path: &Path, password: &SecretString) -> Result<Vault, Error> {
Vault::open(&std::fs::read(path)?, password)
}
/// Unlocks a vault. 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)?;
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 key: Zeroizing<[u8; KEY_LEN]> =
Zeroizing::new(k.as_slice().try_into().map_err(|_| Error::Malformed)?);
return Vault::open_body(bytes, header, body_at, key);
}
}
Err(Error::WrongPassword)
}
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)?;
if body.format != BODY_FORMAT {
return Err(Error::Corrupted);
}
Ok(Vault { key, slots: header.slots, items: body.items })
}
/// 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 { slots: self.slots.clone(), body_nonce }.to_bytes();
let mut json = Zeroizing::new(Vec::with_capacity(4096 + 1024 * self.items.len()));
let body = BodyRef { format: BODY_FORMAT, items: &self.items };
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()?)
}
/// Wraps the same vault key with a new password (new salt and nonce). The items are untouched;
/// the old password stops working at the next save.
pub fn change_password(&mut self, new_password: &SecretString, kdf: KdfParams) -> Result<(), Error> {
let slot = password_slot(&self.key, new_password, kdf)?;
self.slots.retain(|s| s.kind != SLOT_PASSWORD);
self.slots.insert(0, slot.raw());
Ok(())
}
/// 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.
pub fn kdf(&self) -> Option<KdfParams> {
self.slots
.iter()
.filter(|s| s.kind == SLOT_PASSWORD)
.find_map(|s| PasswordSlot::parse(&s.payload).ok())
.map(|s| s.kdf)
}
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))
}
}
+90
View File
@@ -0,0 +1,90 @@
//! Atomic save (docs/FORMAT.md, "Saving").
use crate::Error;
use std::ffi::OsString;
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
/// Where `save_atomic_crashing` stops, as if the process died there.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CrashPoint {
MidTempWrite,
AfterTempWrite,
MidBackup,
AfterBackup,
}
/// Writes `bytes` to `path` so that a crash at any moment leaves either the previous file or the new one
/// in place, and keeps the previous version as `<path>.bak`.
pub fn save_atomic(path: &Path, bytes: &[u8]) -> Result<(), Error> {
save(path, bytes, None)
}
/// `save_atomic` that stops at `crash` with an error, for the crash tests.
#[doc(hidden)]
pub fn save_atomic_crashing(path: &Path, bytes: &[u8], crash: CrashPoint) -> Result<(), Error> {
save(path, bytes, Some(crash))
}
fn sibling(path: &Path, suffix: &str) -> PathBuf {
let mut name: OsString = path.file_name().unwrap_or_default().to_owned();
name.push(suffix);
path.with_file_name(name)
}
fn crashed(at: CrashPoint) -> Error {
Error::Io(std::io::Error::other(format!("simulated crash at {at:?}")))
}
/// Writes and fsyncs `path`; with `half`, writes only the first half and "crashes".
fn write_synced(path: &Path, bytes: &[u8], half: Option<CrashPoint>) -> Result<(), Error> {
let mut f = File::create(path)?;
if let Some(at) = half {
f.write_all(&bytes[..bytes.len() / 2])?;
return Err(crashed(at));
}
f.write_all(bytes)?;
f.sync_all()?;
Ok(())
}
/// `rename` that replaces the target. On Windows a sync client or a virus scanner can hold the target
/// open for a moment, so this retries for about two seconds before giving up.
fn replace(from: &Path, to: &Path) -> Result<(), Error> {
let mut tries = 0;
loop {
match std::fs::rename(from, to) {
Ok(()) => return Ok(()),
Err(e) if tries < 20 && e.kind() == std::io::ErrorKind::PermissionDenied => {
tries += 1;
std::thread::sleep(std::time::Duration::from_millis(100));
}
Err(e) => return Err(e.into()),
}
}
}
fn save(path: &Path, bytes: &[u8], crash: Option<CrashPoint>) -> Result<(), Error> {
let at = |p: CrashPoint| (crash == Some(p)).then_some(p);
let tmp = sibling(path, ".tmp");
write_synced(&tmp, bytes, at(CrashPoint::MidTempWrite))?;
if let Some(p) = at(CrashPoint::AfterTempWrite) {
return Err(crashed(p));
}
if path.exists() {
let old = std::fs::read(path)?;
let bak_tmp = sibling(path, ".bak.tmp");
write_synced(&bak_tmp, &old, at(CrashPoint::MidBackup))?;
replace(&bak_tmp, &sibling(path, ".bak"))?;
}
if let Some(p) = at(CrashPoint::AfterBackup) {
return Err(crashed(p));
}
replace(&tmp, path)?;
#[cfg(unix)]
if let Some(dir) = path.parent() {
File::open(dir)?.sync_all()?;
}
Ok(())
}
+59
View File
@@ -0,0 +1,59 @@
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use zeroize::Zeroizing;
/// A string that is wiped from memory when dropped and never printed.
/// `Debug` and `Display` give `[redacted]`; read it with [`SecretString::expose`].
#[derive(Clone, Default, PartialEq, Eq)]
pub struct SecretString(Zeroizing<String>);
impl SecretString {
pub fn new(s: String) -> Self {
Self(Zeroizing::new(s))
}
/// The plaintext. Keep the borrow short and do not copy it into ordinary `String`s.
pub fn expose(&self) -> &str {
&self.0
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl From<&str> for SecretString {
fn from(s: &str) -> Self {
Self::new(s.to_owned())
}
}
impl From<String> for SecretString {
fn from(s: String) -> Self {
Self::new(s)
}
}
impl fmt::Debug for SecretString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
impl fmt::Display for SecretString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
impl Serialize for SecretString {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&self.0)
}
}
impl<'de> Deserialize<'de> for SecretString {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
String::deserialize(d).map(Self::new)
}
}