Files
ianitor/crates/control/tests/apply.rs
T

1244 lines
49 KiB
Rust

// 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/.
//! The apply pipeline (ROADMAP §6 phase 2, tests first): a failed health check reverts the
//! commit and restores the previous edge config; a control crash at any stage leaves edge on
//! the last good config and recovery makes repository, files and edge agree; concurrent
//! applies are serialised; Undo names its target; kept changes are pushed, and a failed push
//! keeps the change.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
#[cfg(unix)]
mod common;
#[cfg(not(unix))]
#[test]
fn skipped_on_windows() {
eprintln!(
"SKIPPED on Windows: {} needs Linux (edge admin socket); run it in WSL2",
file!()
);
}
#[cfg(unix)]
mod unix {
use std::time::Duration;
use crate::common::{Env, EnvSpec, host, sha256};
use ianitor_testkit::client::{self, Req};
use ianitor_testkit::upstream::Echo;
use serde_json::json;
async fn get(env: &Env, hostname: &str) -> ianitor_testkit::client::Resp {
client::https(
env.opts.https_listen,
hostname,
env.roots(),
&Req::get(hostname, "/"),
)
.await
.unwrap()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_failed_health_check_reverts_the_commit_and_restores_the_previous_edge_config() {
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::default()).await;
env.start_control(None);
let r = env.add_host(host("a.test", &good.url(), true)).await;
assert_eq!(r["state"], "kept", "{r}");
assert_eq!(r["reason"]["code"], "apply.kept");
let kept_head = env.head();
let kept_edge = env.file("edge/edge.json");
assert_eq!(env.edge_status().await["config_sha256"], sha256(&kept_edge));
let body: serde_json::Value =
serde_json::from_slice(&get(&env, "a.test").await.body).unwrap();
assert_eq!(body["upstream"], "good");
// Point it at an upstream whose health check fails: reverted, with the reason.
let r = env
.apply(
"PUT",
"/api/v1/hosts/a.test",
Some(json!({ "host": host("a.test", &sick.url(), true), "base_rev": kept_head })),
)
.await;
assert_eq!(r["state"], "reverted", "{r}");
assert_eq!(r["reason"]["code"], "apply.reverted.server_error", "{r}");
assert_eq!(r["reason"]["hostname"], "a.test");
assert!(
r["reason"]["message"]
.as_str()
.unwrap()
.contains("a.test was not changed")
);
assert_eq!(r["attempted_host"]["upstreams"][0], sick.url());
// The commit is reverted in git (history keeps both), and the tree is the kept one.
let log = env.git(&["log", "--format=%s", "refs/heads/main"]);
let subjects: Vec<&str> = log.lines().collect();
assert!(
subjects[0].starts_with("Revert \"Changed a.test\""),
"{log}"
);
assert_eq!(subjects[1], "Changed a.test");
assert_eq!(
env.git(&["rev-parse", "refs/heads/main^{tree}"]),
env.git(&["rev-parse", &format!("{kept_head}^{{tree}}")])
);
// Edge serves the previous config again; the files never left it.
assert_eq!(env.file("edge/edge.json"), kept_edge);
env.assert_consistent().await;
let body: serde_json::Value =
serde_json::from_slice(&get(&env, "a.test").await.body).unwrap();
assert_eq!(body["upstream"], "good");
// History shows the attempt as one entry.
let h = env.call("GET", "/api/v1/history", None).await;
let entries = h.json["entries"].as_array().unwrap();
assert_eq!(entries.len(), 2, "{}", h.text);
assert_eq!(entries[0]["state"], "reverted");
assert_eq!(entries[1]["state"], "kept");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn only_touched_hosts_are_judged_and_a_host_already_down_never_reverts() {
let good = Echo::start("good").await;
let flaky = Echo::start("flaky").await;
let sick = Echo::start("sick").await;
sick.health.store(503, std::sync::atomic::Ordering::SeqCst);
let mut env = Env::new(EnvSpec::default()).await;
env.start_control(None);
// Without a health check, the watch only checks that the host answers.
let r = env.add_host(host("b.test", &good.url(), false)).await;
assert_eq!(r["state"], "kept", "{r}");
assert_eq!(r["reason"]["code"], "apply.kept.no_watch", "{r}");
// A host that is up when added and goes down later...
assert_eq!(
env.add_host(host("c.test", &flaky.url(), true)).await["state"],
"kept"
);
flaky.health.store(500, std::sync::atomic::Ordering::SeqCst);
tokio::time::sleep(Duration::from_secs(3)).await;
let o = env.call("GET", "/api/v1/overview", None).await;
let c = o.json["hosts"]
.as_array()
.unwrap()
.iter()
.find(|h| h["hostname"] == "c.test")
.unwrap()
.clone();
assert_eq!(c["health"]["state"], "down", "{}", o.text);
assert_eq!(c["health"]["failure"]["kind"], "server_error");
// ...does not stop other changes (only touched hosts are judged),
assert_eq!(
env.add_host(host("d.test", &good.url(), true)).await["state"],
"kept"
);
// and an edit of the host that was already down is not reverted for it.
let mut edited = host("c.test", &flaky.url(), true);
edited["websockets"] = json!(false);
let r = env
.apply(
"PUT",
"/api/v1/hosts/c.test",
Some(json!({ "host": edited })),
)
.await;
assert_eq!(r["state"], "kept", "{r}");
// A new host that fails its check is reverted.
let r = env.add_host(host("e.test", &sick.url(), true)).await;
assert_eq!(r["state"], "reverted", "{r}");
// Removing a host has nothing to watch and is kept.
let r = env.apply("DELETE", "/api/v1/hosts/b.test", None).await;
assert_eq!(r["state"], "kept", "{r}");
assert_eq!(r["steps"][4]["state"], "skipped");
env.assert_consistent().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn edge_refusing_a_config_fails_the_apply_and_nothing_changes() {
let good = Echo::start("good").await;
let mut env = Env::new(EnvSpec::default()).await;
env.start_control(None);
assert_eq!(
env.add_host(host("a.test", &good.url(), false)).await["state"],
"kept"
);
let before = env.head();
// No certificate for this name: edge refuses the config.
std::fs::remove_file(env.dir.join("certs/d.test.crt")).unwrap();
let r = env.add_host(host("d.test", &good.url(), false)).await;
assert_eq!(r["state"], "failed", "{r}");
assert_eq!(r["reason"]["code"], "apply.failed.reload");
assert!(
r["reason"]["detail"].as_str().unwrap().contains("d.test"),
"{r}"
);
assert_eq!(
env.git(&["rev-parse", "refs/heads/main^{tree}"]),
env.git(&["rev-parse", &format!("{before}^{{tree}}")])
);
env.assert_consistent().await;
assert_eq!(get(&env, "a.test").await.status, 200);
}
// ------------------------------------------------------------ crash safety
/// Kill control at `stage` during an apply; edge must be on the last good config, and a
/// restarted control must bring repository, files and edge back in line.
async fn crash_at(stage: &str) {
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::default()).await;
env.start_control(None);
assert_eq!(
env.add_host(host("a.test", &good.url(), true)).await["state"],
"kept"
);
let good_edge = env.file("edge/edge.json");
let good_head = env.head();
env.kill_control();
env.start_control(Some(stage));
// The reverting stage is reached by a change that fails its watch.
let upstream = if stage == "reverting" {
sick.url()
} else {
good.url()
};
let r = env
.call(
"POST",
"/api/v1/hosts",
Some(json!({ "host": host("b.test", &upstream, true) })),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
let exit = env.wait_control_exit(Duration::from_secs(30));
assert!(
exit.is_some(),
"control did not stop at {stage}:\n{}",
env.control_log()
);
let confirmed = matches!(stage, "confirmed" | "promoted");
// edge.json on disk is always the last good config: the old one, unless edge had
// already confirmed the new one.
if !confirmed {
assert_eq!(
env.file("edge/edge.json"),
good_edge,
"{stage}: edge.json untouched"
);
}
// A trial edge was serving reverts by itself at its deadline (watch 2 s + margin 2 s).
tokio::time::sleep(Duration::from_secs(5)).await;
let st = env.edge_status().await;
assert!(st["trial"].is_null(), "{stage}: trial still running: {st}");
if !confirmed {
assert_eq!(
st["config_sha256"],
sha256(&good_edge),
"{stage}: edge back on the last good config"
);
assert_eq!(get(&env, "a.test").await.status, 200);
}
// Recovery.
env.start_control(None);
let rec = env
.call("GET", &format!("/api/v1/applies/{id}"), None)
.await;
assert_eq!(rec.status, 200, "{}", rec.text);
if confirmed {
assert_eq!(rec.json["state"], "kept", "{stage}: {}", rec.text);
} else if stage == "prepared" {
assert_eq!(rec.json["state"], "failed", "{stage}: {}", rec.text);
assert_eq!(env.head(), good_head, "{stage}: branch never moved");
} else {
assert_eq!(rec.json["state"], "reverted", "{stage}: {}", rec.text);
assert_eq!(
rec.json["reason"]["code"],
if stage == "reverting" {
"apply.reverted.server_error"
} else {
"apply.interrupted"
},
"{stage}: {}",
rec.text
);
assert_eq!(
env.git(&["rev-parse", "refs/heads/main^{tree}"]),
env.git(&["rev-parse", &format!("{good_head}^{{tree}}")]),
"{stage}: the change is reverted in git"
);
}
env.assert_consistent().await;
// And applies work again afterwards.
let r = env.add_host(host("c.test", &good.url(), false)).await;
assert_eq!(r["state"], "kept", "{stage}: {r}");
env.assert_consistent().await;
}
macro_rules! crash_tests {
($($name:ident => $stage:literal),* $(,)?) => {$(
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn $name() {
crash_at($stage).await;
}
)*};
}
crash_tests! {
crash_after_the_commit_object_is_made => "prepared",
crash_after_the_branch_moved => "committed",
crash_after_the_trial_files_are_written => "trial_written",
crash_after_edge_loaded_the_trial => "trial_loaded",
crash_during_the_watch => "watching",
crash_after_the_watch => "watched",
crash_after_edge_confirmed => "confirmed",
crash_after_the_files_were_promoted => "promoted",
crash_while_reverting => "reverting",
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn an_edge_restart_during_the_watch_reverts_and_edge_starts_from_the_last_good_config() {
let good = Echo::start("good").await;
let mut env = Env::new(EnvSpec {
watch_secs: 6,
..Default::default()
})
.await;
env.start_control(None);
assert_eq!(
env.add_host(host("a.test", &good.url(), true)).await["state"],
"kept"
);
let good_edge = env.file("edge/edge.json");
let r = env
.call(
"POST",
"/api/v1/hosts",
Some(json!({ "host": host("b.test", &good.url(), true) })),
)
.await;
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
tokio::time::sleep(Duration::from_secs(2)).await;
env.stop_edge();
env.start_edge();
assert_eq!(env.edge_status().await["config_sha256"], sha256(&good_edge));
let rec = env.wait_apply(&id).await;
assert_eq!(rec["state"], "reverted", "{rec}");
assert_eq!(rec["reason"]["code"], "apply.reverted.edge_lost");
env.assert_consistent().await;
}
// ------------------------------------------------------------ serialisation
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_applies_are_serialised() {
let good = Echo::start("good").await;
let mut env = Env::new(EnvSpec {
watch_secs: 1,
..Default::default()
})
.await;
env.start_control(None);
let names = ["a.test", "b.test", "c.test", "d.test", "e.test"];
let env_ref = &env;
let posts = names.iter().map(|n| {
let body = json!({ "host": host(n, &good.url(), true) });
async move { env_ref.call("POST", "/api/v1/hosts", Some(body)).await }
});
let answers = futures_join(posts).await;
let mut ids = Vec::new();
for a in &answers {
assert_eq!(a.status, 202, "{}", a.text);
ids.push(a.json["apply"]["id"].as_str().unwrap().to_owned());
}
// While one runs, the others say they are queued behind it.
let queued = env
.call("GET", &format!("/api/v1/applies/{}", ids[4]), None)
.await;
let st = queued.json["state"].as_str().unwrap().to_owned();
if st == "queued" {
assert!(
queued.json["queue"]["position"].as_u64().unwrap() >= 1,
"{}",
queued.text
);
}
let mut spans = Vec::new();
for id in &ids {
let r = env.wait_apply(id).await;
assert_eq!(r["state"], "kept", "{r}");
spans.push((
r["started_at"].as_str().unwrap().to_owned(),
r["finished_at"].as_str().unwrap().to_owned(),
r["commit"].as_str().unwrap().to_owned(),
));
}
// One after another: the five commits form one linear chain at the head (nothing
// lost, nothing interleaved). Timestamps have one-second resolution, so they are not
// compared.
let commits: Vec<String> = spans.iter().map(|s| s.2.clone()).collect();
let mut chain = Vec::new();
let mut c = env.head();
for _ in 0..commits.len() {
chain.push(c.clone());
c = env.git(&["rev-parse", &format!("{c}^")]);
}
let mut sorted_chain = chain.clone();
sorted_chain.sort();
let mut sorted_commits = commits.clone();
sorted_commits.sort();
assert_eq!(
sorted_chain, sorted_commits,
"a linear chain of the five commits"
);
let files = env.head_files();
for n in names {
assert!(
files.iter().any(|(p, _)| p == &format!("hosts/{n}.toml")),
"{n} missing"
);
}
env.assert_consistent().await;
}
async fn futures_join<F: std::future::Future>(fs: impl Iterator<Item = F>) -> Vec<F::Output> {
let mut out = Vec::new();
let handles: Vec<_> = fs.collect();
// Start all at once: poll them together.
let mut pinned: Vec<std::pin::Pin<Box<F>>> = handles.into_iter().map(Box::pin).collect();
let mut results: Vec<Option<F::Output>> = (0..pinned.len()).map(|_| None).collect();
std::future::poll_fn(|cx| {
let mut pending = false;
for (i, f) in pinned.iter_mut().enumerate() {
if results[i].is_none() {
match f.as_mut().poll(cx) {
std::task::Poll::Ready(v) => results[i] = Some(v),
std::task::Poll::Pending => pending = true,
}
}
}
if pending {
std::task::Poll::Pending
} else {
std::task::Poll::Ready(())
}
})
.await;
for r in results {
out.push(r.unwrap());
}
out
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_queued_apply_can_be_cancelled() {
let good = Echo::start("good").await;
let mut env = Env::new(EnvSpec {
watch_secs: 3,
..Default::default()
})
.await;
env.start_control(None);
let a = env
.call(
"POST",
"/api/v1/hosts",
Some(json!({ "host": host("a.test", &good.url(), true) })),
)
.await;
let b = env
.call(
"POST",
"/api/v1/hosts",
Some(json!({ "host": host("b.test", &good.url(), true) })),
)
.await;
let bid = b.json["apply"]["id"].as_str().unwrap().to_owned();
let r = env
.call("DELETE", &format!("/api/v1/applies/{bid}"), None)
.await;
assert_eq!(r.status, 204, "{}", r.text);
let rb = env.wait_apply(&bid).await;
assert_eq!(rb["state"], "failed");
assert_eq!(rb["reason"]["code"], "apply.cancelled");
let ra = env
.wait_apply(a.json["apply"]["id"].as_str().unwrap())
.await;
assert_eq!(ra["state"], "kept");
// A running or finished apply cannot be cancelled.
let r = env
.call(
"DELETE",
&format!("/api/v1/applies/{}", ra["id"].as_str().unwrap()),
None,
)
.await;
assert_eq!(r.status, 409);
assert!(
!env.head_files()
.iter()
.any(|(p, _)| p == "hosts/b.test.toml")
);
env.assert_consistent().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_revert_that_fails_pauses_changes_until_a_restore() {
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;
env.start_control(None);
let kept = env.add_host(host("a.test", &good.url(), true)).await;
let good_edge = env.file("edge/edge.json");
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();
// While it is being watched, lock the branch so the revert commit cannot land.
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}");
// Edge was still told to drop the trial: visitors get the last good config.
let st = env.edge_status().await;
assert_eq!(st["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);
assert_eq!(o.json["undo"]["blocked"]["code"], "undo.paused");
let r = env
.call(
"POST",
"/api/v1/hosts",
Some(json!({ "host": host("c.test", &good.url(), false) })),
)
.await;
assert_eq!(r.status, 409);
// 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.start_control(None);
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.
let r = env
.apply(
"POST",
"/api/v1/restore",
Some(json!({ "change_id": kept["id"] })),
)
.await;
assert_eq!(r["state"], "kept", "{r}");
let o = env.call("GET", "/api/v1/overview", None).await;
assert!(o.json["paused"].is_null(), "{}", o.text);
env.assert_consistent().await;
}
/// QC fix round 2 (M3 reopened): a Restore while the pause is not saved must not take the
/// `reverting` journal with it, or a restart loads the unverified head.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_restore_while_the_pause_is_unsaved_never_drops_it() {
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;
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 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}");
// Restore (the way out) while the pause still cannot be saved: refused, journal kept.
let r = env
.call(
"POST",
"/api/v1/restore",
Some(json!({ "change_id": kept["id"] })),
)
.await;
if r.status == 202 {
env.wait_apply(r.json["apply"]["id"].as_str().unwrap())
.await;
} else {
assert_eq!(r.status, 409, "{}", r.text);
assert_eq!(r.json["error"]["code"], "control.paused", "{}", r.text);
}
let j: serde_json::Value = serde_json::from_str(&env.file("state/journal.json"))
.expect("the reverting journal is kept");
assert_eq!(j["stage"], "reverting", "{j}");
// The cause goes away; control restarts and finishes the revert, never loading the
// unverified head.
env.kill_control();
std::fs::remove_file(&lock).unwrap();
env.start_control(None);
tokio::time::sleep(Duration::from_secs(1)).await;
assert_eq!(env.edge_status().await["config_sha256"], sha256(&good_edge));
env.assert_consistent().await;
}
/// QC fix round 2: when the config files cannot be written after a confirmed apply,
/// control pauses with the journal kept, still starts (paused) if they cannot be written
/// at the next start either, and resumes once they can.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn unwritable_config_files_pause_and_never_stop_control_from_starting() {
let good = Echo::start("good").await;
let mut env = Env::new(EnvSpec::default()).await;
env.start_control(None);
assert_eq!(
env.add_host(host("a.test", &good.url(), false)).await["state"],
"kept"
);
env.kill_control();
env.start_control_env(None, &[("IANITOR_TEST_FAIL_WRITE", "edge.json")]);
let r = env.add_host(host("b.test", &good.url(), false)).await;
assert_eq!(r["state"], "kept", "{r}");
let j: serde_json::Value =
serde_json::from_str(&env.file("state/journal.json")).expect("journal kept");
assert_eq!(j["stage"], "confirmed", "{j}");
let o = env.call("GET", "/api/v1/overview", None).await;
assert_eq!(o.json["paused"]["code"], "control.paused", "{}", o.text);
// Restart while the file still cannot be written: control starts, paused.
env.kill_control();
env.start_control_env(None, &[("IANITOR_TEST_FAIL_WRITE", "edge.json")]);
let o = env.call("GET", "/api/v1/overview", None).await;
assert_eq!(o.status, 200);
assert_eq!(o.json["paused"]["code"], "control.paused", "{}", o.text);
// Once it can be written, a restart finishes the promotion and changes resume.
env.kill_control();
env.start_control(None);
let o = env.call("GET", "/api/v1/overview", None).await;
assert!(o.json["paused"].is_null(), "{}", o.text);
assert!(
env.head_files()
.iter()
.any(|(p, _)| p == "hosts/b.test.toml")
);
env.assert_consistent().await;
}
/// QC fix round 3: a request during a Restore's watch must not write the unverified head
/// to edge.json (or drop the Restore's journal); after the Restore is reverted, edge serves
/// what it served before.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_request_during_a_restore_watch_never_writes_the_unverified_head() {
async fn upstream_of(env: &Env) -> String {
let r = client::https(
env.opts.https_listen,
"a.test",
env.roots(),
&Req::get("a.test", "/"),
)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&r.body).unwrap_or_default();
format!("{} {}", r.status, v["upstream"].as_str().unwrap_or("?"))
}
let one = Echo::start("one").await;
let two = Echo::start("two").await;
let mut env = Env::new(EnvSpec {
watch_secs: 4,
..Default::default()
})
.await;
env.start_control(None);
let kept1 = env.add_host(host("a.test", &one.url(), true)).await;
assert_eq!(kept1["state"], "kept");
// edge.json cannot be replaced (a non-empty directory in its place): promote fails.
let ej = env.dir.join("edge/edge.json");
std::fs::remove_file(&ej).unwrap();
std::fs::create_dir(&ej).unwrap();
std::fs::write(ej.join("x"), "x").unwrap();
let r = env
.apply(
"PUT",
"/api/v1/hosts/a.test",
Some(json!({ "host": host("a.test", &two.url(), true) })),
)
.await;
assert_eq!(r["state"], "kept", "{r}");
assert_eq!(upstream_of(&env).await, "200 two");
// Restore the first version; its upstream is sick now, so its watch will fail.
one.health.store(500, std::sync::atomic::Ordering::SeqCst);
let r = env
.call(
"POST",
"/api/v1/restore",
Some(json!({ "change_id": kept1["id"] })),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
let deadline = std::time::Instant::now() + Duration::from_secs(20);
loop {
let s = env
.call("GET", &format!("/api/v1/applies/{id}"), None)
.await;
if s.json["state"] == "watching" {
break;
}
assert!(
std::time::Instant::now() < deadline,
"never watched: {}",
s.text
);
tokio::time::sleep(Duration::from_millis(50)).await;
}
// The disk problem goes away; a write request arrives during the watch.
std::fs::remove_dir_all(&ej).unwrap();
let _ = env
.call(
"POST",
"/api/v1/hosts",
Some(json!({ "host": host("a.test", &two.url(), true) })),
)
.await;
assert!(
env.dir.join("state/journal.json").exists(),
"the Restore's journal is still there"
);
assert!(
!ej.exists() || env.file("edge/edge.json").contains(&two.url()),
"edge.json not written from the head under watch"
);
let rec = env.wait_apply(&id).await;
assert_ne!(rec["state"], "kept", "{rec}");
let now = upstream_of(&env).await;
assert_eq!(
now, "200 two",
"after the Restore was undone, edge serves the failed Restore's config ({now})"
);
}
/// Edge gone while a revert runs: control cannot see what edge serves, so it does not
/// claim `reverted`; it pauses, and a restart with edge back finishes the job.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_revert_that_cannot_see_edge_ends_as_needs_attention() {
let good = Echo::start("good").await;
let mut env = Env::new(EnvSpec {
watch_secs: 3,
..Default::default()
})
.await;
env.start_control(None);
assert_eq!(
env.add_host(host("a.test", &good.url(), true)).await["state"],
"kept"
);
let good_edge = env.file("edge/edge.json");
let r = env
.call(
"POST",
"/api/v1/hosts",
Some(json!({ "host": host("b.test", &good.url(), true) })),
)
.await;
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
tokio::time::sleep(Duration::from_millis(1500)).await;
env.stop_edge();
let rec = env.wait_apply(&id).await;
assert_eq!(rec["state"], "needs_attention", "{rec}");
env.start_edge();
env.kill_control();
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.edge_status().await["config_sha256"], sha256(&good_edge));
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)]
async fn undo_names_its_target_and_undo_after_undo_is_a_redo() {
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::default()).await;
env.start_control(None);
let u = env.call("GET", "/api/v1/undo", None).await;
assert_eq!(u.json["blocked"]["code"], "undo.nothing", "{}", u.text);
let a = env.add_host(host("a.test", &good.url(), false)).await;
let b = env.add_host(host("b.test", &good.url(), false)).await;
// A reverted attempt does not become the Undo target.
let failed = env.add_host(host("c.test", &sick.url(), true)).await;
assert_eq!(failed["state"], "reverted");
let u = env.call("GET", "/api/v1/undo", None).await;
assert_eq!(u.json["target"]["change_id"], b["id"], "{}", u.text);
assert_eq!(u.json["target"]["summary"], "Added b.test");
assert_eq!(u.json["effect"], "Removes b.test");
// Undo refuses a target that is not the latest kept change.
let r = env
.call(
"POST",
"/api/v1/undo",
Some(json!({ "target_change_id": a["id"] })),
)
.await;
assert_eq!(r.status, 409, "{}", r.text);
assert_eq!(r.json["error"]["code"], "undo.target_moved");
assert!(
r.json["error"]["message"]
.as_str()
.unwrap()
.contains("Added b.test")
);
let undo = env
.apply(
"POST",
"/api/v1/undo",
Some(json!({ "target_change_id": b["id"] })),
)
.await;
assert_eq!(undo["state"], "kept", "{undo}");
assert_eq!(undo["summary"], "Undid: Added b.test");
assert_eq!(undo["undo_of"], b["id"]);
assert!(
!env.head_files()
.iter()
.any(|(p, _)| p == "hosts/b.test.toml")
);
// Undo again: a redo, and it says so.
let u = env.call("GET", "/api/v1/undo", None).await;
assert_eq!(u.json["target"]["change_id"], undo["id"]);
assert_eq!(u.json["effect"], "Adds b.test back", "{}", u.text);
let redo = env
.apply(
"POST",
"/api/v1/undo",
Some(json!({ "target_change_id": undo["id"] })),
)
.await;
assert_eq!(redo["state"], "kept");
assert!(
env.head_files()
.iter()
.any(|(p, _)| p == "hosts/b.test.toml")
);
// Restore the version after the first change, as a new change.
let p = env
.call(
"GET",
&format!(
"/api/v1/history/{}/restore-preview",
a["id"].as_str().unwrap()
),
None,
)
.await;
assert_eq!(p.json["restorable"], true, "{}", p.text);
assert_eq!(p.json["changes"][0]["hostname"], "b.test");
assert_eq!(p.json["changes"][0]["effect"], "removed");
let head = env.head();
let r = env
.apply(
"POST",
"/api/v1/restore",
Some(json!({ "change_id": a["id"], "base_rev": head })),
)
.await;
assert_eq!(r["state"], "kept", "{r}");
assert_eq!(r["kind"], "restore");
assert_eq!(r["restore_of"], a["id"]);
let names: Vec<String> = env.head_files().into_iter().map(|(p, _)| p).collect();
assert_eq!(names, ["hosts/a.test.toml", "ianitor.toml"]);
// Restoring the same version again: nothing to do.
let r = env
.call(
"POST",
"/api/v1/restore",
Some(json!({ "change_id": r["id"] })),
)
.await;
assert_eq!(r.json["error"]["code"], "restore.same", "{}", r.text);
// A reverted change cannot be restored.
let r = env
.call(
"POST",
"/api/v1/restore",
Some(json!({ "change_id": failed["id"] })),
)
.await;
assert_eq!(r.json["error"]["code"], "restore.not_kept", "{}", r.text);
env.assert_consistent().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn an_edit_from_an_old_form_is_refused_only_if_the_same_host_changed() {
let good = Echo::start("good").await;
let mut env = Env::new(EnvSpec::default()).await;
env.start_control(None);
env.add_host(host("a.test", &good.url(), false)).await;
let form = env.call("GET", "/api/v1/hosts/a.test", None).await;
let rev = form.json["rev"].as_str().unwrap().to_owned();
// Another host changes: no conflict.
env.add_host(host("b.test", &good.url(), false)).await;
let mut edited = host("a.test", &good.url(), false);
edited["websockets"] = json!(false);
let r = env
.apply(
"PUT",
"/api/v1/hosts/a.test",
Some(json!({ "host": edited.clone(), "base_rev": rev })),
)
.await;
assert_eq!(r["state"], "kept", "{r}");
// The same host changed since the form was loaded: refused, with who and when.
edited["access_log"] = json!("truncated");
let r = env
.call(
"PUT",
"/api/v1/hosts/a.test",
Some(json!({ "host": edited, "base_rev": rev })),
)
.await;
assert_eq!(r.status, 409, "{}", r.text);
assert_eq!(r.json["error"]["code"], "change.conflict");
assert_eq!(r.json["error"]["params"]["summary"], "Changed a.test");
}
// ------------------------------------------------------------ push
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn kept_changes_are_pushed_and_a_failed_push_keeps_the_change() {
let good = Echo::start("good").await;
let remote_dir = ianitor_testkit::proc::TempDir::new("remote");
let remote = remote_dir.join("routes-remote.git");
let mut env = Env::new(EnvSpec {
remote: Some(remote.to_string_lossy().into_owned()),
..Default::default()
})
.await;
// The remote does not exist yet: the push fails, the change is still kept.
env.start_control(None);
let r = env.add_host(host("a.test", &good.url(), false)).await;
assert_eq!(r["state"], "kept", "{r}");
tokio::time::sleep(Duration::from_secs(1)).await;
let o = env.call("GET", "/api/v1/overview", None).await;
assert_eq!(
o.json["repo"]["push_error_code"], "push.failed.unreachable",
"{}",
o.text
);
assert!(o.json["repo"]["unpushed"].as_u64().unwrap() >= 1);
assert!(
env.head_files()
.iter()
.any(|(p, _)| p == "hosts/a.test.toml")
);
env.assert_consistent().await;
// Create the remote and push now.
let st = std::process::Command::new("git")
.args(["init", "--bare", "--quiet"])
.arg(&remote)
.status()
.unwrap();
assert!(st.success());
let r = env.call("POST", "/api/v1/repo/push", None).await;
assert_eq!(r.status, 200, "{}", r.text);
assert!(r.json["push_error_code"].is_null(), "{}", r.text);
assert_eq!(r.json["unpushed"], 0);
let remote_head = std::process::Command::new("git")
.env("GIT_DIR", &remote)
.args(["rev-parse", "refs/heads/main"])
.output()
.unwrap();
assert_eq!(
String::from_utf8_lossy(&remote_head.stdout).trim(),
env.head()
);
// The next kept change is pushed by itself.
env.add_host(host("b.test", &good.url(), false)).await;
tokio::time::sleep(Duration::from_secs(2)).await;
let remote_head = std::process::Command::new("git")
.env("GIT_DIR", &remote)
.args(["rev-parse", "refs/heads/main"])
.output()
.unwrap();
assert_eq!(
String::from_utf8_lossy(&remote_head.stdout).trim(),
env.head()
);
}
// ------------------------------------------------------------ share links end to end
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn share_links_end_to_end() {
let good = Echo::start("good").await;
let auth = ianitor_testkit::authelia::MockAuthelia::start().await;
let site = format!("[forward_auth]\nurl = \"{}\"\n", auth.url());
let mut env = Env::new(EnvSpec {
site,
..Default::default()
})
.await;
env.start_control(None);
let mut h = host("share.test", &good.url(), false);
h["auth"] = json!("forward-auth");
assert_eq!(env.add_host(h).await["state"], "kept");
// Links off: refused with the plain-English reason.
let r = env
.call(
"POST",
"/api/v1/hosts/share.test/share-links",
Some(json!({})),
)
.await;
assert_eq!(r.status, 409);
assert_eq!(r.json["error"]["code"], "share.disabled");
let r = env
.apply(
"PATCH",
"/api/v1/hosts/share.test",
Some(json!({ "share_links": true })),
)
.await;
assert_eq!(r["state"], "kept", "{r}");
assert_eq!(r["kind"], "share_links");
let r = env
.call(
"POST",
"/api/v1/hosts/share.test/share-links",
Some(json!({ "path_prefix": "/albums", "expires_in_s": 3600 })),
)
.await;
assert_eq!(r.status, 201, "{}", r.text);
let url = r.json["url"].as_str().unwrap().to_owned();
let id = r.json["id"].as_str().unwrap().to_owned();
assert!(
url.starts_with(&format!(
"https://share.test:{}/albums?share=ish1.",
env.opts.https_listen.port()
)),
"{url}"
);
let path = url
.split_once(&format!(":{}", env.opts.https_listen.port()))
.unwrap()
.1
.to_owned();
let visit = |p: String, cookie: Option<String>| {
let mut req = Req::get("share.test", &p);
if let Some(c) = cookie {
req = req.header("cookie", &c);
}
let (addr, roots) = (env.opts.https_listen, env.roots());
async move {
client::https(addr, "share.test", roots, &req)
.await
.unwrap()
}
};
let r = visit(path.clone(), None).await;
assert_eq!(r.status, 303, "{}", r.text());
let cookie = r
.header("set-cookie")
.unwrap()
.split(';')
.next()
.unwrap()
.to_owned();
assert_eq!(
visit("/albums/x".into(), Some(cookie.clone())).await.status,
200
);
assert_eq!(
visit("/private".into(), Some(cookie.clone())).await.status,
302,
"outside the prefix: sign-in"
);
let list = env.call("GET", "/api/v1/share-links", None).await;
assert_eq!(list.json["items"][0]["state"], "active");
assert!(!list.text.contains("ish1."), "no tokens in the list");
// Stop: refused within seconds.
let r = env
.call("DELETE", &format!("/api/v1/share-links/{id}"), None)
.await;
assert_eq!(r.status, 204);
assert_eq!(
visit("/albums/x".into(), Some(cookie.clone())).await.status,
302
);
let r = visit(path.clone(), None).await;
assert_eq!(r.status, 403);
// replaces: the new link works, the replaced one stops.
let r1 = env
.call(
"POST",
"/api/v1/hosts/share.test/share-links",
Some(json!({})),
)
.await;
let p1 = r1.json["url"]
.as_str()
.unwrap()
.split_once(&format!(":{}", env.opts.https_listen.port()))
.unwrap()
.1
.to_owned();
let r2 = env
.call(
"POST",
"/api/v1/hosts/share.test/share-links",
Some(json!({ "replaces": r1.json["id"], "password": "correct horse" })),
)
.await;
assert_eq!(r2.status, 201, "{}", r2.text);
assert_eq!(r2.json["has_password"], true);
assert_eq!(visit(p1, None).await.status, 403, "replaced link stopped");
// Stop all.
let r = env.call("POST", "/api/v1/share-links/stop-all", None).await;
assert_eq!(r.status, 200);
let p2 = r2.json["url"]
.as_str()
.unwrap()
.split_once(&format!(":{}", env.opts.https_listen.port()))
.unwrap()
.1
.to_owned();
let r = visit(p2, None).await;
// A password link shows its page before anything is proven; the POST is refused.
assert_eq!(r.status, 401);
// Tokens and passwords are not in control's log.
let log = env.control_log();
assert!(!log.contains("ish1."), "token in the control log");
assert!(!log.contains("correct horse"));
}
}