[control] Store and recovery fixes: cross-process token lock, revert keeps its journal until done, epoch and deny list never roll back, journal errors propagate, lost confirm reloads edge, trial hash checked

This commit is contained in:
2026-11-07 18:51:58 +01:00
parent b9e14c6aee
commit 4448527b16
10 changed files with 305 additions and 66 deletions
+34 -13
View File
@@ -59,6 +59,11 @@ pub struct Tokens {
lock: std::sync::Mutex<()>,
}
struct StoreGuard<'a> {
_m: std::sync::MutexGuard<'a, ()>,
_f: std::fs::File,
}
pub fn valid_name(n: &str) -> bool {
let n = n.trim();
!n.is_empty()
@@ -75,6 +80,30 @@ impl Tokens {
}
}
/// Exclusive access to `tokens.json` for one read-modify-write: a mutex inside this
/// process and an advisory lock on `tokens.lock` across processes (the CLI and the
/// server), released when the guard is dropped, also if the process dies.
fn guard(&self) -> Result<StoreGuard<'_>, String> {
let m = self
.lock
.lock()
.map_err(|_| "token store unavailable".to_owned())?;
let path = self.path.with_file_name("tokens.lock");
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)
.map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
}
let f = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(&path)
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
f.lock()
.map_err(|e| format!("cannot lock {}: {e}", path.display()))?;
Ok(StoreGuard { _m: m, _f: f })
}
fn load(&self) -> Result<TokenFile, String> {
Ok(read_json(&self.path)?.unwrap_or_default())
}
@@ -89,10 +118,7 @@ impl Tokens {
name: &str,
expires_at: Option<u64>,
) -> Result<(TokenRecord, String), String> {
let _g = self
.lock
.lock()
.map_err(|_| "token store unavailable".to_owned())?;
let _g = self.guard()?;
if !valid_name(name) {
return Err("token.name".into());
}
@@ -118,14 +144,12 @@ impl Tokens {
}
pub fn list(&self) -> Result<Vec<TokenRecord>, String> {
let _g = self.guard()?;
Ok(self.load()?.tokens)
}
pub fn revoke(&self, id: &str) -> Result<Option<TokenRecord>, String> {
let _g = self
.lock
.lock()
.map_err(|_| "token store unavailable".to_owned())?;
let _g = self.guard()?;
let mut f = self.load()?;
let Some(t) = f.tokens.iter_mut().find(|t| t.id == id) else {
return Ok(None);
@@ -139,10 +163,7 @@ impl Tokens {
}
pub fn rename(&self, id: &str, name: &str) -> Result<Option<TokenRecord>, String> {
let _g = self
.lock
.lock()
.map_err(|_| "token store unavailable".to_owned())?;
let _g = self.guard()?;
if !valid_name(name) {
return Err("token.name".into());
}
@@ -170,7 +191,7 @@ impl Tokens {
.map(|(id, _)| id)
.filter(|id| id.len() == 16)
.ok_or(Refusal::Unknown)?;
let _g = self.lock.lock().map_err(|_| Refusal::Unknown)?;
let _g = self.guard().map_err(|_| Refusal::Unknown)?;
let mut f = self.load().map_err(|_| Refusal::Unknown)?;
let presented = sha256_hex(value.as_bytes());
let Some(t) = f.tokens.iter_mut().find(|t| t.id == id) else {