// 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/. //! Differential harness: one set of route files, compiled by `ianitor-core` into the edge //! config and into Caddy JSON; the same request corpus is sent to Ianitor (in-process) and //! to Caddy (the `caddy` binary running the generated JSON); status, selected headers and //! body are compared. Everything listens on 127.0.0.1. //! //! Test code: panics are failures. #![cfg(unix)] #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use std::collections::BTreeMap; use std::fmt::Write as _; use std::net::SocketAddr; use std::process::{Command, Stdio}; use std::sync::Arc; use std::time::Duration; use ianitor_core::compile::{self, CompileOptions}; use ianitor_core::{Model, SourceFile, load}; use ianitor_testkit::authelia::MockAuthelia; use ianitor_testkit::client::{self, Req, Resp, WsOutcome}; use ianitor_testkit::proc::{ChildGuard, TempDir, free_port, local, wait_for_port}; use ianitor_testkit::tls::TestCa; use ianitor_testkit::upstream::{Echo, WsEcho, closed_port}; use rustls::RootCertStore; /// The value behind the `api_key` credential. Written with a trailing newline, like most /// systemd credentials; both engines must drop it. pub const SECRET: &str = "diff-secret-value-7f3a"; /// Upstreams, auth server, certificates, credentials and the compiled model. pub struct Env { pub dir: TempDir, pub ca: TestCa, pub model: Model, /// The routes behind `model`: the site file and `(hosts/.toml, contents)`. pub site: String, pub hosts: Vec<(String, String)>, _upstreams: (Echo, Echo, Echo, Echo, WsEcho, MockAuthelia), } fn host(name: &str, body: &str) -> (String, String) { ( format!("hosts/{name}.toml"), format!("hostname = \"{name}\"\ntls = \"domi\"\n{body}"), ) } impl Env { pub async fn start() -> Env { let app = Echo::start("app").await; let sick = Echo::start("sick").await; sick.health.store(500, std::sync::atomic::Ordering::SeqCst); let rr_a = Echo::start("rr").await; let rr_b = Echo::start("rr").await; let ws = WsEcho::start().await; let auth = MockAuthelia::start().await; let site = format!( "secrets = [\"api_key\"]\n\n[forward_auth]\nurl = \"{}\"\ncopy_headers = [\"Remote-User\", \"Remote-Groups\"]\n", auth.url() ); let rules = "\ [[request_headers]]\naction = \"set\"\nname = \"X-Static\"\nvalue = \"static-value\"\n\ [[request_headers]]\naction = \"remove\"\nname = \"X-Remove-Me\"\n\ [[request_headers]]\naction = \"set\"\nname = \"X-Api-Key\"\nsecret = \"api_key\"\n\ [[response_headers]]\naction = \"set\"\nname = \"X-Frame-Options\"\nvalue = \"DENY\"\n\ [[response_headers]]\naction = \"remove\"\nname = \"X-Powered-By\"\n"; let hosts = vec![ host( "plain.test", &format!( "upstreams = [\"{}\"]\naccess_log = \"truncated\"\n{rules}", app.url() ), ), host("ws.test", &format!("upstreams = [\"{}\"]\n", ws.url())), host( "nows.test", &format!("upstreams = [\"{}\"]\nwebsockets = false\n", app.url()), ), host( "down.test", &format!("upstreams = [\"http://127.0.0.1:{}\"]\n", closed_port()), ), host( "auth.test", &format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", app.url()), ), host( "wsauth.test", &format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", ws.url()), ), host( "hc.test", &format!( "upstreams = [\"{}\"]\n[health_check]\npath = \"/healthz\"\ninterval_secs = 1\n", app.url() ), ), host( "hcdown.test", &format!( "upstreams = [\"{}\"]\n[health_check]\npath = \"/healthz\"\ninterval_secs = 1\n", sick.url() ), ), host( "rr.test", &format!("upstreams = [\"{}\", \"{}\"]\n", rr_a.url(), rr_b.url()), ), ]; let sources: Vec = hosts .iter() .map(|(n, c)| SourceFile { name: n, contents: c, }) .collect(); let model = load( &SourceFile { name: "ianitor.toml", contents: &site, }, &sources, ) .expect("diff routes are valid"); let dir = TempDir::new("diff"); for d in ["certs", "creds", "logs", "state-edge", "state-caddy", "xdg"] { std::fs::create_dir_all(dir.join(d)).unwrap(); } let ca = TestCa::new("Ianitor Diff CA"); for h in model.hosts() { 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(dir.join(&format!("certs/{}.key", h.hostname)), leaf.key_pem).unwrap(); } std::fs::write(dir.join("creds/api_key"), format!("{SECRET}\n")).unwrap(); Env { dir, ca, model, site, hosts, _upstreams: (app, sick, rr_a, rr_b, ws, auth), } } pub fn options(&self, engine: &str) -> CompileOptions { CompileOptions { http_listen: local(free_port()), https_listen: local(free_port()), cert_dir: self.dir.str("certs"), state_dir: self.dir.str(&format!("state-{engine}")), access_log: self.dir.str(&format!("logs/{engine}-access.log")), caddy_credentials_dir: self.dir.str("creds"), caddy_admin: None, } } pub fn roots(&self) -> Arc { self.ca.roots() } } /// A running engine: where to send requests. pub struct Target { pub name: &'static str, pub http: SocketAddr, pub https: SocketAddr, _guard: Guard, } enum Guard { Edge(Option>), Caddy(#[allow(dead_code)] ChildGuard), } impl Drop for Target { fn drop(&mut self) { if let Guard::Edge(stop) = &mut self._guard && let Some(s) = stop.take() { let _ = s.send(()); } } } /// Start Ianitor edge in this process from an edge config text. pub fn start_edge(env: &Env, name: &'static str, config_text: &str) -> Target { let cfg: ianitor_core::edge_config::EdgeConfig = serde_json::from_str(config_text).unwrap(); let (http, https) = ( cfg.http_listen.parse().unwrap(), cfg.https_listen.parse().unwrap(), ); let rt = ianitor_edge::runtime::build(cfg, Some(&env.dir.join("creds"))).expect("edge runtime"); let opts = ianitor_edge::Options::default(); let shared = ianitor_edge::shared_for(rt, &opts); let server = ianitor_edge::server(shared, &opts).expect("edge server"); let (tx, rx) = tokio::sync::oneshot::channel(); std::thread::spawn(move || ianitor_edge::run_until(server, rx)); assert!( wait_for_port(https, Duration::from_secs(20)), "edge did not listen on {https}" ); assert!( wait_for_port(http, Duration::from_secs(5)), "edge did not listen on {http}" ); Target { name, http, https, _guard: Guard::Edge(Some(tx)), } } /// Start `caddy run` on a generated Caddy JSON. pub fn start_caddy(env: &Env, name: &'static str, caddy: &std::path::Path, json: &str) -> Target { let v: serde_json::Value = serde_json::from_str(json).unwrap(); let servers = &v["apps"]["http"]["servers"]; let https: SocketAddr = servers["ianitor_https"]["listen"][0] .as_str() .unwrap() .parse() .unwrap(); let http: SocketAddr = servers["ianitor_http"]["listen"][0] .as_str() .unwrap() .parse() .unwrap(); let file = env.dir.join(&format!("{name}.json")); std::fs::write(&file, json).unwrap(); let log = std::fs::File::create(env.dir.join(&format!("{name}.log"))).unwrap(); let child = Command::new(caddy) .arg("run") .arg("--config") .arg(&file) .env("HOME", env.dir.join("xdg")) .env("XDG_CONFIG_HOME", env.dir.join("xdg")) .env("XDG_DATA_HOME", env.dir.join("xdg")) .stdout(Stdio::from(log.try_clone().unwrap())) .stderr(Stdio::from(log)) .spawn() .expect("spawn caddy"); let guard = ChildGuard(child); if !wait_for_port(https, Duration::from_secs(20)) { let out = std::fs::read_to_string(env.dir.join(&format!("{name}.log"))).unwrap_or_default(); panic!("caddy did not listen on {https}:\n{out}"); } assert!(wait_for_port(http, Duration::from_secs(5))); Target { name, http, https, _guard: Guard::Caddy(guard), } } pub enum Action { Https { sni: &'static str, req: Req, }, Http { req: Req, }, Websocket { sni: &'static str, host: &'static str, headers: Vec<(&'static str, &'static str)>, }, } /// One request of the corpus. Status, every response header (except [`IGNORED_HEADERS`]) /// and the body are compared. pub struct Case { pub name: &'static str, pub action: Action, } fn https(name: &'static str, sni: &'static str, req: Req) -> Case { Case { name, action: Action::Https { sni, req }, } } fn http(name: &'static str, req: Req) -> Case { Case { name, action: Action::Http { req }, } } fn ws(name: &'static str, host: &'static str, headers: Vec<(&'static str, &'static str)>) -> Case { Case { name, action: Action::Websocket { sni: host, host, headers, }, } } /// The seed corpus: plain requests, header rules, websocket upgrades, upstream down, /// auth denied and allowed, misbehaving auth server, health checks, odd request targets. pub fn corpus() -> Vec { let p = "plain.test"; let a = "auth.test"; let good = ("cookie", "authelia_session=good"); let session = |s: &str| format!("authelia_session={s}"); vec![ https("plain GET", p, Req::get(p, "/")), https( "GET with path and query", p, Req::get(p, "/deep/path/x.html?q=1&r=two"), ), https("HEAD", p, Req::new("HEAD", p, "/")), https( "POST with body", p, Req::new("POST", p, "/submit") .header("content-type", "application/x-www-form-urlencoded") .body(b"a=1&b=2"), ), https( "PUT binary body", p, Req::new("PUT", p, "/blob").body(&[0u8, 1, 2, 3, 255, 254]), ), https("DELETE", p, Req::new("DELETE", p, "/item/7")), https( "request header removed", p, Req::get(p, "/").header("x-remove-me", "1"), ), https( "removal is exact, not a prefix match", p, Req::get(p, "/") .header("x-remove-me", "1") .header("x-remove-me-too", "kept"), ), https( "request header overwritten", p, Req::get(p, "/").header("x-static", "from-client"), ), https( "client header passes", p, Req::get(p, "/").header("x-client", "hello"), ), https( "X-Forwarded-* replaced", p, Req::get(p, "/") .header("x-forwarded-for", "6.6.6.6") .header("x-forwarded-host", "evil.test") .header("x-forwarded-proto", "gopher"), ), https( "secret header cannot be preset", p, Req::get(p, "/").header("x-api-key", "client-value"), ), https("upstream 404 passes through", p, Req::get(p, "/status/404")), https("upstream 500 passes through", p, Req::get(p, "/status/500")), https("upstream 204", p, Req::get(p, "/status/204")), https("large body", p, Req::get(p, "/big?n=300000")), https("chunked body", p, Req::get(p, "/chunked")), https("two Set-Cookie headers", p, Req::get(p, "/set-cookie")), https("Host in upper case", p, Req::get("PLAIN.TEST", "/")), https( "unknown Host on a known SNI", p, Req::get("unknown.test", "/"), ), https( "absolute-form target, same host", p, Req::get(p, "https://plain.test/abs?q=1"), ), https( "absolute-form target, other host", p, Req::get(p, "https://evil.test/x"), ), http("HTTP redirects to HTTPS", Req::get(p, "/a/b?c=d")), http("HTTP unknown host", Req::get("unknown.test", "/")), http( "HTTP unknown ACME token", Req::get(p, "/.well-known/acme-challenge/nope"), ), http( "HTTP absolute-form, same host", Req::get(p, "http://plain.test/x?y"), ), http( "HTTP absolute-form, other host", Req::get(p, "http://evil.test/x"), ), ws("websocket upgrade", "ws.test", vec![]), ws("websocket refused when disabled", "nows.test", vec![]), https( "plain GET where websockets are disabled", "nows.test", Req::get("nows.test", "/"), ), https( "websocket refused: second Upgrade header", "nows.test", Req::get("nows.test", "/") .header("connection", "upgrade") .header("upgrade", "h2c") .header("upgrade", "websocket"), ), https( "websocket refused: token list", "nows.test", Req::get("nows.test", "/") .header("connection", "upgrade") .header("upgrade", "websocket, h2c"), ), https("upstream down GET", "down.test", Req::get("down.test", "/")), https( "upstream down POST", "down.test", Req::new("POST", "down.test", "/x").body(b"lost"), ), https( "auth denied GET redirects to portal", a, Req::get(a, "/private?x=1"), ), https("auth denied HEAD", a, Req::new("HEAD", a, "/private")), https( "auth denied POST", a, Req::new("POST", a, "/submit").body(b"nope"), ), https( "auth bad credentials", a, Req::get(a, "/").header("authorization", "Bearer wrong"), ), https( "auth forbidden", a, Req::get(a, "/").header("cookie", &session("forbidden")), ), https( "auth allowed with session", a, Req::get(a, "/me").header(good.0, good.1), ), https( "auth allowed ignores spoofed identity", a, Req::get(a, "/me") .header(good.0, good.1) .header("remote-user", "mallory"), ), https( "auth strips spoofed identity it does not copy", a, Req::get(a, "/me") .header(good.0, good.1) .header("remote-email", "m@evil.test") .header("remote-name", "Mallory"), ), https( "auth allowed without identity strips spoofed", a, Req::get(a, "/me") .header("cookie", &session("nameless")) .header("remote-user", "mallory"), ), https( "auth allowed with bearer token", a, Req::get(a, "/api").header("authorization", "Bearer good"), ), https( "auth allowed GET with query", a, Req::get(a, "/search?q=a+b").header(good.0, good.1), ), https( "auth allowed POST keeps the body", a, Req::new("POST", a, "/form") .header(good.0, good.1) .body(b"field=value"), ), https( "auth answers 100 Continue first", a, Req::get(a, "/").header("cookie", &session("continue-ok")), ), https( "auth answers 9 informational heads first", a, Req::get(a, "/").header("cookie", &session("continue-x9")), ), https( "auth answers 1000 informational heads first", a, Req::get(a, "/").header("cookie", &session("continue-x1000")), ), https( "auth answers 1001 informational heads first", a, Req::get(a, "/").header("cookie", &session("continue-x1001")), ), https( "auth answers 2xx with a 5 MB body", a, Req::get(a, "/").header("cookie", &session("big-ok")), ), https( "auth answers 401 with a 5 MB body", a, Req::get(a, "/").header("cookie", &session("big-deny")), ), https( "auth answers 2xx with a truncated body", a, Req::get(a, "/").header("cookie", &session("truncated-ok")), ), https( "auth answers 101", a, Req::get(a, "/").header("cookie", &session("switch")), ), ws("websocket denied by auth", "wsauth.test", vec![]), ws("websocket allowed by auth", "wsauth.test", vec![good]), https("healthy upstream", "hc.test", Req::get("hc.test", "/")), https( "all upstreams unhealthy", "hcdown.test", Req::get("hcdown.test", "/"), ), https("round robin 1", "rr.test", Req::get("rr.test", "/")), https("round robin 2", "rr.test", Req::get("rr.test", "/")), ] } /// Response headers not compared, with the reason. pub const IGNORED_HEADERS: &[(&str, &str)] = &[ ("date", "the clock moves between the two requests"), ( "connection", "hop-by-hop (RFC 9110 7.6.1): describes the client connection, not the response", ), ("keep-alive", "hop-by-hop (RFC 9110 7.6.1)"), ( "sec-websocket-accept", "derived from the client's random Sec-WebSocket-Key", ), ]; /// What one engine answered, normalised for comparison. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Observation { pub status: u16, pub headers: BTreeMap, pub body: String, } fn observe_parts(status: u16, raw: &[(String, String)], body: &[u8], t: &Target) -> Observation { let mut headers: BTreeMap = BTreeMap::new(); for (n, v) in raw { let n = n.to_ascii_lowercase(); if IGNORED_HEADERS.iter().any(|(i, _)| *i == n) { continue; } // The two engines listen on different ports; Location carries the HTTPS port. let v = v.replace(&format!(":{}", t.https.port()), ":"); headers .entry(n) .and_modify(|e| { e.push('\n'); e.push_str(&v) }) .or_insert(v); } Observation { status, headers, body: String::from_utf8_lossy(body).into_owned(), } } fn observe(resp: &Resp, t: &Target) -> Observation { observe_parts(resp.status, &resp.headers, &resp.body, t) } fn failed(e: std::io::Error) -> Observation { Observation { status: 0, headers: BTreeMap::new(), body: format!("client error: {e}"), } } pub async fn run_case(case: &Case, t: &Target, roots: Arc) -> Observation { match &case.action { Action::Https { sni, req } => client::https(t.https, sni, roots, req) .await .map_or_else(failed, |r| observe(&r, t)), Action::Http { req } => client::http(t.http, req) .await .map_or_else(failed, |r| observe(&r, t)), Action::Websocket { sni, host, headers } => { match client::websocket(t.https, sni, roots, host, "/socket", headers, "ping").await { Ok(WsOutcome::Upgraded { status, headers, echo, }) => observe_parts(status, &headers, format!("echo: {echo}").as_bytes(), t), Ok(WsOutcome::Refused(r)) => observe(&r, t), Err(e) => failed(e), } } } } pub struct Outcome { pub name: &'static str, pub ianitor: Observation, pub caddy: Observation, } /// How a documented divergence is recognised. Each rule is narrow on purpose. pub enum Rule { /// Caddy has `header` with one of `values` and Ianitor has no such header; with `only_if`, /// Caddy's answer must also carry that header/value pair (the upstream's own report). ExtraHeaderInCaddy { header: &'static str, values: &'static [&'static str], only_if: Option<(&'static str, &'static str)>, }, /// This exact case, with exactly these statuses; nothing else is compared. Status { case: &'static str, ianitor: u16, caddy: u16, }, } pub struct Divergence { pub id: &'static str, pub rule: Rule, pub reason: &'static str, } /// Documented, accepted differences between the engines. Anything else is a mismatch. pub const KNOWN_DIVERGENCES: &[Divergence] = &[ Divergence { id: "KD-1", rule: Rule::ExtraHeaderInCaddy { header: "content-type", values: &[ "text/plain; charset=utf-8", "text/html; charset=utf-8", "application/octet-stream", ], only_if: Some(("x-sent-content-type", "none")), }, reason: "the upstream sent no Content-Type; Caddy (Go net/http) adds a sniffed one, Ianitor passes the response unchanged", }, Divergence { id: "KD-2", rule: Rule::ExtraHeaderInCaddy { header: "via", values: &["1.1 Caddy"], only_if: None, }, reason: "Caddy adds `Via: 1.1 Caddy` to proxied responses; Ianitor adds no Via header", }, Divergence { id: "KD-3", rule: Rule::ExtraHeaderInCaddy { header: "server", values: &["Caddy"], only_if: None, }, reason: "Caddy names itself in `Server`; Ianitor sends no Server header of its own", }, Divergence { id: "KD-4", rule: Rule::Status { case: "auth answers 2xx with a 5 MB body", ianitor: 502, caddy: 200, }, reason: "edge reads at most 1 MiB of an auth answer and fails closed; Caddy ignores the body", }, Divergence { id: "KD-5", rule: Rule::Status { case: "auth answers 401 with a 5 MB body", ianitor: 502, caddy: 401, }, reason: "edge reads at most 1 MiB of an auth answer and fails closed; Caddy streams it to the client", }, Divergence { id: "KD-6", rule: Rule::Status { case: "auth answers 2xx with a truncated body", ianitor: 502, caddy: 200, }, reason: "edge treats a broken auth answer as a failure; Caddy allows on the 2xx status line", }, Divergence { id: "KD-7", rule: Rule::Status { case: "auth answers 101", ianitor: 502, caddy: 200, }, reason: "edge treats 101 from the auth server as a denial (502); Caddy answers 200 without reaching the upstream", }, Divergence { id: "KD-8", rule: Rule::Status { case: "absolute-form target, other host", ianitor: 400, caddy: 404, }, reason: "Pingora rejects a request whose target authority differs from Host (400); Go routes by the target (404 here)", }, Divergence { id: "KD-9", rule: Rule::Status { case: "HTTP absolute-form, other host", ianitor: 400, caddy: 404, }, reason: "as KD-8, on the plain-HTTP listener", }, Divergence { id: "KD-10", rule: Rule::Status { case: "auth answers 1001 informational heads first", ianitor: 502, caddy: 200, }, reason: "edge fails closed after 1000 informational heads from the auth server; Go limits only their total header bytes", }, ]; impl Outcome { pub fn same(&self) -> bool { self.ianitor == self.caddy } /// The divergence ids that explain every difference, or `None`. pub fn known_divergence(&self) -> Option { if self.same() { return None; } for d in KNOWN_DIVERGENCES { if let Rule::Status { case, ianitor, caddy, } = d.rule && case == self.name && self.ianitor.status == ianitor && self.caddy.status == caddy { return Some(d.id.to_owned()); } } let mut c = self.caddy.clone(); let mut ids = Vec::new(); for d in KNOWN_DIVERGENCES { if let Rule::ExtraHeaderInCaddy { header, values, only_if, } = d.rule { let extra = c .headers .get(header) .is_some_and(|v| values.contains(&v.as_str())) && !self.ianitor.headers.contains_key(header) && only_if.is_none_or(|(h, v)| c.headers.get(h).is_some_and(|x| x == v)); if extra { c.headers.remove(header); ids.push(d.id); } } } (!ids.is_empty() && c == self.ianitor).then(|| ids.join("+")) } pub fn mismatch(&self) -> bool { !self.same() && self.known_divergence().is_none() } } pub struct Report { pub outcomes: Vec, } impl Report { pub fn mismatches(&self) -> Vec<&Outcome> { self.outcomes.iter().filter(|o| o.mismatch()).collect() } pub fn known(&self) -> Vec<&Outcome> { self.outcomes .iter() .filter(|o| o.known_divergence().is_some()) .collect() } pub fn render(&self, title: &str) -> String { let identity_only = |o: &&Outcome| { o.known_divergence() .is_some_and(|k| k.split('+').all(|id| id == "KD-2" || id == "KD-3")) }; let identity = self.outcomes.iter().filter(identity_only).count(); let mut s = format!( "== {title}: {} cases: {} identical, {} identical apart from Via/Server (KD-2, KD-3), \ {} other known divergence, {} differ\n", self.outcomes.len(), self.outcomes.iter().filter(|o| o.same()).count(), identity, self.known().len() - identity, self.mismatches().len() ); for o in &self.outcomes { if o.same() { let _ = writeln!(s, " same {:3} {}", o.ianitor.status, o.name); } else if let Some(kd) = o.known_divergence() { let _ = writeln!(s, " {kd:<10} {:3} {}", o.ianitor.status, o.name); } else { let _ = writeln!(s, " DIFF {}", o.name); for d in differences(&o.ianitor, &o.caddy) { let _ = writeln!(s, " {d}"); } } } for d in KNOWN_DIVERGENCES { let _ = writeln!(s, " {}: {}", d.id, d.reason); } for (h, why) in IGNORED_HEADERS { let _ = writeln!(s, " not compared: {h} ({why})"); } s } } fn short(o: &Observation) -> Observation { let mut o = o.clone(); if o.body.len() > 300 { o.body = format!( "{}… ({} bytes)", o.body.chars().take(300).collect::(), o.body.len() ); } o } /// The host a case is about (its SNI, or the Host header of plain-HTTP cases). pub fn case_host(case: &Case) -> String { match &case.action { Action::Https { sni, .. } | Action::Websocket { sni, .. } => (*sni).to_owned(), Action::Http { req } => req .headers .iter() .find(|(n, _)| n == "host") .map(|(_, v)| v.to_ascii_lowercase()) .unwrap_or_default(), } } /// Send every case to both targets, one after the other (round robin needs a stable order). pub async fn run_corpus(ianitor: &Target, caddy: &Target, roots: Arc) -> Report { run_cases(ianitor, caddy, roots, |_| true).await } /// Like [`run_corpus`], for the cases `keep` selects. pub async fn run_cases( ianitor: &Target, caddy: &Target, roots: Arc, keep: impl Fn(&Case) -> bool, ) -> Report { let mut outcomes = Vec::new(); for case in corpus().into_iter().filter(|c| keep(c)) { let i = run_case(&case, ianitor, roots.clone()).await; let c = run_case(&case, caddy, roots.clone()).await; outcomes.push(Outcome { name: case.name, ianitor: i, caddy: c, }); } Report { outcomes } } /// Compile both configs for one pair of engine instances. pub fn compile_pair(env: &Env) -> (String, String) { let edge = compile::edge(&env.model, &env.options("edge")).unwrap(); let caddy = compile::caddy(&env.model, &env.options("caddy")).unwrap(); (edge, caddy) } /// Deliberately broken Caddy compiler: forgets every response header rule. pub fn break_caddy(json: &str) -> String { let mut v: serde_json::Value = serde_json::from_str(json).unwrap(); fn walk(v: &mut serde_json::Value) { match v { serde_json::Value::Object(m) => { if m.get("handler").and_then(|h| h.as_str()) == Some("reverse_proxy") && let Some(h) = m.get_mut("headers").and_then(|h| h.as_object_mut()) { h.remove("response"); } m.values_mut().for_each(walk); } serde_json::Value::Array(a) => a.iter_mut().for_each(walk), _ => {} } } walk(&mut v); serde_json::to_string_pretty(&v).unwrap() } /// Deliberately broken edge compiler: forgets every request header rule. pub fn break_edge(json: &str) -> String { let mut cfg: ianitor_core::edge_config::EdgeConfig = serde_json::from_str(json).unwrap(); for h in &mut cfg.hosts { h.request_headers.clear(); } serde_json::to_string_pretty(&cfg).unwrap() } /// Both engines run health checks every second; give them time for the first verdicts. pub async fn settle() { tokio::time::sleep(Duration::from_millis(2500)).await; } /// Field-by-field differences, for the report. fn differences(i: &Observation, c: &Observation) -> Vec { let mut out = Vec::new(); if i.status != c.status { out.push(format!("status: ianitor {} / caddy {}", i.status, c.status)); } let names: std::collections::BTreeSet<&String> = i.headers.keys().chain(c.headers.keys()).collect(); for n in names { let (a, b) = (i.headers.get(n), c.headers.get(n)); if a != b { out.push(format!("header {n}: ianitor {a:?} / caddy {b:?}")); } } if i.body != c.body { out.push(format!( "body: ianitor {:?} / caddy {:?}", short(i).body, short(c).body )); } out }