[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:
@@ -1043,6 +1043,9 @@ pub async fn mint_share_link(
|
||||
MintError::PasswordShort => field_err("share.password_short", "password"),
|
||||
MintError::PasswordLong => field_err("share.password_long", "password"),
|
||||
MintError::Replaces => field_err("share.replaces", "replaces"),
|
||||
MintError::TooMany => {
|
||||
ApiError::new(StatusCode::CONFLICT, "share.too_many", Params::new())
|
||||
}
|
||||
MintError::Store(s) => ApiError::internal(s),
|
||||
})?;
|
||||
if b.replaces.is_some() {
|
||||
|
||||
@@ -5,6 +5,9 @@
|
||||
//! Crash points for the crash-safety tests: with `IANITOR_TEST_CRASH_AT=<stage>` in its
|
||||
//! environment, control aborts (no cleanup, like a kill -9) when an apply reaches that stage.
|
||||
//! Without the variable this does nothing; the NixOS unit never sets it.
|
||||
//!
|
||||
//! `IANITOR_TEST_FAIL_WRITE=<file name>` makes every write of a state file with that name
|
||||
//! fail, as on a full disk (fault injection for the same tests).
|
||||
|
||||
/// The stages, in order.
|
||||
pub const STAGES: [&str; 9] = [
|
||||
@@ -25,3 +28,17 @@ pub fn point(stage: &str) {
|
||||
std::process::abort();
|
||||
}
|
||||
}
|
||||
|
||||
/// Fail a state-file write when `IANITOR_TEST_FAIL_WRITE` names this file.
|
||||
pub fn fail_write(path: &std::path::Path) -> Result<(), String> {
|
||||
match (
|
||||
std::env::var_os("IANITOR_TEST_FAIL_WRITE"),
|
||||
path.file_name(),
|
||||
) {
|
||||
(Some(want), Some(name)) if want == name => Err(format!(
|
||||
"cannot write {}: IANITOR_TEST_FAIL_WRITE (injected)",
|
||||
path.display()
|
||||
)),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
+103
-17
@@ -274,11 +274,14 @@ impl Control {
|
||||
self.paused.lock().ok().and_then(|p| p.clone())
|
||||
}
|
||||
|
||||
fn pause(&self, r: Reason) {
|
||||
let _ = write_json(&self.cfg.state_dir.join("paused.json"), &r);
|
||||
/// Pause changes. Always in memory; `Err` when it could not be saved, and then the
|
||||
/// caller must keep the journal so a restart still knows.
|
||||
fn pause(&self, r: Reason) -> Result<(), String> {
|
||||
let saved = write_json(&self.cfg.state_dir.join("paused.json"), &r);
|
||||
if let Ok(mut p) = self.paused.lock() {
|
||||
*p = Some(r);
|
||||
}
|
||||
saved
|
||||
}
|
||||
|
||||
fn unpause(&self) {
|
||||
@@ -786,7 +789,10 @@ impl Control {
|
||||
self.update(&id, |r| r.commit = Some(commit.clone()));
|
||||
j.stage = "committed".into();
|
||||
if let Err(e) = self.journal(&j) {
|
||||
log::error!(target: "ianitor::apply", "{e}");
|
||||
// The journal still says `prepared` with this commit, which recovery also reverts.
|
||||
return self
|
||||
.revert(&id, &j, fail_internal(e).unwrap_or_default(), "failed")
|
||||
.await;
|
||||
}
|
||||
crash::point("committed");
|
||||
|
||||
@@ -837,7 +843,11 @@ impl Control {
|
||||
.await;
|
||||
}
|
||||
j.stage = "trial_written".into();
|
||||
let _ = self.journal(&j);
|
||||
if let Err(e) = self.journal(&j) {
|
||||
return self
|
||||
.revert(&id, &j, fail_internal(e).unwrap_or_default(), "failed")
|
||||
.await;
|
||||
}
|
||||
crash::point("trial_written");
|
||||
self.update(&id, |r| {
|
||||
r.step("write", "done");
|
||||
@@ -897,7 +907,32 @@ impl Control {
|
||||
};
|
||||
j.stage = "trial_loaded".into();
|
||||
j.edge_sha256 = Some(sha.clone());
|
||||
let _ = self.journal(&j);
|
||||
let want = crate::util::sha256_hex(edge_text.as_bytes());
|
||||
if sha != want {
|
||||
let r = reason(
|
||||
"apply.failed.reload",
|
||||
messages::params([("engine", "Pingora".into())]),
|
||||
);
|
||||
let detail = format!(
|
||||
"edge loaded a trial with SHA-256 {sha}, not the one control wrote ({want})"
|
||||
);
|
||||
return self
|
||||
.revert(
|
||||
&id,
|
||||
&j,
|
||||
Reason {
|
||||
detail: Some(detail),
|
||||
..r
|
||||
},
|
||||
"failed",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
if let Err(e) = self.journal(&j) {
|
||||
return self
|
||||
.revert(&id, &j, fail_internal(e).unwrap_or_default(), "failed")
|
||||
.await;
|
||||
}
|
||||
crash::point("trial_loaded");
|
||||
self.update(&id, |r| r.step("reload", "done"));
|
||||
|
||||
@@ -968,15 +1003,36 @@ impl Control {
|
||||
.await;
|
||||
}
|
||||
j.stage = "confirmed".into();
|
||||
let _ = self.journal(&j);
|
||||
if let Err(e) = self.journal(&j) {
|
||||
// Without a `confirmed` journal a crash would revert a kept change; so revert now
|
||||
// (the revert also brings edge back to edge.json).
|
||||
return self
|
||||
.revert(&id, &j, fail_internal(e).unwrap_or_default(), "failed")
|
||||
.await;
|
||||
}
|
||||
crash::point("confirmed");
|
||||
if let Err(e) = self.promote() {
|
||||
// Edge serves the new config and the repository has it; the files catch up at
|
||||
// the next start (recovery promotes again).
|
||||
log::error!(target: "ianitor::apply", "cannot promote the trial files: {e}");
|
||||
let promoted = self.promote().or_else(|e| {
|
||||
log::error!(target: "ianitor::apply", "cannot promote the trial files ({e}); writing them again");
|
||||
write_atomic(&self.cfg.edge.config, edge_text.as_bytes(), 0o644)
|
||||
.and_then(|_| write_atomic(&self.cfg.caddy.config, caddy_text.as_bytes(), 0o644))
|
||||
});
|
||||
if let Err(e) = promoted {
|
||||
// Edge serves the change and the repository has it, but the files do not: keep
|
||||
// the journal at `confirmed` (recovery promotes) and pause so nothing overwrites it.
|
||||
log::error!(target: "ianitor::apply", "cannot write the config files: {e}");
|
||||
let mut p = reason("control.files_unwritten", Params::new());
|
||||
p.detail = Some(e.to_string());
|
||||
let _ = self.pause(p);
|
||||
let push_step = self.push_step();
|
||||
self.update(&id, |r| r.step("push", push_step));
|
||||
self.finish(&id, "kept", Some(kept_reason), Vec::new());
|
||||
return;
|
||||
}
|
||||
j.stage = "promoted".into();
|
||||
let _ = self.journal(&j);
|
||||
if let Err(e) = self.journal(&j) {
|
||||
// Files are promoted; a stale `confirmed` journal only makes recovery promote again.
|
||||
log::error!(target: "ianitor::apply", "{e}");
|
||||
}
|
||||
crash::point("promoted");
|
||||
// Record first, journal last: a crash in between is finished again by recovery.
|
||||
let push_step = self.push_step();
|
||||
@@ -1210,7 +1266,10 @@ impl Control {
|
||||
let mut j = j.clone();
|
||||
j.stage = "reverting".into();
|
||||
j.reason = Some(why.clone());
|
||||
let _ = self.journal(&j);
|
||||
if let Err(e) = self.journal(&j) {
|
||||
// The earlier stage stays on disk; recovery reverts from it too.
|
||||
log::error!(target: "ianitor::apply", "{e}");
|
||||
}
|
||||
crash::point("reverting");
|
||||
match self.finish_revert(&j).await {
|
||||
Ok(rev) => {
|
||||
@@ -1222,9 +1281,12 @@ impl Control {
|
||||
log::error!(target: "ianitor::apply", "apply {id}: the revert failed: {e}");
|
||||
let mut r = reason("apply.needs_attention", Params::new());
|
||||
r.detail = Some(format!("{}: {e}", why.message));
|
||||
self.pause(r.clone());
|
||||
// The journal stays at `reverting`: a restart retries the revert, and even
|
||||
// if the pause below cannot be saved, it never loads the unverified head.
|
||||
if let Err(pe) = self.pause(r.clone()) {
|
||||
log::error!(target: "ianitor::apply", "cannot save the pause ({pe}); the journal keeps it");
|
||||
}
|
||||
self.finish(id, "needs_attention", Some(r), Vec::new());
|
||||
self.clear_journal();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1239,6 +1301,20 @@ impl Control {
|
||||
log::warn!(target: "ianitor::apply", "could not tell edge to abort the trial: {e}")
|
||||
}
|
||||
}
|
||||
// If edge confirmed the trial after all (an answer lost on the way), it still runs
|
||||
// the reverted config: reload it from edge.json, the last good config.
|
||||
if let (Ok(st), Ok(disk)) = (
|
||||
self.edge.status().await,
|
||||
std::fs::read(&self.cfg.edge.config),
|
||||
) && st.trial.is_none()
|
||||
&& st.config_sha256 != crate::util::sha256_hex(&disk)
|
||||
{
|
||||
log::warn!(target: "ianitor::apply", "edge runs a config that is not edge.json; reloading it");
|
||||
self.edge
|
||||
.reload()
|
||||
.await
|
||||
.map_err(|e| format!("edge did not reload edge.json: {e}"))?;
|
||||
}
|
||||
}
|
||||
let head = self.repo.head_required().map_err(|e| e.to_string())?;
|
||||
let mut rev = None;
|
||||
@@ -1322,11 +1398,21 @@ impl Control {
|
||||
};
|
||||
self.finish(&j.apply_id, state, Some(why), Vec::new());
|
||||
self.clear_journal();
|
||||
if self
|
||||
.paused()
|
||||
.is_some_and(|p| p.code == "apply.needs_attention")
|
||||
{
|
||||
log::info!(target: "ianitor::apply", "the interrupted revert is done; changes resume");
|
||||
self.unpause();
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
// Journal kept: the next start tries again.
|
||||
let mut r = reason("apply.needs_attention", Params::new());
|
||||
r.detail = Some(e);
|
||||
self.pause(r.clone());
|
||||
if let Err(pe) = self.pause(r.clone()) {
|
||||
log::error!(target: "ianitor::apply", "cannot save the pause: {pe}");
|
||||
}
|
||||
self.finish(&j.apply_id, "needs_attention", Some(r), Vec::new());
|
||||
}
|
||||
}
|
||||
@@ -1378,7 +1464,7 @@ impl Control {
|
||||
Ok(x) => x,
|
||||
Err(f) => {
|
||||
log::error!(target: "ianitor::control", "{}", f.reason.message);
|
||||
self.pause(f.reason);
|
||||
let _ = self.pause(f.reason);
|
||||
return;
|
||||
}
|
||||
};
|
||||
@@ -1394,7 +1480,7 @@ impl Control {
|
||||
let mut r = reason("repo.unreadable", messages::params([("file", file)]));
|
||||
r.detail = fe.first().and_then(|e| e.detail.clone());
|
||||
log::error!(target: "ianitor::control", "the routes repository does not validate: {}", r.detail.clone().unwrap_or_default());
|
||||
self.pause(r);
|
||||
let _ = self.pause(r);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -188,6 +188,9 @@ fn template(code: &str) -> &'static str {
|
||||
"share.unavailable" => {
|
||||
"Share links are not set up on this server: the share-link key is missing from the credentials."
|
||||
}
|
||||
"share.too_many" => {
|
||||
"There are 2,000 active share links already. Stop some, or stop all, then try again."
|
||||
}
|
||||
"share.not_found" => "There is no share link with that id.",
|
||||
"share.replaces" => "The link to replace is not a link for {hostname}.",
|
||||
// 3.5 tokens, limits
|
||||
@@ -203,6 +206,9 @@ fn template(code: &str) -> &'static str {
|
||||
"token.name" => "Use 1 to 64 letters, digits, spaces, dots, dashes or underscores.",
|
||||
"token.expiry" => "Choose between 1 and 3650 days, or never.",
|
||||
"rate.limited" => "Too many requests in a short time. Try again in {seconds} s.",
|
||||
"control.files_unwritten" => {
|
||||
"The change is live, but Ianitor could not save the proxy settings to disk. Changes are paused until Ianitor restarts and saves them."
|
||||
}
|
||||
"control.paused" => "Changes are paused: {reason} Traffic keeps flowing.",
|
||||
// request shape
|
||||
"request.body" => "The request body is not valid: {problem}",
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
//! and on its own every 5 s. When control is down nothing can be stopped, but edge keeps
|
||||
//! refusing what is already on the list, also across its own restarts.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use ianitor_core::share::{self, LinkSpec, ShareId, ShareKey};
|
||||
@@ -61,6 +62,10 @@ struct RevocationFile {
|
||||
const KEEP_SECS: u64 = 30 * 86_400;
|
||||
pub const MIN_EXPIRY: u64 = 3600;
|
||||
pub const MAX_EXPIRY: u64 = 90 * 86_400;
|
||||
/// Most active links at once.
|
||||
pub const MAX_ACTIVE: usize = 2000;
|
||||
/// Most ids edge takes on its deny list (edge refuses 10,000 and more).
|
||||
const MAX_DENY: usize = 9_999;
|
||||
|
||||
pub struct Shares {
|
||||
path: PathBuf,
|
||||
@@ -80,6 +85,8 @@ pub enum MintError {
|
||||
PasswordShort,
|
||||
PasswordLong,
|
||||
Replaces,
|
||||
/// More active links than [`MAX_ACTIVE`].
|
||||
TooMany,
|
||||
Store(String),
|
||||
}
|
||||
|
||||
@@ -96,33 +103,91 @@ impl Shares {
|
||||
Ok(read_json(&self.path)?.unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The revocation file as edge has it now, if it can be read.
|
||||
fn published(&self) -> Option<(u32, BTreeSet<String>)> {
|
||||
#[derive(Deserialize)]
|
||||
struct Published {
|
||||
epoch: u32,
|
||||
deny: Vec<String>,
|
||||
}
|
||||
let p: Published = serde_json::from_slice(&std::fs::read(&self.revocations).ok()?).ok()?;
|
||||
Some((p.epoch, p.deny.into_iter().collect()))
|
||||
}
|
||||
|
||||
/// The records, with the epoch never below the published one (records lost or restored
|
||||
/// from an older backup must not bring stopped links back).
|
||||
fn load_reconciled(&self) -> Result<ShareFile, String> {
|
||||
let mut f = self.load()?;
|
||||
if let Some((epoch, _)) = self.published()
|
||||
&& epoch > f.epoch
|
||||
{
|
||||
log::warn!(target: "ianitor::share", "share-link records are behind the published revocations (epoch {} < {epoch}); continuing from {epoch}", f.epoch);
|
||||
f.epoch = epoch;
|
||||
}
|
||||
Ok(f)
|
||||
}
|
||||
|
||||
fn save(&self, f: &mut ShareFile) -> Result<(), String> {
|
||||
let t = now();
|
||||
f.links.retain(|l| {
|
||||
let end = l.stopped_at.unwrap_or(l.expires_at).min(l.expires_at);
|
||||
t < end.saturating_add(KEEP_SECS)
|
||||
});
|
||||
// Kept at least until they expire: a stopped link must stay on the deny list as long
|
||||
// as its token would otherwise work.
|
||||
f.links
|
||||
.retain(|l| t < l.expires_at.saturating_add(KEEP_SECS));
|
||||
let deny = self.reconcile(f);
|
||||
write_json(&self.path, f)?;
|
||||
self.write_revocations(f)
|
||||
self.publish(f.epoch, deny)
|
||||
}
|
||||
|
||||
/// The deny list for `f`, raising `f.epoch` when the list cannot be kept whole:
|
||||
/// - a published id that the records cannot account for (stopped link lost from the
|
||||
/// records) is never just dropped: the epoch goes up, which stops every older link;
|
||||
/// - a list longer than edge accepts also raises the epoch, instead of being cut short.
|
||||
fn reconcile(&self, f: &mut ShareFile) -> Vec<String> {
|
||||
let t = now();
|
||||
let published = self.published();
|
||||
if let Some((epoch, _)) = &published {
|
||||
f.epoch = f.epoch.max(*epoch);
|
||||
}
|
||||
let deny_for = |f: &ShareFile| -> Vec<String> {
|
||||
let mut d: Vec<String> = f
|
||||
.links
|
||||
.iter()
|
||||
.filter(|l| l.stopped_at.is_some() && l.expires_at > t && l.epoch >= f.epoch)
|
||||
.map(|l| l.id.clone())
|
||||
.collect();
|
||||
d.sort();
|
||||
d
|
||||
};
|
||||
let mut deny = deny_for(f);
|
||||
if let Some((epoch, old)) = published
|
||||
&& epoch == f.epoch
|
||||
{
|
||||
let accounted = |id: &String| {
|
||||
deny.binary_search(id).is_ok()
|
||||
|| f.links
|
||||
.iter()
|
||||
.any(|l| &l.id == id && (l.expires_at <= t || l.epoch < f.epoch))
|
||||
};
|
||||
if !old.iter().all(accounted) {
|
||||
log::warn!(target: "ianitor::share", "stopped links are missing from the records; raising the epoch, which stops every earlier link");
|
||||
f.epoch = f.epoch.saturating_add(1);
|
||||
deny = deny_for(f);
|
||||
}
|
||||
}
|
||||
if deny.len() > MAX_DENY {
|
||||
log::warn!(target: "ianitor::share", "more than {MAX_DENY} stopped links; raising the epoch, which stops every earlier link");
|
||||
f.epoch = f.epoch.saturating_add(1);
|
||||
deny = deny_for(f);
|
||||
}
|
||||
deny
|
||||
}
|
||||
|
||||
/// Write the revocation file edge reads.
|
||||
pub fn write_revocations(&self, f: &ShareFile) -> Result<(), String> {
|
||||
let t = now();
|
||||
let mut deny: Vec<String> = f
|
||||
.links
|
||||
.iter()
|
||||
.filter(|l| l.stopped_at.is_some() && l.expires_at > t && l.epoch >= f.epoch)
|
||||
.map(|l| l.id.clone())
|
||||
.collect();
|
||||
deny.sort();
|
||||
deny.truncate(9_999);
|
||||
fn publish(&self, epoch: u32, deny: Vec<String>) -> Result<(), String> {
|
||||
// Readable by edge (another user); it holds only random link ids.
|
||||
let text = serde_json::to_vec(&RevocationFile {
|
||||
epoch: f.epoch,
|
||||
deny,
|
||||
})
|
||||
.map_err(|e| e.to_string())?;
|
||||
let text =
|
||||
serde_json::to_vec(&RevocationFile { epoch, deny }).map_err(|e| e.to_string())?;
|
||||
crate::crash::fail_write(&self.revocations)?;
|
||||
crate::util::write_atomic(&self.revocations, &text, 0o644)
|
||||
.map_err(|e| format!("cannot write {}: {e}", self.revocations.display()))
|
||||
}
|
||||
@@ -132,8 +197,8 @@ impl Shares {
|
||||
.lock
|
||||
.lock()
|
||||
.map_err(|_| "share store unavailable".to_owned())?;
|
||||
let f = self.load()?;
|
||||
self.write_revocations(&f)
|
||||
let mut f = self.load()?;
|
||||
self.save(&mut f)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -164,7 +229,16 @@ impl Shares {
|
||||
.lock
|
||||
.lock()
|
||||
.map_err(|_| MintError::Store("share store unavailable".into()))?;
|
||||
let mut f = self.load().map_err(MintError::Store)?;
|
||||
let mut f = self.load_reconciled().map_err(MintError::Store)?;
|
||||
let t0 = now();
|
||||
if f.links
|
||||
.iter()
|
||||
.filter(|l| l.stopped_at.is_none() && l.expires_at > t0)
|
||||
.count()
|
||||
>= MAX_ACTIVE
|
||||
{
|
||||
return Err(MintError::TooMany);
|
||||
}
|
||||
if let Some(r) = replaces {
|
||||
let Some(old) = f
|
||||
.links
|
||||
@@ -208,7 +282,7 @@ impl Shares {
|
||||
.lock
|
||||
.lock()
|
||||
.map_err(|_| "share store unavailable".to_owned())?;
|
||||
let mut f = self.load()?;
|
||||
let mut f = self.load_reconciled()?;
|
||||
let Some(l) = f.links.iter_mut().find(|l| l.id == id) else {
|
||||
return Ok(None);
|
||||
};
|
||||
@@ -224,7 +298,7 @@ impl Shares {
|
||||
.lock
|
||||
.lock()
|
||||
.map_err(|_| "share store unavailable".to_owned())?;
|
||||
let mut f = self.load()?;
|
||||
let mut f = self.load_reconciled()?;
|
||||
f.epoch = f.epoch.saturating_add(1);
|
||||
let e = f.epoch;
|
||||
self.save(&mut f)?;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -114,6 +114,7 @@ pub fn read_json<T: DeserializeOwned>(path: &Path) -> Result<Option<T>, String>
|
||||
|
||||
/// Write a JSON state file atomically, readable by its owner only.
|
||||
pub fn write_json<T: Serialize>(path: &Path, value: &T) -> Result<(), String> {
|
||||
crate::crash::fail_write(path)?;
|
||||
let mut text = serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?;
|
||||
text.push(b'\n');
|
||||
write_atomic(path, &text, 0o600).map_err(|e| format!("cannot write {}: {e}", path.display()))
|
||||
|
||||
Reference in New Issue
Block a user