store: serialize vault mutations and write unique temp files (M9)

This commit is contained in:
raucao committed 2026-11-30 10:31:00 +04:00
1 parent 0f983ff558
commit b4fe138641
5 files changed
+191 -54

No files matched your search

+12 -2
View File
@@ -782,11 +782,21 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
## The key vault (M8)
- **One file, `keys.json`**, at `glib::user_data_dir()/org.kosmos.raucao.Regent/`
(mode **0600**, atomic temp+rename via `write_private`, a corrupt file moved to
`keys.json.corrupt`). It holds `version`, an optional plaintext `device` nsec,
(mode **0600**, written atomically to a **unique** `tempfile::NamedTempFile`
and renamed over the target, a corrupt file moved to a timestamped
`keys.json.corrupt.<secs>.<nanos>` so a second corruption does not erase the
first). It holds `version`, an optional plaintext `device` nsec,
and `keys: [{pubkey, name, ncryptsec}]`. There is **no Secret Service and no
`oo7`** dependency: the login keyring was never at-rest protection (unlocked at
login for the whole session, keyed off the login password).
- **Vault mutations are serialized (M9).** `add_user_key` and `change_passphrase`
hold a `tokio::sync::Mutex` (`writes`) across their whole body, because each
encrypts and then updates state — interleaved, they could write a key under the
old passphrase beside keys re-encrypted under the new one, producing a vault no
passphrase opens. `save()` additionally holds a `std::sync::Mutex`
(`save_lock`, never across an `await`) across read-clone → write → rename, and
the temp file is unique, so concurrent saves cannot collide on a shared
`keys.json.tmp`. (`profiles.json` uses the same unique-temp write.)
- **Identity keys are NIP-49 `ncryptsec`** (`log_n = 16`, rust-nostr's
`MAX_LOG_N = 18` caps a tampered entry), all under **one global passphrase**.
The `pubkey` is stored beside the ciphertext so `list_user_keys` and the
Generated
+1
View File
@@ -2023,6 +2023,7 @@ dependencies = [
"reqwest",
"serde",
"serde_json",
"tempfile",
"tokio",
"url",
"zeroize",
+3
View File
@@ -40,6 +40,9 @@ base64 = "0.22"
# timeout counts time spent suspended (`Instant` is `CLOCK_MONOTONIC`, which
# stops during suspend). See `store::keys::boottime`.
libc = "0.2"
# Unique, mode-0600 temp files for the atomic vault write, so concurrent saves
# cannot collide on a fixed `keys.json.tmp` path (M9).
tempfile = "3"
qrcode = { version = "0.14", features = ["image"] }
image = { version = "0.25", default-features = false, features = ["png"] }
+147 -31
View File
@@ -97,6 +97,14 @@ pub struct KeyStore {
/// [`boottime`] (seconds since boot, including suspend), not an `Instant`,
/// so a machine that sleeps through the timeout still locks on resume.
unlocked_at: Mutex<Option<Duration>>,
/// Serializes the mutations that can interleave into a mixed-passphrase
/// vault: `add_user_key` and `change_passphrase` both encrypt, then update
/// state and save. Held across their `spawn_blocking` awaits (M9).
writes: tokio::sync::Mutex<()>,
/// Serializes the read-clone → write → rename in [`KeyStore::save`], so the
/// last writer always has the newest state snapshot. Never held across an
/// await: `save` is synchronous.
save_lock: Mutex<()>,
}
impl KeyStore {
@@ -127,7 +135,7 @@ impl KeyStore {
Ok(vault) => vault,
Err(error) => {
eprintln!("regent: moving unreadable {} aside: {error}", path.display());
let _ = std::fs::rename(&path, path.with_extension("json.corrupt"));
let _ = std::fs::rename(&path, corrupt_path(&path));
Vault::default()
}
},
@@ -155,6 +163,8 @@ impl KeyStore {
}),
unlocked: Mutex::new(None),
unlocked_at: Mutex::new(None),
writes: tokio::sync::Mutex::new(()),
save_lock: Mutex::new(()),
})
}
@@ -347,8 +357,11 @@ impl KeyStore {
/// Re-encrypt every key under a new passphrase.
///
/// Only possible while unlocked — we hold the decrypted keys, so the *old*
/// passphrase is not needed.
/// passphrase is not needed. Serialized with `add_user_key` behind the
/// `writes` mutex, so a key being added cannot be written under the old
/// passphrase beside keys re-encrypted under the new one (M9).
pub async fn change_passphrase(&self, new_passphrase: &str) -> Result<()> {
let _write = self.writes.lock().await;
let keys: Vec<(PublicKey, Keys)> = {
let unlocked = self.unlocked.lock().unwrap();
let unlocked = unlocked
@@ -395,7 +408,12 @@ impl KeyStore {
}
/// Encrypt and store one identity key, then unlock the vault.
///
/// Serialized with `change_passphrase` behind the `writes` mutex: both
/// encrypt and then update state, and letting them interleave produced a
/// vault no passphrase could open (M9).
async fn add_user_key(&self, name: &str, keys: &Keys, passphrase: &str) -> Result<()> {
let _write = self.writes.lock().await;
self.verify_passphrase(passphrase).await?;
let keys = keys.clone();
@@ -455,10 +473,15 @@ impl KeyStore {
/// Write the vault out atomically. An ephemeral vault (no path) does
/// nothing.
///
/// Serialized by `save_lock`, and the temp file is unique
/// ([`tempfile::NamedTempFile`]) so two concurrent saves cannot collide on a
/// shared path (M9).
fn save(&self) -> Result<()> {
if self.path.as_os_str().is_empty() {
return Ok(());
}
let _guard = self.save_lock.lock().unwrap();
let (device, keys) = {
let state = self.state.lock().unwrap();
let device = state
@@ -474,13 +497,26 @@ impl KeyStore {
keys,
};
if let Some(parent) = self.path.parent() {
std::fs::create_dir_all(parent)?;
}
let parent = self
.path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| std::path::Path::new("."));
std::fs::create_dir_all(parent)?;
let contents = serde_json::to_string_pretty(&vault)?;
let temporary = self.path.with_extension("json.tmp");
write_private(&temporary, contents.as_bytes())?;
std::fs::rename(&temporary, &self.path)?;
use std::io::Write;
let mut temporary = tempfile::NamedTempFile::new_in(parent)?;
temporary.write_all(contents.as_bytes())?;
temporary.as_file().sync_all()?;
temporary.persist(&self.path).map_err(|error| error.error)?;
// Belt-and-braces: the file is 0600 from tempfile already, but the
// permission must not depend on the umask.
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&self.path, std::fs::Permissions::from_mode(0o600));
}
Ok(())
}
}
@@ -554,26 +590,16 @@ fn decrypt_all(entries: &[StoredKey], passphrase: &str) -> Result<HashMap<Public
Ok(keys)
}
/// Write a file that is private from the moment it exists.
fn write_private(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
use std::io::Write;
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(path)?;
file.write_all(bytes)?;
file.sync_all()?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
}
Ok(())
/// A unique name for a quarantined unreadable vault.
///
/// Sub-second precision (or the pid) so a second corruption does not rename over
/// the first backup, which is the only copy of the keys (M9).
fn corrupt_path(path: &std::path::Path) -> PathBuf {
let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|since| format!("{}.{}", since.as_secs(), since.subsec_nanos()))
.unwrap_or_else(|_| format!("pid{}", std::process::id()));
PathBuf::from(format!("{}.corrupt.{stamp}", path.display()))
}
#[cfg(test)]
@@ -600,6 +626,21 @@ mod tests {
std::fs::metadata(path).unwrap().permissions().mode() & 0o777
}
/// The timestamped backups of an unreadable vault, if any.
fn corrupt_backups(path: &Path) -> Vec<PathBuf> {
std::fs::read_dir(path.parent().unwrap())
.unwrap()
.filter_map(std::result::Result::ok)
.filter(|entry| {
entry
.file_name()
.to_string_lossy()
.starts_with("keys.json.corrupt.")
})
.map(|entry| entry.path())
.collect()
}
#[tokio::test]
async fn the_device_key_is_generated_once_and_survives_a_reopen() {
let (path, store) = scratch();
@@ -831,10 +872,19 @@ mod tests {
let reopened = KeyStore::at(path.clone()).expect("open");
assert!(reopened.list_user_keys().is_empty(), "it starts empty");
assert!(
path.with_extension("json.corrupt").exists(),
"the unreadable file is kept for recovery"
let backups = corrupt_backups(&path);
assert_eq!(backups.len(), 1, "the unreadable file is kept for recovery");
// A second corruption gets its own timestamped backup: the first is not
// overwritten.
std::fs::write(&path, b"{ not json either").expect("corrupt it again");
let _ = KeyStore::at(path.clone()).expect("open");
assert_eq!(
corrupt_backups(&path).len(),
2,
"each corruption keeps its own backup"
);
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
@@ -864,4 +914,70 @@ mod tests {
let second = boottime();
assert!(second >= first);
}
/// Two concurrent `add_user_key` calls leave a valid vault with both keys,
/// and no temp file behind (M9).
#[tokio::test]
async fn concurrent_adds_do_not_collide() {
let (path, store) = scratch();
let store = std::sync::Arc::new(store);
let (a, b) = tokio::join!(
store.generate_user_key("A", "hunter2"),
store.generate_user_key("B", "hunter2"),
);
a.expect("a");
b.expect("b");
assert_eq!(store.list_user_keys().len(), 2);
let reopened = KeyStore::at(path.clone()).expect("reopen");
assert_eq!(reopened.list_user_keys().len(), 2);
let leftovers: Vec<_> = std::fs::read_dir(path.parent().unwrap())
.unwrap()
.filter_map(std::result::Result::ok)
.filter(|entry| entry.file_name().to_string_lossy().contains(".tmp"))
.collect();
assert!(leftovers.is_empty(), "no temp file is left behind");
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
/// A concurrent add and passphrase change must never leave a
/// mixed-passphrase vault. Whichever order they serialise in, exactly one
/// passphrase opens the file and every stored key decrypts under it — never
/// a vault that opens with neither (M9).
#[tokio::test]
async fn a_concurrent_add_and_change_never_mix_passphrases() {
// Few iterations: each runs several NIP-49 scrypt operations (slow in a
// debug build). The invariant holds deterministically under the `writes`
// mutex; the loop only widens the interleavings a regression could use.
for _ in 0..2 {
let (path, store) = scratch();
store.generate_user_key("Work", "old").await.expect("generate");
let store = std::sync::Arc::new(store);
let changing = store.change_passphrase("new");
let secret = Keys::generate().secret_key().to_bech32().unwrap();
let adding = store.import_user_key("Sneaky", &secret, "old");
let _ = tokio::join!(changing, adding);
let reopened = KeyStore::at(path.clone()).expect("reopen");
let opens_new = reopened.unlock("new").await.is_ok();
let opens_old = if opens_new {
false
} else {
reopened.unlock("old").await.is_ok()
};
assert!(
opens_new ^ opens_old,
"exactly one passphrase opens the vault (new={opens_new} old={opens_old})"
);
for key in reopened.list_user_keys() {
assert!(
reopened.user_key(&key.public_key).expect("load").is_some(),
"every stored key decrypts under the one passphrase"
);
}
drop(store);
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
}
}
+28 -21
View File
@@ -379,16 +379,38 @@ impl Profiles {
if self.path.as_os_str().is_empty() {
return;
}
if let Some(parent) = self.path.parent() {
let _ = std::fs::create_dir_all(parent);
}
// A unique temp file (M9): a fixed `profiles.json.tmp` would collide
// when two fetch completions save at once. Atomic rename keeps the file
// valid throughout; last-writer-wins on concurrent completions is
// acceptable here (the watermarks make a lost write re-fetchable).
let parent = self
.path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| std::path::Path::new("."));
let _ = std::fs::create_dir_all(parent);
let entries = self.entries.lock().unwrap().clone();
let Ok(contents) = serde_json::to_string_pretty(&entries) else {
return;
};
let temporary = self.path.with_extension("json.tmp");
if write_private(&temporary, contents.as_bytes()).is_ok() {
let _ = std::fs::rename(&temporary, &self.path);
use std::io::Write;
match tempfile::NamedTempFile::new_in(parent) {
Ok(mut temporary) => {
if temporary.write_all(contents.as_bytes()).is_ok()
&& temporary.as_file().sync_all().is_ok()
&& temporary.persist(&self.path).is_ok()
{
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(
&self.path,
std::fs::Permissions::from_mode(0o600),
);
}
}
}
Err(error) => eprintln!("regent: could not write profiles: {error}"),
}
}
}
@@ -1902,18 +1924,3 @@ mod tests {
}
}
fn write_private(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
use std::io::Write;
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(path)?;
file.write_all(bytes)?;
file.sync_all()?;
Ok(())
}