[edge] Tests first: reload under load, refused and trial configs, admin status, share-link visits and prefix escapes (red)

This commit is contained in:
2026-11-07 17:47:43 +01:00
parent 7c81945771
commit c0ed9c65c5
7 changed files with 1178 additions and 20 deletions
Generated
+1
View File
@@ -1044,6 +1044,7 @@ dependencies = [
"instant-acme",
"log",
"pingora",
"ring",
"rustls",
"rustls-pki-types",
"serde",
+1
View File
@@ -30,6 +30,7 @@ thiserror.workspace = true
[dev-dependencies]
ianitor-testkit.workspace = true
ring.workspace = true
[lints]
workspace = true
+85 -20
View File
@@ -4,20 +4,26 @@
//! Runs the real `ianitor-edge` binary on 127.0.0.1 with a compiled config, a test CA for
//! `tls = "domi"` hosts and a credentials directory. stderr goes to a file the tests inspect.
//! Every edge also gets an admin socket and a share-link revocation file in its directory.
#![allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::net::SocketAddr;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::time::Duration;
use ianitor_core::compile::{self, CompileOptions};
use ianitor_core::{SourceFile, TlsMode, load};
use ianitor_testkit::more::{JsonResp, unix_json};
use ianitor_testkit::proc::{ChildGuard, TempDir, free_port, local, wait_for_port};
use ianitor_testkit::tls::TestCa;
use rustls::RootCertStore;
/// The share-link key written as the `share-link-key` credential of every test edge.
pub const SHARE_KEY: &[u8] = b"edge-test-share-key-0123456789abcdef0123456789";
pub struct Edge {
pub child: ChildGuard,
pub http: SocketAddr,
@@ -25,6 +31,7 @@ pub struct Edge {
pub dir: TempDir,
pub ca: TestCa,
pub config_text: String,
pub opts: CompileOptions,
}
impl Edge {
@@ -53,6 +60,44 @@ impl Edge {
pub fn exited(&mut self) -> Option<std::process::ExitStatus> {
self.child.0.try_wait().unwrap()
}
pub fn admin_socket(&self) -> PathBuf {
self.dir.join("admin.sock")
}
pub fn config_path(&self) -> PathBuf {
self.dir.join("edge.json")
}
pub fn trial_path(&self) -> PathBuf {
self.dir.join("edge.json.trial")
}
pub fn revocations_path(&self) -> PathBuf {
self.dir.join("share-revocations.json")
}
/// Compile routes with this edge's options (same ports, same directories).
pub fn compile(&self, site: &str, hosts: &[(String, String)]) -> String {
compile_with(&self.dir, &self.ca, &self.opts, site, hosts)
}
/// Call the admin socket.
pub async fn admin(
&self,
method: &str,
path: &str,
body: Option<serde_json::Value>,
) -> JsonResp {
unix_json(&self.admin_socket(), method, path, body.as_ref())
.await
.unwrap_or_else(|e| panic!("admin {method} {path}: {e}\n{}", self.stderr()))
}
pub fn write_revocations(&self, epoch: u32, deny: &[String]) {
let v = serde_json::json!({ "epoch": epoch, "deny": deny });
std::fs::write(self.revocations_path(), v.to_string()).unwrap();
}
}
pub struct EdgeSpec<'a> {
@@ -78,14 +123,15 @@ impl Default for EdgeSpec<'_> {
}
}
/// Compile, write certificates and credentials, start the binary. Does not wait for readiness.
pub fn spawn(spec: EdgeSpec<'_>) -> Edge {
let dir = TempDir::new("edge");
for d in ["certs", "state", "creds", "logs"] {
std::fs::create_dir_all(dir.join(d)).unwrap();
}
let sources: Vec<SourceFile> = spec
.hosts
/// Load and compile; write a Domi certificate for every `tls = "domi"` host that has none.
fn compile_with(
dir: &TempDir,
ca: &TestCa,
opts: &CompileOptions,
site: &str,
hosts: &[(String, String)],
) -> String {
let sources: Vec<SourceFile> = hosts
.iter()
.map(|(n, c)| SourceFile {
name: n,
@@ -95,27 +141,38 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge {
let model = load(
&SourceFile {
name: "ianitor.toml",
contents: spec.site,
contents: site,
},
&sources,
)
.expect("valid routes");
let ca = TestCa::new("Ianitor Test CA");
for h in model.hosts() {
if h.tls == TlsMode::Domi {
let crt = dir.join(&format!("certs/{}.crt", h.hostname));
if h.tls == TlsMode::Domi && !crt.exists() {
let leaf = ca.issue(&[h.hostname.as_str()]);
std::fs::write(
dir.join(&format!("certs/{}.crt", h.hostname)),
leaf.cert_pem,
)
.unwrap();
std::fs::write(&crt, leaf.cert_pem).unwrap();
std::fs::write(dir.join(&format!("certs/{}.key", h.hostname)), leaf.key_pem).unwrap();
}
}
compile::edge(&model, opts).unwrap()
}
/// Compile, write certificates and credentials, start the binary. Does not wait for readiness.
pub fn spawn(spec: EdgeSpec<'_>) -> Edge {
let dir = TempDir::new("edge");
for d in ["certs", "state", "creds", "logs"] {
std::fs::create_dir_all(dir.join(d)).unwrap();
}
let ca = TestCa::new("Ianitor Test CA");
std::fs::write(dir.join("creds/share-link-key"), SHARE_KEY).unwrap();
for (name, value) in &spec.secrets {
std::fs::write(dir.join(&format!("creds/{name}")), value).unwrap();
}
std::fs::write(
dir.join("share-revocations.json"),
"{\"epoch\": 0, \"deny\": []}",
)
.unwrap();
let http = local(spec.http_port.unwrap_or_else(free_port));
let https = local(free_port());
@@ -128,12 +185,15 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge {
caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(),
caddy_admin: None,
};
let config_text = compile::edge(&model, &opts).unwrap();
let config_text = compile_with(&dir, &ca, &opts, spec.site, &spec.hosts);
std::fs::write(dir.join("edge.json"), &config_text).unwrap();
let stderr = std::fs::File::create(dir.join("edge.stderr")).unwrap();
let mut cmd = Command::new(env!("CARGO_BIN_EXE_ianitor-edge"));
cmd.arg("--config").arg(dir.join("edge.json"));
cmd.arg("--admin-socket").arg(dir.join("admin.sock"));
cmd.arg("--share-revocations")
.arg(dir.join("share-revocations.json"));
cmd.args(&spec.extra_args);
cmd.env("CREDENTIALS_DIRECTORY", dir.join("creds"));
cmd.env("IANITOR_LOG", spec.log_level);
@@ -147,15 +207,20 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge {
dir,
ca,
config_text,
opts,
}
}
/// Spawn and wait until both listeners accept connections.
/// Spawn and wait until both listeners and the admin socket accept connections.
pub fn start(spec: EdgeSpec<'_>) -> Edge {
let mut e = spawn(spec);
let ok = wait_for_port(e.https, Duration::from_secs(20))
&& wait_for_port(e.http, Duration::from_secs(5));
if !ok || e.exited().is_some() {
let deadline = std::time::Instant::now() + Duration::from_secs(5);
while !e.admin_socket().exists() && std::time::Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(20));
}
if !ok || !e.admin_socket().exists() || e.exited().is_some() {
panic!("ianitor-edge did not start:\n{}", e.stderr());
}
e
+403
View File
@@ -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");
}
}
+413
View File
@@ -0,0 +1,413 @@
// 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/.
//! Share links in edge (ROADMAP §6 phase 2, tests first): a valid link lets the visitor in on
//! its host and prefix only, without forward-auth; the token travels in the URL once and is
//! then a path-scoped cookie; it never reaches the upstream or a log; expired, altered,
//! wrong-host, wrong-path, stopped and password-less tokens are refused; wrong passwords are
//! throttled; no path trick escapes the prefix.
#![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::time::{Duration, SystemTime, UNIX_EPOCH};
use crate::common::{Edge, EdgeSpec, SHARE_KEY, host_file, start};
use ianitor_core::share::{LinkSpec, ShareId, ShareKey, mint};
use ianitor_testkit::authelia::MockAuthelia;
use ianitor_testkit::client::{self, Req, Resp};
use ianitor_testkit::more::https_raw;
use ianitor_testkit::upstream::Echo;
const HOST: &str = "share.test";
fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
fn key() -> ShareKey {
ShareKey::new(SHARE_KEY).unwrap()
}
fn link(host: &str, id: u8, prefix: &str, expires_at: u64, password: Option<&str>) -> String {
mint(
&key(),
host,
&LinkSpec {
id: ShareId([id; 16]),
epoch: 0,
expires_at,
prefix,
password,
},
)
.unwrap()
}
struct Env {
edge: Edge,
echo: Echo,
auth: MockAuthelia,
}
async fn env() -> Env {
let auth = MockAuthelia::start().await;
let echo = Echo::start("app").await;
let site = format!("[forward_auth]\nurl = \"{}\"\n", auth.url());
let edge = start(EdgeSpec {
site: &site,
hosts: vec![
host_file(
HOST,
&format!(
"upstreams = [\"{}\"]\nauth = \"forward-auth\"\nshare_links = true\naccess_log = \"truncated\"\n",
echo.url()
),
),
host_file(
"closed.test",
&format!(
"upstreams = [\"{}\"]\nauth = \"forward-auth\"\nshare_links = false\n",
echo.url()
),
),
],
log_level: "debug",
..Default::default()
});
Env { edge, echo, auth }
}
impl Env {
async fn get(&self, host: &str, path: &str, cookie: Option<&str>) -> Resp {
let mut req = Req::get(host, path);
if let Some(c) = cookie {
req = req.header("cookie", c);
}
client::https(self.edge.https, host, self.edge.roots(), &req)
.await
.unwrap()
}
async fn post_password(&self, token: &str, password: &str) -> Resp {
let body = format!(
"t={}&password={}",
urlencode(token),
urlencode(password)
);
let req = Req::new("POST", HOST, "/.well-known/ianitor/share")
.header("content-type", "application/x-www-form-urlencoded")
.body(body.as_bytes());
client::https(self.edge.https, HOST, self.edge.roots(), &req)
.await
.unwrap()
}
/// Requests the upstream saw (health checks excluded).
fn upstream_paths(&self) -> Vec<String> {
self.echo.proxied().iter().map(|r| r.path.clone()).collect()
}
}
fn urlencode(s: &str) -> String {
s.bytes()
.map(|b| {
if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
(b as char).to_string()
} else {
format!("%{b:02X}")
}
})
.collect()
}
/// The `name=value` part of the share cookie a response sets.
fn share_cookie(r: &Resp) -> String {
let sc = r
.header_all("set-cookie")
.into_iter()
.find(|c| c.starts_with("__Secure-ianitor-share="))
.unwrap_or_else(|| panic!("no share cookie in {:?}", r.headers));
sc.split(';').next().unwrap().to_owned()
}
fn assert_visitor_page(r: &Resp, status: u16, heading: &str) {
assert_eq!(r.status, status, "{}", r.text());
assert!(r.text().contains(heading), "{heading}: {}", r.text());
assert_eq!(r.header("cache-control"), Some("no-store"));
assert_eq!(r.header("referrer-policy"), Some("no-referrer"));
assert!(
r.header("content-security-policy")
.is_some_and(|c| c.contains("default-src 'none'"))
);
assert!(r.header("content-type").unwrap().starts_with("text/html"));
assert!(!r.text().contains("<script"), "no JavaScript");
assert!(!r.text().contains("http://") && !r.text().contains("https://"), "no external requests");
assert!(r.body.len() < 8 * 1024);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_valid_link_lets_the_visitor_in_without_forward_auth() {
let e = env().await;
let t = link(HOST, 1, "/albums", now() + 3600, None);
let r = e
.get(HOST, &format!("/albums/summer?x=1&share={t}&y=2"), None)
.await;
assert_eq!(r.status, 303, "{}", r.text());
assert_eq!(r.header("location"), Some("/albums/summer?x=1&y=2"));
assert_eq!(r.header("referrer-policy"), Some("no-referrer"));
let set = r
.header_all("set-cookie")
.into_iter()
.find(|c| c.starts_with("__Secure-ianitor-share="))
.unwrap()
.to_owned();
for attr in ["Path=/albums", "HttpOnly", "Secure", "SameSite=Lax", "Max-Age="] {
assert!(set.contains(attr), "{attr} missing in {set}");
}
assert!(!set.contains(&t), "the cookie is not the link token");
assert!(e.upstream_paths().is_empty(), "the token request never reached the upstream");
let auth_calls = e.auth.requests().len();
let cookie = share_cookie(&r);
let r = e
.get(HOST, "/albums/summer?x=1&y=2", Some(&format!("{cookie}; other=1")))
.await;
assert_eq!(r.status, 200, "{}", r.text());
assert_eq!(e.auth.requests().len(), auth_calls, "no forward-auth for a share visitor");
let seen = e.echo.proxied();
let last = seen.last().unwrap();
assert_eq!(last.path, "/albums/summer");
let cookie_sent = last
.header("cookie")
.map(|c| String::from_utf8_lossy(c).into_owned())
.unwrap_or_default();
assert!(!cookie_sent.contains("ianitor-share"), "share cookie stripped: {cookie_sent}");
assert!(cookie_sent.contains("other=1"), "other cookies kept: {cookie_sent}");
assert!(last.header("referer").is_none());
// The prefix itself and deeper paths are covered.
assert_eq!(e.get(HOST, "/albums", Some(&cookie)).await.status, 200);
assert_eq!(e.get(HOST, "/albums/a/b/c.jpg", Some(&cookie)).await.status, 200);
// Neither the token nor the cookie appears in any log.
tokio::time::sleep(Duration::from_millis(200)).await;
let logs = e.edge.all_output();
assert!(!logs.contains(&t[5..40]), "token in logs");
assert!(!logs.contains(&cookie[30..60]), "cookie in logs");
assert!(!e.edge.access_log().contains("share="), "query in access log");
for r in e.echo.requests() {
for (_, v) in &r.headers {
assert!(!String::from_utf8_lossy(v).contains(&t[5..40]));
}
}
}
#[tokio::test(flavor = "multi_thread")]
async fn bad_tokens_get_plain_english_pages() {
let e = env().await;
// Expired: the signature proves the date.
let t = link(HOST, 2, "/", now() - 10, None);
let r = e.get(HOST, &format!("/?share={t}"), None).await;
assert_visitor_page(&r, 410, "This link has expired");
// Another host's token, an altered token, a token made with another key.
let other = link("closed.test", 3, "/", now() + 3600, None);
let mut altered = link(HOST, 4, "/", now() + 3600, None);
let last = altered.pop().unwrap();
altered.push(if last == 'A' { 'B' } else { 'A' });
let foreign = mint(
&ShareKey::new(b"another-key-another-key-another-key-0000").unwrap(),
HOST,
&LinkSpec {
id: ShareId([5; 16]),
epoch: 0,
expires_at: now() + 3600,
prefix: "/",
password: None,
},
)
.unwrap();
for bad in [other, altered, foreign, "ish1.garbage".to_owned()] {
let r = e.get(HOST, &format!("/?share={bad}"), None).await;
assert_visitor_page(&r, 403, "This link no longer works");
}
// Escaping: only the hostname and the date come from the request.
let r = e.get(HOST, "/?share=ish1.%3Cscript%3E", None).await;
assert!(!r.text().contains("<script>"));
assert!(e.upstream_paths().is_empty());
// A `share` parameter that is not ours is left alone (goes to the normal sign-in).
let r = e.get(HOST, "/?share=holiday", None).await;
assert_eq!(r.status, 302, "forward-auth portal redirect");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_link_outside_its_prefix_falls_back_to_sign_in_and_never_leaks() {
let e = env().await;
let t = link(HOST, 6, "/albums", now() + 3600, None);
let r = e.get(HOST, &format!("/private?share={t}"), None).await;
assert_eq!(r.status, 302, "normal sign-in: {}", r.text());
// Signed in, the request goes through, but the token is not passed on.
let r = e
.get(
HOST,
&format!("/private?a=1&share={t}"),
Some("authelia_session=good"),
)
.await;
assert_eq!(r.status, 200);
let body: serde_json::Value = serde_json::from_slice(&r.body).unwrap();
assert_eq!(body["query"], "a=1", "token stripped before the upstream");
// On a host without share links the token gives nothing.
let t2 = link("closed.test", 7, "/", now() + 3600, None);
let r = e.get("closed.test", &format!("/?share={t2}"), None).await;
assert_eq!(r.status, 302);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_password_link_asks_checks_and_throttles() {
let e = env().await;
let t = link(HOST, 8, "/docs", now() + 3600, Some("correct horse"));
let r = e.get(HOST, &format!("/docs/a?share={t}"), None).await;
assert_visitor_page(&r, 401, "This link is protected");
assert!(r.text().contains("share.test"));
assert!(r.text().contains("action=\"/.well-known/ianitor/share\""));
assert!(r.text().contains("name=\"password\""));
assert!(r.text().contains("The link works until"));
assert!(share_cookie_absent(&r));
let r = e.post_password(&t, "wrong password").await;
assert_visitor_page(&r, 401, "That password is not right");
assert!(share_cookie_absent(&r));
let r = e.post_password(&t, "correct horse").await;
assert_eq!(r.status, 303, "{}", r.text());
assert_eq!(r.header("location"), Some("/docs"));
let cookie = share_cookie(&r);
assert_eq!(e.get(HOST, "/docs/a", Some(&cookie)).await.status, 200);
// The cookie of a password link cannot be turned into a link that skips the password.
let v = cookie.split_once('=').unwrap().1.to_owned();
let r = e
.get(HOST, &format!("/docs?share={}", v.replacen("iss1.", "ish1.", 1)), None)
.await;
assert_ne!(r.status, 303);
// Five wrong tries a minute, then a pause (the right password too).
let t2 = link(HOST, 9, "/docs", now() + 3600, Some("correct horse"));
for _ in 0..5 {
assert_eq!(e.post_password(&t2, "nope nope").await.status, 401);
}
let r = e.post_password(&t2, "nope nope").await;
assert_visitor_page(&r, 429, "Too many tries");
let r = e.post_password(&t2, "correct horse").await;
assert_eq!(r.status, 429);
// Other links are not affected.
let t3 = link(HOST, 10, "/docs", now() + 3600, Some("correct horse"));
assert_eq!(e.post_password(&t3, "correct horse").await.status, 303);
// The password never reaches a log.
assert!(!e.edge.all_output().contains("correct horse"));
}
fn share_cookie_absent(r: &Resp) -> bool {
!r.header_all("set-cookie")
.iter()
.any(|c| c.starts_with("__Secure-ianitor-share="))
}
#[tokio::test(flavor = "multi_thread")]
async fn no_path_trick_escapes_the_cookie_prefix() {
let e = env().await;
let t = link(HOST, 11, "/a", now() + 3600, None);
let r = e.get(HOST, &format!("/a?share={t}"), None).await;
let cookie = share_cookie(&r);
let before = e.upstream_paths().len();
for path in [
"/ab",
"/A",
"/A/x",
"/b",
"/a/../b",
"/a/%2e%2e/b",
"/a/%2E%2E/b",
"/a/%252e%252e/b",
"/a%2f..%2fb",
"/a//b",
"//a/b",
"/a/..;/b",
"/a/\\..\\b",
"/a\\..\\b",
] {
let raw = format!(
"GET {path} HTTP/1.1\r\nHost: {HOST}\r\nCookie: {cookie}\r\nConnection: close\r\n\r\n"
);
let r = https_raw(e.edge.https, HOST, e.edge.roots(), raw.as_bytes())
.await
.unwrap();
assert_ne!(r.status, 200, "{path} got through: {}", r.text());
}
assert_eq!(
e.upstream_paths().len(),
before,
"no escaped request reached the upstream: {:?}",
e.upstream_paths()
);
}
#[tokio::test(flavor = "multi_thread")]
async fn stopped_links_and_stop_all_take_effect_at_once() {
let e = env().await;
let t = link(HOST, 12, "/", now() + 3600, None);
let keep = link(HOST, 13, "/", now() + 3600, None);
let cookie = share_cookie(&e.get(HOST, &format!("/?share={t}"), None).await);
let keep_cookie = share_cookie(&e.get(HOST, &format!("/?share={keep}"), None).await);
assert_eq!(e.get(HOST, "/", Some(&cookie)).await.status, 200);
e.edge.write_revocations(0, &[ShareId([12; 16]).to_hex()]);
let r = e.edge.admin("POST", "/v1/share-revocations/reload", None).await;
assert_eq!(r.status, 200, "{}", r.text);
assert_eq!(e.get(HOST, "/", Some(&cookie)).await.status, 302, "back to sign-in");
let r = e.get(HOST, &format!("/?share={t}"), None).await;
assert_visitor_page(&r, 403, "This link no longer works");
assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 200);
// Stop all: a new epoch ends every older link.
e.edge.write_revocations(1, &[]);
e.edge.admin("POST", "/v1/share-revocations/reload", None).await;
assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 302);
// Without the admin call, edge notices a changed file within 5 s.
e.edge.write_revocations(0, &[]);
tokio::time::sleep(Duration::from_secs(6)).await;
assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 200);
// A broken file keeps the last good state; a missing one stops all share access.
std::fs::write(e.edge.revocations_path(), "{ broken").unwrap();
let r = e.edge.admin("POST", "/v1/share-revocations/reload", None).await;
assert_eq!(r.status, 422);
assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 200);
std::fs::remove_file(e.edge.revocations_path()).unwrap();
e.edge.admin("POST", "/v1/share-revocations/reload", None).await;
assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 302);
}
}
+1
View File
@@ -9,6 +9,7 @@
pub mod authelia;
pub mod client;
pub mod more;
pub mod proc;
pub mod raw;
pub mod tls;
+274
View File
@@ -0,0 +1,274 @@
// 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/.
//! Clients the phase 2 tests need: raw request bytes over TLS (for paths a URI type refuses,
//! like backslashes), a keep-alive HTTP/1.1 connection that is reused across requests, and
//! JSON over a Unix socket (edge's admin socket) or loopback TCP (the control API).
use std::io;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper_util::rt::TokioIo;
use rustls::RootCertStore;
use rustls_pki_types::ServerName;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use crate::client::{Req, Resp, tls_connector};
const TIMEOUT: Duration = Duration::from_secs(15);
fn other(e: impl std::fmt::Display) -> io::Error {
io::Error::other(e.to_string())
}
/// Parse a complete HTTP/1.1 response (Content-Length, chunked or read-to-close).
pub fn parse_response(raw: &[u8]) -> io::Result<Resp> {
let end = raw
.windows(4)
.position(|w| w == b"\r\n\r\n")
.ok_or_else(|| other("no complete response head"))?;
let head = String::from_utf8_lossy(&raw[..end]).into_owned();
let mut lines = head.split("\r\n");
let status_line = lines.next().unwrap_or_default();
let status: u16 = status_line
.split(' ')
.nth(1)
.and_then(|s| s.parse().ok())
.ok_or_else(|| other(format!("bad status line {status_line:?}")))?;
let headers: Vec<(String, String)> = lines
.filter_map(|l| l.split_once(':'))
.map(|(n, v)| (n.trim().to_ascii_lowercase(), v.trim().to_owned()))
.collect();
let mut body = raw[end + 4..].to_vec();
if headers
.iter()
.any(|(n, v)| n == "transfer-encoding" && v.eq_ignore_ascii_case("chunked"))
{
let mut out = Vec::new();
let mut rest = &body[..];
loop {
let Some(p) = rest.windows(2).position(|w| w == b"\r\n") else {
break;
};
let size = usize::from_str_radix(
String::from_utf8_lossy(&rest[..p]).split(';').next().unwrap_or("0").trim(),
16,
)
.map_err(other)?;
rest = &rest[p + 2..];
if size == 0 || rest.len() < size {
break;
}
out.extend_from_slice(&rest[..size]);
rest = &rest[(size + 2).min(rest.len())..];
}
body = out;
} else if let Some(len) = headers
.iter()
.find(|(n, _)| n == "content-length")
.and_then(|(_, v)| v.parse::<usize>().ok())
{
body.truncate(len);
}
Ok(Resp {
status,
headers,
body,
})
}
/// Send `request` (complete raw bytes, which should ask for `Connection: close`) over a fresh
/// TLS connection and read until the server closes.
pub async fn https_raw(
addr: SocketAddr,
sni: &str,
roots: Arc<RootCertStore>,
request: &[u8],
) -> io::Result<Resp> {
tokio::time::timeout(TIMEOUT, async {
let tcp = TcpStream::connect(addr).await?;
let name = ServerName::try_from(sni.to_owned()).map_err(other)?;
let mut s = tls_connector(roots).connect(name, tcp).await?;
s.write_all(request).await?;
let mut buf = Vec::new();
// A close_notify-less close is fine here.
let _ = s.read_to_end(&mut buf).await;
parse_response(&buf)
})
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
}
/// One HTTP/1.1 connection over TLS, reused for every request until it fails.
pub struct KeepAlive {
sender: hyper::client::conn::http1::SendRequest<Full<Bytes>>,
}
impl KeepAlive {
pub async fn connect(
addr: SocketAddr,
sni: &str,
roots: Arc<RootCertStore>,
) -> io::Result<KeepAlive> {
let tcp = TcpStream::connect(addr).await?;
tcp.set_nodelay(true)?;
let name = ServerName::try_from(sni.to_owned()).map_err(other)?;
let s = tls_connector(roots).connect(name, tcp).await?;
let (sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(s))
.await
.map_err(other)?;
tokio::spawn(async move {
let _ = conn.await;
});
Ok(KeepAlive { sender })
}
/// Send one request on this connection. An `Err` means the connection is gone.
pub async fn send(&mut self, req: &Req) -> io::Result<Resp> {
self.sender.ready().await.map_err(other)?;
let mut b = hyper::Request::builder()
.method(req.method.as_str())
.uri(req.path.as_str());
for (n, v) in &req.headers {
b = b.header(n.as_str(), v.as_str());
}
let request = b
.body(Full::new(Bytes::from(req.body.clone())))
.map_err(other)?;
let resp = tokio::time::timeout(TIMEOUT, self.sender.send_request(request))
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
.map_err(other)?;
let status = resp.status().as_u16();
let headers = resp
.headers()
.iter()
.map(|(n, v)| {
(
n.as_str().to_owned(),
String::from_utf8_lossy(v.as_bytes()).into_owned(),
)
})
.collect();
let body = resp
.into_body()
.collect()
.await
.map_err(other)?
.to_bytes()
.to_vec();
Ok(Resp {
status,
headers,
body,
})
}
}
/// A JSON answer: status and parsed body (`Null` when the body is empty or not JSON).
#[derive(Debug, Clone)]
pub struct JsonResp {
pub status: u16,
pub headers: Vec<(String, String)>,
pub json: serde_json::Value,
pub text: String,
}
impl JsonResp {
pub fn header(&self, name: &str) -> Option<&str> {
self.headers
.iter()
.find(|(n, _)| n.eq_ignore_ascii_case(name))
.map(|(_, v)| v.as_str())
}
}
fn json_resp(r: Resp) -> JsonResp {
let text = String::from_utf8_lossy(&r.body).into_owned();
JsonResp {
status: r.status,
headers: r.headers,
json: serde_json::from_str(&text).unwrap_or(serde_json::Value::Null),
text,
}
}
fn raw_request(
method: &str,
path: &str,
host: &str,
headers: &[(&str, &str)],
body: Option<&serde_json::Value>,
) -> Vec<u8> {
let body = body.map(|b| b.to_string()).unwrap_or_default();
let mut out = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n");
for (n, v) in headers {
out.push_str(&format!("{n}: {v}\r\n"));
}
if !body.is_empty() || method != "GET" {
out.push_str("Content-Type: application/json\r\n");
out.push_str(&format!("Content-Length: {}\r\n", body.len()));
}
out.push_str("\r\n");
out.push_str(&body);
out.into_bytes()
}
/// A request over a Unix socket (edge's admin socket).
#[cfg(unix)]
pub async fn unix_json(
socket: &std::path::Path,
method: &str,
path: &str,
body: Option<&serde_json::Value>,
) -> io::Result<JsonResp> {
tokio::time::timeout(TIMEOUT, async {
let mut s = tokio::net::UnixStream::connect(socket).await?;
s.write_all(&raw_request(method, path, "localhost", &[], body))
.await?;
let mut buf = Vec::new();
s.read_to_end(&mut buf).await?;
parse_response(&buf).map(json_resp)
})
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
}
/// A request over plain TCP (the control API on loopback), with extra headers.
pub async fn tcp_json(
addr: SocketAddr,
method: &str,
path: &str,
headers: &[(&str, &str)],
body: Option<&serde_json::Value>,
) -> io::Result<JsonResp> {
tokio::time::timeout(Duration::from_secs(120), async {
let mut s = TcpStream::connect(addr).await?;
s.write_all(&raw_request(method, path, &addr.to_string(), headers, body))
.await?;
let mut buf = Vec::new();
s.read_to_end(&mut buf).await?;
parse_response(&buf).map(json_resp)
})
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
}
/// Send raw bytes over plain TCP and parse the answer (for malformed requests).
pub async fn tcp_raw(addr: SocketAddr, request: &[u8]) -> io::Result<Resp> {
tokio::time::timeout(TIMEOUT, async {
let mut s = TcpStream::connect(addr).await?;
s.write_all(request).await?;
let mut buf = Vec::new();
s.read_to_end(&mut buf).await?;
parse_response(&buf)
})
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
}