[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:
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/core", "crates/edge", "crates/control", "tests/diff", "tests/
|
|||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
rust-version = "1.88"
|
rust-version = "1.89"
|
||||||
license = "MPL-2.0"
|
license = "MPL-2.0"
|
||||||
publish = false
|
publish = false
|
||||||
|
|
||||||
|
|||||||
@@ -1043,6 +1043,9 @@ pub async fn mint_share_link(
|
|||||||
MintError::PasswordShort => field_err("share.password_short", "password"),
|
MintError::PasswordShort => field_err("share.password_short", "password"),
|
||||||
MintError::PasswordLong => field_err("share.password_long", "password"),
|
MintError::PasswordLong => field_err("share.password_long", "password"),
|
||||||
MintError::Replaces => field_err("share.replaces", "replaces"),
|
MintError::Replaces => field_err("share.replaces", "replaces"),
|
||||||
|
MintError::TooMany => {
|
||||||
|
ApiError::new(StatusCode::CONFLICT, "share.too_many", Params::new())
|
||||||
|
}
|
||||||
MintError::Store(s) => ApiError::internal(s),
|
MintError::Store(s) => ApiError::internal(s),
|
||||||
})?;
|
})?;
|
||||||
if b.replaces.is_some() {
|
if b.replaces.is_some() {
|
||||||
|
|||||||
@@ -5,6 +5,9 @@
|
|||||||
//! Crash points for the crash-safety tests: with `IANITOR_TEST_CRASH_AT=<stage>` in its
|
//! 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.
|
//! 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.
|
//! 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.
|
/// The stages, in order.
|
||||||
pub const STAGES: [&str; 9] = [
|
pub const STAGES: [&str; 9] = [
|
||||||
@@ -25,3 +28,17 @@ pub fn point(stage: &str) {
|
|||||||
std::process::abort();
|
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())
|
self.paused.lock().ok().and_then(|p| p.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn pause(&self, r: Reason) {
|
/// Pause changes. Always in memory; `Err` when it could not be saved, and then the
|
||||||
let _ = write_json(&self.cfg.state_dir.join("paused.json"), &r);
|
/// 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() {
|
if let Ok(mut p) = self.paused.lock() {
|
||||||
*p = Some(r);
|
*p = Some(r);
|
||||||
}
|
}
|
||||||
|
saved
|
||||||
}
|
}
|
||||||
|
|
||||||
fn unpause(&self) {
|
fn unpause(&self) {
|
||||||
@@ -786,7 +789,10 @@ impl Control {
|
|||||||
self.update(&id, |r| r.commit = Some(commit.clone()));
|
self.update(&id, |r| r.commit = Some(commit.clone()));
|
||||||
j.stage = "committed".into();
|
j.stage = "committed".into();
|
||||||
if let Err(e) = self.journal(&j) {
|
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");
|
crash::point("committed");
|
||||||
|
|
||||||
@@ -837,7 +843,11 @@ impl Control {
|
|||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
j.stage = "trial_written".into();
|
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");
|
crash::point("trial_written");
|
||||||
self.update(&id, |r| {
|
self.update(&id, |r| {
|
||||||
r.step("write", "done");
|
r.step("write", "done");
|
||||||
@@ -897,7 +907,32 @@ impl Control {
|
|||||||
};
|
};
|
||||||
j.stage = "trial_loaded".into();
|
j.stage = "trial_loaded".into();
|
||||||
j.edge_sha256 = Some(sha.clone());
|
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");
|
crash::point("trial_loaded");
|
||||||
self.update(&id, |r| r.step("reload", "done"));
|
self.update(&id, |r| r.step("reload", "done"));
|
||||||
|
|
||||||
@@ -968,15 +1003,36 @@ impl Control {
|
|||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
j.stage = "confirmed".into();
|
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");
|
crash::point("confirmed");
|
||||||
if let Err(e) = self.promote() {
|
let promoted = self.promote().or_else(|e| {
|
||||||
// Edge serves the new config and the repository has it; the files catch up at
|
log::error!(target: "ianitor::apply", "cannot promote the trial files ({e}); writing them again");
|
||||||
// the next start (recovery promotes again).
|
write_atomic(&self.cfg.edge.config, edge_text.as_bytes(), 0o644)
|
||||||
log::error!(target: "ianitor::apply", "cannot promote the trial files: {e}");
|
.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();
|
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");
|
crash::point("promoted");
|
||||||
// Record first, journal last: a crash in between is finished again by recovery.
|
// Record first, journal last: a crash in between is finished again by recovery.
|
||||||
let push_step = self.push_step();
|
let push_step = self.push_step();
|
||||||
@@ -1210,7 +1266,10 @@ impl Control {
|
|||||||
let mut j = j.clone();
|
let mut j = j.clone();
|
||||||
j.stage = "reverting".into();
|
j.stage = "reverting".into();
|
||||||
j.reason = Some(why.clone());
|
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");
|
crash::point("reverting");
|
||||||
match self.finish_revert(&j).await {
|
match self.finish_revert(&j).await {
|
||||||
Ok(rev) => {
|
Ok(rev) => {
|
||||||
@@ -1222,9 +1281,12 @@ impl Control {
|
|||||||
log::error!(target: "ianitor::apply", "apply {id}: the revert failed: {e}");
|
log::error!(target: "ianitor::apply", "apply {id}: the revert failed: {e}");
|
||||||
let mut r = reason("apply.needs_attention", Params::new());
|
let mut r = reason("apply.needs_attention", Params::new());
|
||||||
r.detail = Some(format!("{}: {e}", why.message));
|
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.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}")
|
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 head = self.repo.head_required().map_err(|e| e.to_string())?;
|
||||||
let mut rev = None;
|
let mut rev = None;
|
||||||
@@ -1322,11 +1398,21 @@ impl Control {
|
|||||||
};
|
};
|
||||||
self.finish(&j.apply_id, state, Some(why), Vec::new());
|
self.finish(&j.apply_id, state, Some(why), Vec::new());
|
||||||
self.clear_journal();
|
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) => {
|
Err(e) => {
|
||||||
|
// Journal kept: the next start tries again.
|
||||||
let mut r = reason("apply.needs_attention", Params::new());
|
let mut r = reason("apply.needs_attention", Params::new());
|
||||||
r.detail = Some(e);
|
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());
|
self.finish(&j.apply_id, "needs_attention", Some(r), Vec::new());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1378,7 +1464,7 @@ impl Control {
|
|||||||
Ok(x) => x,
|
Ok(x) => x,
|
||||||
Err(f) => {
|
Err(f) => {
|
||||||
log::error!(target: "ianitor::control", "{}", f.reason.message);
|
log::error!(target: "ianitor::control", "{}", f.reason.message);
|
||||||
self.pause(f.reason);
|
let _ = self.pause(f.reason);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -1394,7 +1480,7 @@ impl Control {
|
|||||||
let mut r = reason("repo.unreadable", messages::params([("file", file)]));
|
let mut r = reason("repo.unreadable", messages::params([("file", file)]));
|
||||||
r.detail = fe.first().and_then(|e| e.detail.clone());
|
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());
|
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;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -188,6 +188,9 @@ fn template(code: &str) -> &'static str {
|
|||||||
"share.unavailable" => {
|
"share.unavailable" => {
|
||||||
"Share links are not set up on this server: the share-link key is missing from the credentials."
|
"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.not_found" => "There is no share link with that id.",
|
||||||
"share.replaces" => "The link to replace is not a link for {hostname}.",
|
"share.replaces" => "The link to replace is not a link for {hostname}.",
|
||||||
// 3.5 tokens, limits
|
// 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.name" => "Use 1 to 64 letters, digits, spaces, dots, dashes or underscores.",
|
||||||
"token.expiry" => "Choose between 1 and 3650 days, or never.",
|
"token.expiry" => "Choose between 1 and 3650 days, or never.",
|
||||||
"rate.limited" => "Too many requests in a short time. Try again in {seconds} s.",
|
"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.",
|
"control.paused" => "Changes are paused: {reason} Traffic keeps flowing.",
|
||||||
// request shape
|
// request shape
|
||||||
"request.body" => "The request body is not valid: {problem}",
|
"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
|
//! 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.
|
//! refusing what is already on the list, also across its own restarts.
|
||||||
|
|
||||||
|
use std::collections::BTreeSet;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
use ianitor_core::share::{self, LinkSpec, ShareId, ShareKey};
|
use ianitor_core::share::{self, LinkSpec, ShareId, ShareKey};
|
||||||
@@ -61,6 +62,10 @@ struct RevocationFile {
|
|||||||
const KEEP_SECS: u64 = 30 * 86_400;
|
const KEEP_SECS: u64 = 30 * 86_400;
|
||||||
pub const MIN_EXPIRY: u64 = 3600;
|
pub const MIN_EXPIRY: u64 = 3600;
|
||||||
pub const MAX_EXPIRY: u64 = 90 * 86_400;
|
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 {
|
pub struct Shares {
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
@@ -80,6 +85,8 @@ pub enum MintError {
|
|||||||
PasswordShort,
|
PasswordShort,
|
||||||
PasswordLong,
|
PasswordLong,
|
||||||
Replaces,
|
Replaces,
|
||||||
|
/// More active links than [`MAX_ACTIVE`].
|
||||||
|
TooMany,
|
||||||
Store(String),
|
Store(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,33 +103,91 @@ impl Shares {
|
|||||||
Ok(read_json(&self.path)?.unwrap_or_default())
|
Ok(read_json(&self.path)?.unwrap_or_default())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn save(&self, f: &mut ShareFile) -> Result<(), String> {
|
/// The revocation file as edge has it now, if it can be read.
|
||||||
let t = now();
|
fn published(&self) -> Option<(u32, BTreeSet<String>)> {
|
||||||
f.links.retain(|l| {
|
#[derive(Deserialize)]
|
||||||
let end = l.stopped_at.unwrap_or(l.expires_at).min(l.expires_at);
|
struct Published {
|
||||||
t < end.saturating_add(KEEP_SECS)
|
epoch: u32,
|
||||||
});
|
deny: Vec<String>,
|
||||||
write_json(&self.path, f)?;
|
}
|
||||||
self.write_revocations(f)
|
let p: Published = serde_json::from_slice(&std::fs::read(&self.revocations).ok()?).ok()?;
|
||||||
|
Some((p.epoch, p.deny.into_iter().collect()))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Write the revocation file edge reads.
|
/// The records, with the epoch never below the published one (records lost or restored
|
||||||
pub fn write_revocations(&self, f: &ShareFile) -> Result<(), String> {
|
/// 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();
|
let t = now();
|
||||||
let mut deny: Vec<String> = f
|
// 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.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
|
.links
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|l| l.stopped_at.is_some() && l.expires_at > t && l.epoch >= f.epoch)
|
.filter(|l| l.stopped_at.is_some() && l.expires_at > t && l.epoch >= f.epoch)
|
||||||
.map(|l| l.id.clone())
|
.map(|l| l.id.clone())
|
||||||
.collect();
|
.collect();
|
||||||
deny.sort();
|
d.sort();
|
||||||
deny.truncate(9_999);
|
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.
|
||||||
|
fn publish(&self, epoch: u32, deny: Vec<String>) -> Result<(), String> {
|
||||||
// Readable by edge (another user); it holds only random link ids.
|
// Readable by edge (another user); it holds only random link ids.
|
||||||
let text = serde_json::to_vec(&RevocationFile {
|
let text =
|
||||||
epoch: f.epoch,
|
serde_json::to_vec(&RevocationFile { epoch, deny }).map_err(|e| e.to_string())?;
|
||||||
deny,
|
crate::crash::fail_write(&self.revocations)?;
|
||||||
})
|
|
||||||
.map_err(|e| e.to_string())?;
|
|
||||||
crate::util::write_atomic(&self.revocations, &text, 0o644)
|
crate::util::write_atomic(&self.revocations, &text, 0o644)
|
||||||
.map_err(|e| format!("cannot write {}: {e}", self.revocations.display()))
|
.map_err(|e| format!("cannot write {}: {e}", self.revocations.display()))
|
||||||
}
|
}
|
||||||
@@ -132,8 +197,8 @@ impl Shares {
|
|||||||
.lock
|
.lock
|
||||||
.lock()
|
.lock()
|
||||||
.map_err(|_| "share store unavailable".to_owned())?;
|
.map_err(|_| "share store unavailable".to_owned())?;
|
||||||
let f = self.load()?;
|
let mut f = self.load()?;
|
||||||
self.write_revocations(&f)
|
self.save(&mut f)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
@@ -164,7 +229,16 @@ impl Shares {
|
|||||||
.lock
|
.lock
|
||||||
.lock()
|
.lock()
|
||||||
.map_err(|_| MintError::Store("share store unavailable".into()))?;
|
.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 {
|
if let Some(r) = replaces {
|
||||||
let Some(old) = f
|
let Some(old) = f
|
||||||
.links
|
.links
|
||||||
@@ -208,7 +282,7 @@ impl Shares {
|
|||||||
.lock
|
.lock
|
||||||
.lock()
|
.lock()
|
||||||
.map_err(|_| "share store unavailable".to_owned())?;
|
.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 {
|
let Some(l) = f.links.iter_mut().find(|l| l.id == id) else {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
};
|
};
|
||||||
@@ -224,7 +298,7 @@ impl Shares {
|
|||||||
.lock
|
.lock
|
||||||
.lock()
|
.lock()
|
||||||
.map_err(|_| "share store unavailable".to_owned())?;
|
.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);
|
f.epoch = f.epoch.saturating_add(1);
|
||||||
let e = f.epoch;
|
let e = f.epoch;
|
||||||
self.save(&mut f)?;
|
self.save(&mut f)?;
|
||||||
|
|||||||
@@ -59,6 +59,11 @@ pub struct Tokens {
|
|||||||
lock: std::sync::Mutex<()>,
|
lock: std::sync::Mutex<()>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct StoreGuard<'a> {
|
||||||
|
_m: std::sync::MutexGuard<'a, ()>,
|
||||||
|
_f: std::fs::File,
|
||||||
|
}
|
||||||
|
|
||||||
pub fn valid_name(n: &str) -> bool {
|
pub fn valid_name(n: &str) -> bool {
|
||||||
let n = n.trim();
|
let n = n.trim();
|
||||||
!n.is_empty()
|
!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> {
|
fn load(&self) -> Result<TokenFile, String> {
|
||||||
Ok(read_json(&self.path)?.unwrap_or_default())
|
Ok(read_json(&self.path)?.unwrap_or_default())
|
||||||
}
|
}
|
||||||
@@ -89,10 +118,7 @@ impl Tokens {
|
|||||||
name: &str,
|
name: &str,
|
||||||
expires_at: Option<u64>,
|
expires_at: Option<u64>,
|
||||||
) -> Result<(TokenRecord, String), String> {
|
) -> Result<(TokenRecord, String), String> {
|
||||||
let _g = self
|
let _g = self.guard()?;
|
||||||
.lock
|
|
||||||
.lock()
|
|
||||||
.map_err(|_| "token store unavailable".to_owned())?;
|
|
||||||
if !valid_name(name) {
|
if !valid_name(name) {
|
||||||
return Err("token.name".into());
|
return Err("token.name".into());
|
||||||
}
|
}
|
||||||
@@ -118,14 +144,12 @@ impl Tokens {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn list(&self) -> Result<Vec<TokenRecord>, String> {
|
pub fn list(&self) -> Result<Vec<TokenRecord>, String> {
|
||||||
|
let _g = self.guard()?;
|
||||||
Ok(self.load()?.tokens)
|
Ok(self.load()?.tokens)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn revoke(&self, id: &str) -> Result<Option<TokenRecord>, String> {
|
pub fn revoke(&self, id: &str) -> Result<Option<TokenRecord>, String> {
|
||||||
let _g = self
|
let _g = self.guard()?;
|
||||||
.lock
|
|
||||||
.lock()
|
|
||||||
.map_err(|_| "token store unavailable".to_owned())?;
|
|
||||||
let mut f = self.load()?;
|
let mut f = self.load()?;
|
||||||
let Some(t) = f.tokens.iter_mut().find(|t| t.id == id) else {
|
let Some(t) = f.tokens.iter_mut().find(|t| t.id == id) else {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
@@ -139,10 +163,7 @@ impl Tokens {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn rename(&self, id: &str, name: &str) -> Result<Option<TokenRecord>, String> {
|
pub fn rename(&self, id: &str, name: &str) -> Result<Option<TokenRecord>, String> {
|
||||||
let _g = self
|
let _g = self.guard()?;
|
||||||
.lock
|
|
||||||
.lock()
|
|
||||||
.map_err(|_| "token store unavailable".to_owned())?;
|
|
||||||
if !valid_name(name) {
|
if !valid_name(name) {
|
||||||
return Err("token.name".into());
|
return Err("token.name".into());
|
||||||
}
|
}
|
||||||
@@ -170,7 +191,7 @@ impl Tokens {
|
|||||||
.map(|(id, _)| id)
|
.map(|(id, _)| id)
|
||||||
.filter(|id| id.len() == 16)
|
.filter(|id| id.len() == 16)
|
||||||
.ok_or(Refusal::Unknown)?;
|
.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 mut f = self.load().map_err(|_| Refusal::Unknown)?;
|
||||||
let presented = sha256_hex(value.as_bytes());
|
let presented = sha256_hex(value.as_bytes());
|
||||||
let Some(t) = f.tokens.iter_mut().find(|t| t.id == id) else {
|
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.
|
/// Write a JSON state file atomically, readable by its owner only.
|
||||||
pub fn write_json<T: Serialize>(path: &Path, value: &T) -> Result<(), String> {
|
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())?;
|
let mut text = serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?;
|
||||||
text.push(b'\n');
|
text.push(b'\n');
|
||||||
write_atomic(path, &text, 0o600).map_err(|e| format!("cannot write {}: {e}", path.display()))
|
write_atomic(path, &text, 0o600).map_err(|e| format!("cannot write {}: {e}", path.display()))
|
||||||
|
|||||||
@@ -523,7 +523,6 @@ mod unix {
|
|||||||
let lock = env.repo().join("refs/heads/main.lock");
|
let lock = env.repo().join("refs/heads/main.lock");
|
||||||
std::fs::write(&lock, "").unwrap();
|
std::fs::write(&lock, "").unwrap();
|
||||||
let rec = env.wait_apply(&id).await;
|
let rec = env.wait_apply(&id).await;
|
||||||
std::fs::remove_file(&lock).unwrap();
|
|
||||||
assert_eq!(rec["state"], "needs_attention", "{rec}");
|
assert_eq!(rec["state"], "needs_attention", "{rec}");
|
||||||
// Edge was still told to drop the trial: visitors get the last good config.
|
// Edge was still told to drop the trial: visitors get the last good config.
|
||||||
let st = env.edge_status().await;
|
let st = env.edge_status().await;
|
||||||
@@ -540,10 +539,14 @@ mod unix {
|
|||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
assert_eq!(r.status, 409);
|
assert_eq!(r.status, 409);
|
||||||
// A control restart does not push the unverified head to edge.
|
// A control restart (the branch still locked) retries the revert, fails again, and
|
||||||
|
// does not push the unverified head to edge.
|
||||||
env.kill_control();
|
env.kill_control();
|
||||||
env.start_control(None);
|
env.start_control(None);
|
||||||
assert_eq!(env.edge_status().await["config_sha256"], sha256(&good_edge));
|
assert_eq!(env.edge_status().await["config_sha256"], sha256(&good_edge));
|
||||||
|
let o = env.call("GET", "/api/v1/overview", None).await;
|
||||||
|
assert_eq!(o.json["paused"]["code"], "control.paused", "{}", o.text);
|
||||||
|
std::fs::remove_file(&lock).unwrap();
|
||||||
// Restore the last kept version: the way out.
|
// Restore the last kept version: the way out.
|
||||||
let r = env
|
let r = env
|
||||||
.apply(
|
.apply(
|
||||||
@@ -563,16 +566,31 @@ mod unix {
|
|||||||
let good = Echo::start("good").await;
|
let good = Echo::start("good").await;
|
||||||
let sick = Echo::start("sick").await;
|
let sick = Echo::start("sick").await;
|
||||||
sick.health.store(500, std::sync::atomic::Ordering::SeqCst);
|
sick.health.store(500, std::sync::atomic::Ordering::SeqCst);
|
||||||
let mut env = Env::new(EnvSpec { watch_secs: 3, ..Default::default() }).await;
|
let mut env = Env::new(EnvSpec {
|
||||||
|
watch_secs: 3,
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.await;
|
||||||
// A full disk, as far as paused.json is concerned.
|
// A full disk, as far as paused.json is concerned.
|
||||||
env.start_control_env(None, &[("IANITOR_TEST_FAIL_WRITE", "paused.json")]);
|
env.start_control_env(None, &[("IANITOR_TEST_FAIL_WRITE", "paused.json")]);
|
||||||
let kept = env.add_host(host("a.test", &good.url(), true)).await;
|
let kept = env.add_host(host("a.test", &good.url(), true)).await;
|
||||||
let good_edge = env.file("edge/edge.json");
|
let good_edge = env.file("edge/edge.json");
|
||||||
let good_tree = env.git(&["rev-parse", "refs/heads/main^{tree}"]);
|
let good_tree = env.git(&["rev-parse", "refs/heads/main^{tree}"]);
|
||||||
let r = env.call("POST", "/api/v1/hosts", Some(json!({ "host": host("b.test", &sick.url(), true) }))).await;
|
let r = env
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/hosts",
|
||||||
|
Some(json!({ "host": host("b.test", &sick.url(), true) })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
|
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
|
||||||
let deadline = std::time::Instant::now() + Duration::from_secs(10);
|
let deadline = std::time::Instant::now() + Duration::from_secs(10);
|
||||||
while env.call("GET", &format!("/api/v1/applies/{id}"), None).await.json["commit"].is_null() {
|
while env
|
||||||
|
.call("GET", &format!("/api/v1/applies/{id}"), None)
|
||||||
|
.await
|
||||||
|
.json["commit"]
|
||||||
|
.is_null()
|
||||||
|
{
|
||||||
assert!(std::time::Instant::now() < deadline);
|
assert!(std::time::Instant::now() < deadline);
|
||||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||||
}
|
}
|
||||||
@@ -582,7 +600,8 @@ mod unix {
|
|||||||
assert_eq!(rec["state"], "needs_attention", "{rec}");
|
assert_eq!(rec["state"], "needs_attention", "{rec}");
|
||||||
// The pause is not on disk, so the journal must stay, at `reverting`.
|
// The pause is not on disk, so the journal must stay, at `reverting`.
|
||||||
assert!(!env.dir.join("state/paused.json").exists());
|
assert!(!env.dir.join("state/paused.json").exists());
|
||||||
let j: serde_json::Value = serde_json::from_str(&env.file("state/journal.json")).expect("journal kept");
|
let j: serde_json::Value =
|
||||||
|
serde_json::from_str(&env.file("state/journal.json")).expect("journal kept");
|
||||||
assert_eq!(j["stage"], "reverting", "{j}");
|
assert_eq!(j["stage"], "reverting", "{j}");
|
||||||
|
|
||||||
// Restart while the branch is still locked: still no unverified config for edge.
|
// Restart while the branch is still locked: still no unverified config for edge.
|
||||||
@@ -597,7 +616,9 @@ mod unix {
|
|||||||
env.kill_control();
|
env.kill_control();
|
||||||
std::fs::remove_file(&lock).unwrap();
|
std::fs::remove_file(&lock).unwrap();
|
||||||
env.start_control(None);
|
env.start_control(None);
|
||||||
let rec = env.call("GET", &format!("/api/v1/applies/{id}"), None).await;
|
let rec = env
|
||||||
|
.call("GET", &format!("/api/v1/applies/{id}"), None)
|
||||||
|
.await;
|
||||||
assert_eq!(rec.json["state"], "reverted", "{}", rec.text);
|
assert_eq!(rec.json["state"], "reverted", "{}", rec.text);
|
||||||
assert_eq!(env.git(&["rev-parse", "refs/heads/main^{tree}"]), good_tree);
|
assert_eq!(env.git(&["rev-parse", "refs/heads/main^{tree}"]), good_tree);
|
||||||
let o = env.call("GET", "/api/v1/overview", None).await;
|
let o = env.call("GET", "/api/v1/overview", None).await;
|
||||||
|
|||||||
@@ -62,7 +62,13 @@ fn concurrent_creates_from_the_cli_and_the_server_all_survive() {
|
|||||||
let mut clis: Vec<_> = (0..8)
|
let mut clis: Vec<_> = (0..8)
|
||||||
.map(|i| {
|
.map(|i| {
|
||||||
std::process::Command::new(bin)
|
std::process::Command::new(bin)
|
||||||
.args(["token", "create", "--name", &format!("cli{i}"), "--state-dir"])
|
.args([
|
||||||
|
"token",
|
||||||
|
"create",
|
||||||
|
"--name",
|
||||||
|
&format!("cli{i}"),
|
||||||
|
"--state-dir",
|
||||||
|
])
|
||||||
.arg(d.path())
|
.arg(d.path())
|
||||||
.stdout(std::process::Stdio::null())
|
.stdout(std::process::Stdio::null())
|
||||||
.stderr(std::process::Stdio::null())
|
.stderr(std::process::Stdio::null())
|
||||||
@@ -91,7 +97,9 @@ fn losing_share_links_json_never_lowers_the_revocation_epoch() {
|
|||||||
s.stop_all().unwrap();
|
s.stop_all().unwrap();
|
||||||
assert_eq!(revocations(&rev)["epoch"], 2);
|
assert_eq!(revocations(&rev)["epoch"], 2);
|
||||||
std::fs::remove_file(d.join("share-links.json")).unwrap();
|
std::fs::remove_file(d.join("share-links.json")).unwrap();
|
||||||
Shares::new(d.path(), &rev).ensure_revocation_file().unwrap();
|
Shares::new(d.path(), &rev)
|
||||||
|
.ensure_revocation_file()
|
||||||
|
.unwrap();
|
||||||
assert!(
|
assert!(
|
||||||
revocations(&rev)["epoch"].as_u64().unwrap() >= 2,
|
revocations(&rev)["epoch"].as_u64().unwrap() >= 2,
|
||||||
"{}",
|
"{}",
|
||||||
@@ -118,7 +126,9 @@ fn a_lost_deny_list_raises_the_epoch_instead_of_shrinking() {
|
|||||||
assert_eq!(before["epoch"], 0);
|
assert_eq!(before["epoch"], 0);
|
||||||
// The records are gone (or an older backup without the stop is restored).
|
// The records are gone (or an older backup without the stop is restored).
|
||||||
std::fs::remove_file(d.join("share-links.json")).unwrap();
|
std::fs::remove_file(d.join("share-links.json")).unwrap();
|
||||||
Shares::new(d.path(), &rev).ensure_revocation_file().unwrap();
|
Shares::new(d.path(), &rev)
|
||||||
|
.ensure_revocation_file()
|
||||||
|
.unwrap();
|
||||||
let after = revocations(&rev);
|
let after = revocations(&rev);
|
||||||
let still_denied = after["deny"]
|
let still_denied = after["deny"]
|
||||||
.as_array()
|
.as_array()
|
||||||
|
|||||||
Reference in New Issue
Block a user