[control] Tests first: CLI token races, unsaved pause keeps the journal, lost share records never lower the epoch or shrink the deny list (red)

This commit is contained in:
2026-11-07 18:47:00 +01:00
parent 98dad246d3
commit b9e14c6aee
3 changed files with 220 additions and 0 deletions
+48
View File
@@ -558,6 +558,54 @@ mod unix {
env.assert_consistent().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_pause_that_cannot_be_saved_keeps_the_journal_and_a_restart_finishes_the_revert() {
let good = Echo::start("good").await;
let sick = Echo::start("sick").await;
sick.health.store(500, std::sync::atomic::Ordering::SeqCst);
let mut env = Env::new(EnvSpec { watch_secs: 3, ..Default::default() }).await;
// A full disk, as far as paused.json is concerned.
env.start_control_env(None, &[("IANITOR_TEST_FAIL_WRITE", "paused.json")]);
let kept = env.add_host(host("a.test", &good.url(), true)).await;
let good_edge = env.file("edge/edge.json");
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 id = r.json["apply"]["id"].as_str().unwrap().to_owned();
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() {
assert!(std::time::Instant::now() < deadline);
tokio::time::sleep(Duration::from_millis(20)).await;
}
let lock = env.repo().join("refs/heads/main.lock");
std::fs::write(&lock, "").unwrap();
let rec = env.wait_apply(&id).await;
assert_eq!(rec["state"], "needs_attention", "{rec}");
// The pause is not on disk, so the journal must stay, at `reverting`.
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");
assert_eq!(j["stage"], "reverting", "{j}");
// Restart while the branch is still locked: still no unverified config for edge.
env.kill_control();
env.start_control(None);
assert_eq!(env.edge_status().await["config_sha256"], sha256(&good_edge));
assert_eq!(env.file("edge/edge.json"), good_edge);
let o = env.call("GET", "/api/v1/overview", None).await;
assert_eq!(o.json["paused"]["code"], "control.paused", "{}", o.text);
// Restart once the lock is gone: recovery finishes the revert and resumes.
env.kill_control();
std::fs::remove_file(&lock).unwrap();
env.start_control(None);
let rec = env.call("GET", &format!("/api/v1/applies/{id}"), None).await;
assert_eq!(rec.json["state"], "reverted", "{}", rec.text);
assert_eq!(env.git(&["rev-parse", "refs/heads/main^{tree}"]), good_tree);
let o = env.call("GET", "/api/v1/overview", None).await;
assert!(o.json["paused"].is_null(), "{}", o.text);
assert_eq!(o.json["undo"]["target"]["change_id"], kept["id"]);
env.assert_consistent().await;
}
// ------------------------------------------------------------ undo, restore, conflicts
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+9
View File
@@ -257,6 +257,7 @@ caddy_credentials_dir = "{creds}"
fn command(&self) -> Command {
let mut c = Command::new(env!("CARGO_BIN_EXE_ianitor-control"));
c.env_remove("IANITOR_TEST_CRASH_AT");
c.env_remove("IANITOR_TEST_FAIL_WRITE");
c
}
@@ -329,6 +330,11 @@ caddy_credentials_dir = "{creds}"
/// Start the control binary; with `crash_at`, it aborts when an apply reaches that stage.
pub fn start_control(&mut self, crash_at: Option<&str>) {
self.start_control_env(crash_at, &[]);
}
/// Like [`Env::start_control`], with extra environment (fault injection).
pub fn start_control_env(&mut self, crash_at: Option<&str>, envs: &[(&str, &str)]) {
self.log_n += 1;
let log = std::fs::File::create(self.dir.join(&format!("logs/control-{}.log", self.log_n)))
.unwrap();
@@ -338,6 +344,9 @@ caddy_credentials_dir = "{creds}"
if let Some(stage) = crash_at {
c.env("IANITOR_TEST_CRASH_AT", stage);
}
for (k, v) in envs {
c.env(k, v);
}
c.stdout(Stdio::from(log.try_clone().unwrap()))
.stderr(Stdio::from(log));
self.control = Some(ChildGuard(c.spawn().unwrap()));
+163
View File
@@ -0,0 +1,163 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Token and share-link stores (QC fix round 1, M2 and M4): a CLI revoke is never lost to the
//! server recording token use at the same time, and losing `share-links.json` never revives a
//! stopped link.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use ianitor_control::shares::Shares;
use ianitor_control::tokens::{Refusal, Tokens};
use ianitor_core::share::ShareKey;
use ianitor_testkit::proc::TempDir;
use serde_json::Value;
fn revocations(p: &std::path::Path) -> Value {
serde_json::from_slice(&std::fs::read(p).unwrap()).unwrap()
}
#[test]
fn a_cli_revoke_is_not_lost_while_the_server_records_token_use() {
let bin = env!("CARGO_BIN_EXE_ianitor-control");
let rounds = 20;
let mut lost = 0;
for _ in 0..rounds {
let d = TempDir::new("tok-race");
let server = Tokens::new(d.path());
let values: Vec<_> = (0..150)
.map(|i| server.create(&format!("t{i}"), None).unwrap())
.collect();
let victim = values[75].0.id.clone();
let mut cli = std::process::Command::new(bin)
.args(["token", "revoke", &victim, "--state-dir"])
.arg(d.path())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.unwrap();
for (_, v) in &values {
let _ = server.check(Some(&format!("Bearer {v}")));
}
assert!(cli.wait().unwrap().success());
if !matches!(
server.check(Some(&format!("Bearer {}", values[75].1))),
Err(Refusal::Revoked(_))
) {
lost += 1;
}
}
assert_eq!(
lost, 0,
"the CLI said revoked but the token still worked in {lost}/{rounds} rounds"
);
}
#[test]
fn concurrent_creates_from_the_cli_and_the_server_all_survive() {
let bin = env!("CARGO_BIN_EXE_ianitor-control");
let d = TempDir::new("tok-create");
let server = Tokens::new(d.path());
let mut clis: Vec<_> = (0..8)
.map(|i| {
std::process::Command::new(bin)
.args(["token", "create", "--name", &format!("cli{i}"), "--state-dir"])
.arg(d.path())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.unwrap()
})
.collect();
for i in 0..40 {
server.create(&format!("srv{i}"), None).unwrap();
}
for c in &mut clis {
assert!(c.wait().unwrap().success());
}
assert_eq!(server.list().unwrap().len(), 48);
}
#[test]
fn losing_share_links_json_never_lowers_the_revocation_epoch() {
let d = TempDir::new("epoch");
let rev = d.join("share-revocations.json");
let s = Shares::new(d.path(), &rev);
let key = ShareKey::new(&[9u8; 32]).unwrap();
let m = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
s.stop(&m.record.id).unwrap();
s.stop_all().unwrap();
s.stop_all().unwrap();
assert_eq!(revocations(&rev)["epoch"], 2);
std::fs::remove_file(d.join("share-links.json")).unwrap();
Shares::new(d.path(), &rev).ensure_revocation_file().unwrap();
assert!(
revocations(&rev)["epoch"].as_u64().unwrap() >= 2,
"{}",
revocations(&rev)
);
// Minting after the loss continues from there.
let m2 = Shares::new(d.path(), &rev)
.mint(&key, "a.test", "/", 3600, None, None, "t")
.unwrap();
assert!(m2.record.epoch >= 2);
}
#[test]
fn a_lost_deny_list_raises_the_epoch_instead_of_shrinking() {
let d = TempDir::new("deny");
let rev = d.join("share-revocations.json");
let s = Shares::new(d.path(), &rev);
let key = ShareKey::new(&[9u8; 32]).unwrap();
let a = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
let _b = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
s.stop(&a.record.id).unwrap();
let before = revocations(&rev);
assert_eq!(before["deny"][0], a.record.id);
assert_eq!(before["epoch"], 0);
// The records are gone (or an older backup without the stop is restored).
std::fs::remove_file(d.join("share-links.json")).unwrap();
Shares::new(d.path(), &rev).ensure_revocation_file().unwrap();
let after = revocations(&rev);
let still_denied = after["deny"]
.as_array()
.unwrap()
.iter()
.any(|x| x == &before["deny"][0]);
assert!(
still_denied || after["epoch"].as_u64().unwrap() > 0,
"stopped link {} works again: {after}",
a.record.id
);
}
#[test]
fn a_deny_list_that_would_overflow_raises_the_epoch() {
let d = TempDir::new("overflow");
let rev = d.join("share-revocations.json");
let s = Shares::new(d.path(), &rev);
let t = ianitor_control::util::now();
let links: Vec<Value> = (0..10_050u32)
.map(|i| {
serde_json::json!({
"id": format!("{:032x}", i + 1), "hostname": "a.test", "path_prefix": "/", "epoch": 0,
"created_at": t, "expires_at": t + 3600, "has_password": false, "created_by": "t",
"stopped_at": t
})
})
.collect();
std::fs::write(
d.join("share-links.json"),
serde_json::json!({ "epoch": 0, "links": links }).to_string(),
)
.unwrap();
s.ensure_revocation_file().unwrap();
let r = revocations(&rev);
assert!(
r["epoch"].as_u64().unwrap() >= 1,
"an overflowing deny list must raise the epoch: {}",
r["epoch"]
);
assert!(r["deny"].as_array().unwrap().len() < 10_000);
}