[edge] Tests first: reload under load, refused and trial configs, admin status, share-link visits and prefix escapes (red)
This commit is contained in:
@@ -0,0 +1,403 @@
|
||||
// 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/.
|
||||
|
||||
//! Reload (ROADMAP §8.4, tests first): edge swaps its config in process, so a reload under
|
||||
//! load drops no request and no keep-alive connection; an invalid config is refused and the
|
||||
//! old one keeps serving; a trial config reverts by itself unless control confirms it; the
|
||||
//! admin socket reports health per host and upstream.
|
||||
|
||||
#![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 (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md",
|
||||
file!()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
mod unix {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::common::{Edge, EdgeSpec, host_file, start};
|
||||
use ianitor_testkit::client::{self, Req};
|
||||
use ianitor_testkit::more::KeepAlive;
|
||||
use ianitor_testkit::upstream::Echo;
|
||||
use serde_json::json;
|
||||
|
||||
fn gen_host(echo: &Echo, generation: &str) -> Vec<(String, String)> {
|
||||
vec![host_file(
|
||||
"app.test",
|
||||
&format!(
|
||||
"upstreams = [\"{}\"]\n[[response_headers]]\naction = \"set\"\nname = \"X-Generation\"\nvalue = \"{generation}\"\n",
|
||||
echo.url()
|
||||
),
|
||||
)]
|
||||
}
|
||||
|
||||
async fn generation(edge: &Edge) -> String {
|
||||
let r = client::https(edge.https, "app.test", edge.roots(), &Req::get("app.test", "/"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.status, 200, "{}", r.text());
|
||||
r.header("x-generation").unwrap_or("none").to_owned()
|
||||
}
|
||||
|
||||
fn sha256(text: &str) -> String {
|
||||
ring::digest::digest(&ring::digest::SHA256, text.as_bytes())
|
||||
.as_ref()
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
|
||||
async fn reload_under_load_drops_nothing() {
|
||||
let echo = Echo::start("app").await;
|
||||
let edge = start(EdgeSpec {
|
||||
hosts: gen_host(&echo, "a"),
|
||||
log_level: "warn",
|
||||
..Default::default()
|
||||
});
|
||||
let config_a = edge.config_text.clone();
|
||||
let config_b = edge.compile("", &gen_host(&echo, "b"));
|
||||
|
||||
let clients: usize = std::env::var("IANITOR_RELOAD_CLIENTS")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(32);
|
||||
let secs: u64 = std::env::var("IANITOR_RELOAD_SECS")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(10);
|
||||
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let ok = Arc::new(AtomicU64::new(0));
|
||||
let errors = Arc::new(AtomicU64::new(0));
|
||||
let resets = Arc::new(AtomicU64::new(0));
|
||||
let mut tasks = Vec::new();
|
||||
for _ in 0..clients {
|
||||
let (stop, ok, errors, resets) =
|
||||
(stop.clone(), ok.clone(), errors.clone(), resets.clone());
|
||||
let (addr, roots) = (edge.https, edge.roots());
|
||||
tasks.push(tokio::spawn(async move {
|
||||
let mut conn = KeepAlive::connect(addr, "app.test", roots).await.unwrap();
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let mut latencies = Vec::new();
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
let t = Instant::now();
|
||||
match conn.send(&Req::get("app.test", "/load")).await {
|
||||
Ok(r) if r.status == 200 => {
|
||||
ok.fetch_add(1, Ordering::Relaxed);
|
||||
seen.insert(r.header("x-generation").unwrap_or("none").to_owned());
|
||||
latencies.push(t.elapsed());
|
||||
}
|
||||
Ok(_) => {
|
||||
errors.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
Err(_) => {
|
||||
// The keep-alive connection is gone.
|
||||
resets.fetch_add(1, Ordering::Relaxed);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
(seen, latencies)
|
||||
}));
|
||||
}
|
||||
|
||||
let started = Instant::now();
|
||||
let mut reloads = 0u64;
|
||||
let mut refused = 0u64;
|
||||
while started.elapsed() < Duration::from_secs(secs) {
|
||||
let text = if reloads % 2 == 0 { &config_b } else { &config_a };
|
||||
let tmp = edge.config_path().with_extension("tmp");
|
||||
std::fs::write(&tmp, text).unwrap();
|
||||
std::fs::rename(&tmp, edge.config_path()).unwrap();
|
||||
let r = edge.admin("POST", "/v1/reload", None).await;
|
||||
if r.status == 200 {
|
||||
reloads += 1;
|
||||
} else {
|
||||
refused += 1;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
let mut all_latencies = Vec::new();
|
||||
let mut both = 0;
|
||||
for t in tasks {
|
||||
let (seen, lat) = t.await.unwrap();
|
||||
if seen.contains("a") && seen.contains("b") {
|
||||
both += 1;
|
||||
}
|
||||
all_latencies.extend(lat);
|
||||
}
|
||||
all_latencies.sort();
|
||||
let pct = |p: f64| {
|
||||
all_latencies
|
||||
.get(((all_latencies.len() as f64 - 1.0) * p) as usize)
|
||||
.copied()
|
||||
.unwrap_or_default()
|
||||
};
|
||||
println!(
|
||||
"RELOAD UNDER LOAD: {clients} keep-alive clients, {secs} s, {reloads} reloads ({refused} refused), \
|
||||
{} requests ok, {} errors, {} connection resets, {both}/{clients} connections saw both configs, \
|
||||
latency p50 {:?} p99 {:?} max {:?}",
|
||||
ok.load(Ordering::Relaxed),
|
||||
errors.load(Ordering::Relaxed),
|
||||
resets.load(Ordering::Relaxed),
|
||||
pct(0.5),
|
||||
pct(0.99),
|
||||
pct(1.0),
|
||||
);
|
||||
assert_eq!(refused, 0, "{}", edge.stderr());
|
||||
assert!(reloads >= secs * 5, "only {reloads} reloads");
|
||||
assert_eq!(errors.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(resets.load(Ordering::Relaxed), 0);
|
||||
assert!(ok.load(Ordering::Relaxed) > 1000);
|
||||
assert_eq!(
|
||||
both, clients,
|
||||
"every keep-alive connection must pick up new configs"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_invalid_config_is_refused_and_the_old_one_keeps_serving() {
|
||||
let echo = Echo::start("app").await;
|
||||
let edge = start(EdgeSpec {
|
||||
hosts: gen_host(&echo, "a"),
|
||||
..Default::default()
|
||||
});
|
||||
let before = edge.admin("GET", "/v1/status", None).await;
|
||||
assert_eq!(before.status, 200, "{}", before.text);
|
||||
let sha = before.json["config_sha256"].as_str().unwrap().to_owned();
|
||||
assert_eq!(sha, sha256(&edge.config_text));
|
||||
|
||||
let good_b = edge.compile("", &gen_host(&echo, "b"));
|
||||
let mut broken_cert: serde_json::Value = serde_json::from_str(&good_b).unwrap();
|
||||
broken_cert["hosts"][0]["tls"]["cert"] = json!("/nonexistent/app.test.crt");
|
||||
let mut moved: serde_json::Value = serde_json::from_str(&good_b).unwrap();
|
||||
moved["https_listen"] = json!("127.0.0.1:1");
|
||||
let mut old_version: serde_json::Value = serde_json::from_str(&good_b).unwrap();
|
||||
old_version["version"] = json!(1);
|
||||
let mut share_without_key: serde_json::Value = serde_json::from_str(&good_b).unwrap();
|
||||
share_without_key["hosts"][0]["share_links"] = json!(true);
|
||||
std::fs::remove_file(edge.dir.join("creds/share-link-key")).unwrap();
|
||||
|
||||
for (what, text) in [
|
||||
("not JSON", "{ not json".to_owned()),
|
||||
("unknown field", good_b.replace("\"hosts\"", "\"hostz\"")),
|
||||
("missing certificate", broken_cert.to_string()),
|
||||
("listen address change", moved.to_string()),
|
||||
("old version", old_version.to_string()),
|
||||
("share links without key", share_without_key.to_string()),
|
||||
] {
|
||||
std::fs::write(edge.config_path(), &text).unwrap();
|
||||
let r = edge.admin("POST", "/v1/reload", None).await;
|
||||
assert_eq!(r.status, 422, "{what}: {}", r.text);
|
||||
assert!(
|
||||
r.json["error"].as_str().is_some_and(|e| !e.is_empty()),
|
||||
"{what}: {}",
|
||||
r.text
|
||||
);
|
||||
assert_eq!(generation(&edge).await, "a", "{what}");
|
||||
let s = edge.admin("GET", "/v1/status", None).await;
|
||||
assert_eq!(s.json["config_sha256"], sha, "{what}");
|
||||
}
|
||||
// A missing file is refused too.
|
||||
std::fs::remove_file(edge.config_path()).unwrap();
|
||||
assert_eq!(edge.admin("POST", "/v1/reload", None).await.status, 422);
|
||||
assert_eq!(generation(&edge).await, "a");
|
||||
|
||||
// And a good one is taken.
|
||||
std::fs::write(edge.config_path(), &good_b).unwrap();
|
||||
let r = edge.admin("POST", "/v1/reload", None).await;
|
||||
assert_eq!(r.status, 200, "{}", r.text);
|
||||
assert_eq!(r.json["config_sha256"], sha256(&good_b));
|
||||
assert_eq!(generation(&edge).await, "b");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_trial_reverts_by_itself_unless_confirmed() {
|
||||
let echo = Echo::start("app").await;
|
||||
let edge = start(EdgeSpec {
|
||||
hosts: gen_host(&echo, "a"),
|
||||
..Default::default()
|
||||
});
|
||||
let config_b = edge.compile("", &gen_host(&echo, "b"));
|
||||
std::fs::write(edge.trial_path(), &config_b).unwrap();
|
||||
|
||||
// Not confirmed: back to "a" after the deadline, without anyone asking.
|
||||
let r = edge
|
||||
.admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 2 })))
|
||||
.await;
|
||||
assert_eq!(r.status, 200, "{}", r.text);
|
||||
let trial_sha = r.json["config_sha256"].as_str().unwrap().to_owned();
|
||||
assert_eq!(trial_sha, sha256(&config_b));
|
||||
assert_eq!(generation(&edge).await, "b");
|
||||
let s = edge.admin("GET", "/v1/status", None).await;
|
||||
assert_eq!(s.json["trial"]["config_sha256"], trial_sha);
|
||||
// No reload and no second trial while one runs.
|
||||
assert_eq!(edge.admin("POST", "/v1/reload", None).await.status, 409);
|
||||
assert_eq!(
|
||||
edge.admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 2 })))
|
||||
.await
|
||||
.status,
|
||||
409
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(3500)).await;
|
||||
assert_eq!(generation(&edge).await, "a");
|
||||
let s = edge.admin("GET", "/v1/status", None).await;
|
||||
assert!(s.json["trial"].is_null(), "{}", s.text);
|
||||
assert_eq!(s.json["config_sha256"], sha256(&edge.config_text));
|
||||
// Confirming a trial that already reverted fails.
|
||||
let r = edge
|
||||
.admin("POST", "/v1/confirm", Some(json!({ "config_sha256": trial_sha })))
|
||||
.await;
|
||||
assert_eq!(r.status, 409, "{}", r.text);
|
||||
|
||||
// Confirmed: stays.
|
||||
let r = edge
|
||||
.admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 2 })))
|
||||
.await;
|
||||
assert_eq!(r.status, 200, "{}", r.text);
|
||||
let wrong = edge
|
||||
.admin("POST", "/v1/confirm", Some(json!({ "config_sha256": "00" })))
|
||||
.await;
|
||||
assert_eq!(wrong.status, 409);
|
||||
let r = edge
|
||||
.admin("POST", "/v1/confirm", Some(json!({ "config_sha256": trial_sha })))
|
||||
.await;
|
||||
assert_eq!(r.status, 200, "{}", r.text);
|
||||
tokio::time::sleep(Duration::from_millis(2500)).await;
|
||||
assert_eq!(generation(&edge).await, "b");
|
||||
|
||||
// Aborted: back at once. Abort is idempotent.
|
||||
std::fs::write(edge.trial_path(), &edge.config_text).unwrap();
|
||||
let r = edge
|
||||
.admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 30 })))
|
||||
.await;
|
||||
assert_eq!(r.status, 200, "{}", r.text);
|
||||
assert_eq!(generation(&edge).await, "a");
|
||||
let r = edge.admin("POST", "/v1/abort", None).await;
|
||||
assert_eq!(r.status, 200);
|
||||
assert_eq!(r.json["reverted"], true);
|
||||
assert_eq!(generation(&edge).await, "b");
|
||||
let r = edge.admin("POST", "/v1/abort", None).await;
|
||||
assert_eq!(r.status, 200);
|
||||
assert_eq!(r.json["reverted"], false);
|
||||
|
||||
// A broken trial is refused and nothing changes.
|
||||
std::fs::write(edge.trial_path(), "{}").unwrap();
|
||||
let r = edge
|
||||
.admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 30 })))
|
||||
.await;
|
||||
assert_eq!(r.status, 422);
|
||||
assert_eq!(generation(&edge).await, "b");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn status_reports_health_per_host_and_upstream() {
|
||||
let good = Echo::start("good").await;
|
||||
let sick = Echo::start("sick").await;
|
||||
sick.health.store(503, Ordering::SeqCst);
|
||||
let closed = ianitor_testkit::upstream::closed_port();
|
||||
let plain = Echo::start("plain").await;
|
||||
let edge = start(EdgeSpec {
|
||||
hosts: vec![
|
||||
host_file(
|
||||
"mixed.test",
|
||||
&format!(
|
||||
"upstreams = [\"{}\", \"{}\", \"http://127.0.0.1:{closed}\"]\n[health_check]\npath = \"/healthz\"\ninterval_secs = 1\n",
|
||||
good.url(),
|
||||
sick.url()
|
||||
),
|
||||
),
|
||||
host_file("plain.test", &format!("upstreams = [\"{}\"]\n", plain.url())),
|
||||
],
|
||||
..Default::default()
|
||||
});
|
||||
tokio::time::sleep(Duration::from_millis(2500)).await;
|
||||
let s = edge.admin("GET", "/v1/status", None).await;
|
||||
assert_eq!(s.status, 200, "{}", s.text);
|
||||
let hosts = s.json["hosts"].as_array().unwrap();
|
||||
let mixed = hosts.iter().find(|h| h["hostname"] == "mixed.test").unwrap();
|
||||
assert_eq!(mixed["health_check"], true);
|
||||
let ups = mixed["upstreams"].as_array().unwrap();
|
||||
assert_eq!(ups.len(), 3);
|
||||
assert_eq!(ups[0]["healthy"], true, "{}", s.text);
|
||||
assert_eq!(ups[1]["healthy"], false);
|
||||
assert_eq!(ups[2]["healthy"], false);
|
||||
let last = |u: &serde_json::Value| u["checks"].as_array().unwrap().last().unwrap().clone();
|
||||
assert_eq!(last(&ups[0])["ok"], true);
|
||||
assert!(last(&ups[0])["latency_ms"].is_u64());
|
||||
assert_eq!(last(&ups[1])["kind"], "server_error");
|
||||
assert_eq!(last(&ups[1])["status"], 503);
|
||||
assert_eq!(last(&ups[2])["kind"], "refused");
|
||||
assert!(ups[0]["checks"].as_array().unwrap().len() <= 5);
|
||||
assert!(mixed["certificate"]["state"] == "ok");
|
||||
let plain_h = hosts.iter().find(|h| h["hostname"] == "plain.test").unwrap();
|
||||
assert_eq!(plain_h["health_check"], false);
|
||||
assert!(plain_h["upstreams"][0]["checks"].as_array().unwrap().is_empty());
|
||||
|
||||
// During a trial, watched hosts without a health check get `GET /` probes; any answer
|
||||
// below 500 counts as alive. Hosts with one are checked at least every `every_secs`.
|
||||
std::fs::write(edge.trial_path(), &edge.config_text).unwrap();
|
||||
let r = edge
|
||||
.admin(
|
||||
"POST",
|
||||
"/v1/trial",
|
||||
Some(json!({ "confirm_within_secs": 30, "watch_hosts": ["plain.test"], "watch_every_secs": 1 })),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 200, "{}", r.text);
|
||||
tokio::time::sleep(Duration::from_millis(2500)).await;
|
||||
let s = edge.admin("GET", "/v1/status", None).await;
|
||||
let plain_h = s.json["hosts"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|h| h["hostname"] == "plain.test")
|
||||
.unwrap()
|
||||
.clone();
|
||||
let checks = plain_h["upstreams"][0]["checks"].as_array().unwrap();
|
||||
assert!(!checks.is_empty(), "{}", s.text);
|
||||
assert_eq!(checks.last().unwrap()["ok"], true);
|
||||
assert_eq!(checks.last().unwrap()["source"], "watch");
|
||||
assert!(plain.requests().iter().any(|r| r.path == "/"
|
||||
&& r.header("host") == Some(b"plain.test".as_slice())));
|
||||
edge.admin("POST", "/v1/abort", None).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_admin_socket_is_private() {
|
||||
use std::os::unix::fs::{FileTypeExt, PermissionsExt};
|
||||
let echo = Echo::start("app").await;
|
||||
let edge = start(EdgeSpec {
|
||||
hosts: gen_host(&echo, "a"),
|
||||
..Default::default()
|
||||
});
|
||||
let meta = std::fs::metadata(edge.admin_socket()).unwrap();
|
||||
assert!(meta.file_type().is_socket());
|
||||
assert_eq!(meta.permissions().mode() & 0o007, 0, "no access for others");
|
||||
// Unknown paths and bad bodies get typed errors, not a crash.
|
||||
assert_eq!(edge.admin("GET", "/v1/nope", None).await.status, 404);
|
||||
let r = edge
|
||||
.admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 2, "extra": 1 })))
|
||||
.await;
|
||||
assert_eq!(r.status, 400, "{}", r.text);
|
||||
let r = edge
|
||||
.admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 0 })))
|
||||
.await;
|
||||
assert_eq!(r.status, 400, "{}", r.text);
|
||||
assert_eq!(generation(&edge).await, "a");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user