[diff] Harness: 43-request corpus against Ianitor and Caddy, broken-compiler check
This commit is contained in:
Generated
+4
@@ -1023,6 +1023,10 @@ version = "0.1.0"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"ianitor-core",
|
"ianitor-core",
|
||||||
"ianitor-edge",
|
"ianitor-edge",
|
||||||
|
"ianitor-testkit",
|
||||||
|
"rustls",
|
||||||
|
"serde_json",
|
||||||
|
"tokio",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|||||||
@@ -10,6 +10,10 @@ publish.workspace = true
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
ianitor-core.workspace = true
|
ianitor-core.workspace = true
|
||||||
ianitor-edge.workspace = true
|
ianitor-edge.workspace = true
|
||||||
|
ianitor-testkit.workspace = true
|
||||||
|
tokio.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
|
rustls.workspace = true
|
||||||
|
|
||||||
[lints]
|
[lints.rust]
|
||||||
workspace = true
|
unsafe_code = "forbid"
|
||||||
|
|||||||
+719
-1
@@ -2,4 +2,722 @@
|
|||||||
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
// 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/.
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
//! Differential harness: Ianitor edge versus Caddy on one request corpus.
|
//! 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,
|
||||||
|
_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 = \"{}\"\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<SourceFile> = 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,
|
||||||
|
_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<RootCertStore> {
|
||||||
|
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<tokio::sync::oneshot::Sender<()>>),
|
||||||
|
Caddy(#[allow(dead_code)] ChildGuard),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Target {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Guard::Edge(stop) = &mut self._guard {
|
||||||
|
if 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 = Arc::new(
|
||||||
|
ianitor_edge::runtime::build(cfg, Some(&env.dir.join("creds"))).expect("edge runtime"),
|
||||||
|
);
|
||||||
|
let server = ianitor_edge::server(rt, &ianitor_edge::Options::default()).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)>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Case {
|
||||||
|
pub name: &'static str,
|
||||||
|
pub action: Action,
|
||||||
|
/// Response headers compared besides status and body.
|
||||||
|
pub headers: &'static [&'static str],
|
||||||
|
}
|
||||||
|
|
||||||
|
const STD: &[&str] = &[
|
||||||
|
"content-type",
|
||||||
|
"location",
|
||||||
|
"www-authenticate",
|
||||||
|
"set-cookie",
|
||||||
|
"x-powered-by",
|
||||||
|
"x-frame-options",
|
||||||
|
"x-upstream",
|
||||||
|
];
|
||||||
|
|
||||||
|
fn https(name: &'static str, sni: &'static str, req: Req) -> Case {
|
||||||
|
Case {
|
||||||
|
name,
|
||||||
|
action: Action::Https { sni, req },
|
||||||
|
headers: STD,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The seed corpus: plain requests, header rules, websocket upgrades, upstream down,
|
||||||
|
/// auth denied and allowed, health checks.
|
||||||
|
pub fn corpus() -> Vec<Case> {
|
||||||
|
let p = "plain.test";
|
||||||
|
let a = "auth.test";
|
||||||
|
let good = ("cookie", "authelia_session=good");
|
||||||
|
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(
|
||||||
|
"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", "/"),
|
||||||
|
),
|
||||||
|
Case {
|
||||||
|
name: "HTTP redirects to HTTPS",
|
||||||
|
action: Action::Http {
|
||||||
|
req: Req::get(p, "/a/b?c=d"),
|
||||||
|
},
|
||||||
|
headers: STD,
|
||||||
|
},
|
||||||
|
Case {
|
||||||
|
name: "HTTP unknown host",
|
||||||
|
action: Action::Http {
|
||||||
|
req: Req::get("unknown.test", "/"),
|
||||||
|
},
|
||||||
|
headers: STD,
|
||||||
|
},
|
||||||
|
Case {
|
||||||
|
name: "HTTP unknown ACME token",
|
||||||
|
action: Action::Http {
|
||||||
|
req: Req::get(p, "/.well-known/acme-challenge/nope"),
|
||||||
|
},
|
||||||
|
headers: STD,
|
||||||
|
},
|
||||||
|
Case {
|
||||||
|
name: "websocket upgrade",
|
||||||
|
action: Action::Websocket {
|
||||||
|
sni: "ws.test",
|
||||||
|
host: "ws.test",
|
||||||
|
headers: vec![],
|
||||||
|
},
|
||||||
|
headers: &["upgrade"],
|
||||||
|
},
|
||||||
|
Case {
|
||||||
|
name: "websocket refused when disabled",
|
||||||
|
action: Action::Websocket {
|
||||||
|
sni: "nows.test",
|
||||||
|
host: "nows.test",
|
||||||
|
headers: vec![],
|
||||||
|
},
|
||||||
|
headers: STD,
|
||||||
|
},
|
||||||
|
https(
|
||||||
|
"plain GET where websockets are disabled",
|
||||||
|
"nows.test",
|
||||||
|
Req::get("nows.test", "/"),
|
||||||
|
),
|
||||||
|
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", "authelia_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 allowed without identity strips spoofed",
|
||||||
|
a,
|
||||||
|
Req::get(a, "/me")
|
||||||
|
.header("cookie", "authelia_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),
|
||||||
|
),
|
||||||
|
Case {
|
||||||
|
name: "websocket denied by auth",
|
||||||
|
action: Action::Websocket {
|
||||||
|
sni: "wsauth.test",
|
||||||
|
host: "wsauth.test",
|
||||||
|
headers: vec![],
|
||||||
|
},
|
||||||
|
headers: STD,
|
||||||
|
},
|
||||||
|
Case {
|
||||||
|
name: "websocket allowed by auth",
|
||||||
|
action: Action::Websocket {
|
||||||
|
sni: "wsauth.test",
|
||||||
|
host: "wsauth.test",
|
||||||
|
headers: vec![good],
|
||||||
|
},
|
||||||
|
headers: &["upgrade"],
|
||||||
|
},
|
||||||
|
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", "/")),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What one engine answered, normalised for comparison.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Observation {
|
||||||
|
pub status: u16,
|
||||||
|
pub headers: BTreeMap<String, String>,
|
||||||
|
pub body: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn observe(resp: &Resp, case: &Case, t: &Target) -> Observation {
|
||||||
|
let mut headers = BTreeMap::new();
|
||||||
|
for h in case.headers {
|
||||||
|
let all = resp.header_all(h);
|
||||||
|
if !all.is_empty() {
|
||||||
|
// The two engines listen on different ports; Location carries the HTTPS port.
|
||||||
|
let v = all
|
||||||
|
.join("\n")
|
||||||
|
.replace(&format!(":{}", t.https.port()), ":<https-port>");
|
||||||
|
headers.insert((*h).to_owned(), v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Observation {
|
||||||
|
status: resp.status,
|
||||||
|
headers,
|
||||||
|
body: String::from_utf8_lossy(&resp.body).into_owned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn run_case(case: &Case, t: &Target, roots: Arc<RootCertStore>) -> Observation {
|
||||||
|
match &case.action {
|
||||||
|
Action::Https { sni, req } => match client::https(t.https, sni, roots, req).await {
|
||||||
|
Ok(r) => observe(&r, case, t),
|
||||||
|
Err(e) => Observation {
|
||||||
|
status: 0,
|
||||||
|
headers: BTreeMap::new(),
|
||||||
|
body: format!("client error: {e}"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Action::Http { req } => match client::http(t.http, req).await {
|
||||||
|
Ok(r) => observe(&r, case, t),
|
||||||
|
Err(e) => Observation {
|
||||||
|
status: 0,
|
||||||
|
headers: BTreeMap::new(),
|
||||||
|
body: format!("client error: {e}"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Action::Websocket { sni, host, headers } => {
|
||||||
|
match client::websocket(t.https, sni, roots, host, "/socket", headers, "ping").await {
|
||||||
|
Ok(WsOutcome::Upgraded { status, echo }) => Observation {
|
||||||
|
status,
|
||||||
|
headers: BTreeMap::new(),
|
||||||
|
body: format!("echo: {echo}"),
|
||||||
|
},
|
||||||
|
Ok(WsOutcome::Refused(r)) => observe(&r, case, t),
|
||||||
|
Err(e) => Observation {
|
||||||
|
status: 0,
|
||||||
|
headers: BTreeMap::new(),
|
||||||
|
body: format!("client error: {e}"),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Outcome {
|
||||||
|
pub name: &'static str,
|
||||||
|
pub ianitor: Observation,
|
||||||
|
pub caddy: Observation,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Documented, accepted differences between the engines, each with its reason. Anything
|
||||||
|
/// else is a mismatch.
|
||||||
|
pub const KNOWN_DIVERGENCES: &[(&str, &str)] = &[(
|
||||||
|
"KD-1",
|
||||||
|
"Caddy (Go net/http) adds a sniffed Content-Type when the upstream sends none; \
|
||||||
|
Ianitor passes the upstream response unchanged (no MIME sniffing).",
|
||||||
|
)];
|
||||||
|
|
||||||
|
/// Content types Go's `http.DetectContentType` produces for small text and binary bodies.
|
||||||
|
const SNIFFED: [&str; 3] = [
|
||||||
|
"text/plain; charset=utf-8",
|
||||||
|
"text/html; charset=utf-8",
|
||||||
|
"application/octet-stream",
|
||||||
|
];
|
||||||
|
|
||||||
|
impl Outcome {
|
||||||
|
pub fn same(&self) -> bool {
|
||||||
|
self.ianitor == self.caddy
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Some(id)` when the only difference is a documented divergence.
|
||||||
|
pub fn known_divergence(&self) -> Option<&'static str> {
|
||||||
|
if self.same() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let sniffed = self
|
||||||
|
.caddy
|
||||||
|
.headers
|
||||||
|
.get("content-type")
|
||||||
|
.is_some_and(|v| SNIFFED.contains(&v.as_str()));
|
||||||
|
if sniffed && !self.ianitor.headers.contains_key("content-type") {
|
||||||
|
let mut c = self.caddy.clone();
|
||||||
|
c.headers.remove("content-type");
|
||||||
|
if c == self.ianitor {
|
||||||
|
return Some("KD-1");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mismatch(&self) -> bool {
|
||||||
|
!self.same() && self.known_divergence().is_none()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Report {
|
||||||
|
pub outcomes: Vec<Outcome>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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 mut s = format!(
|
||||||
|
"== {title}: {} cases, {} identical, {} known divergence, {} differ\n",
|
||||||
|
self.outcomes.len(),
|
||||||
|
self.outcomes.iter().filter(|o| o.same()).count(),
|
||||||
|
self.known().len(),
|
||||||
|
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:<4} {:3} {}", o.ianitor.status, o.name);
|
||||||
|
} else {
|
||||||
|
let _ = writeln!(s, " DIFF {}", o.name);
|
||||||
|
let _ = writeln!(s, " ianitor: {:?}", short(&o.ianitor));
|
||||||
|
let _ = writeln!(s, " caddy: {:?}", short(&o.caddy));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (id, why) in KNOWN_DIVERGENCES {
|
||||||
|
let _ = writeln!(s, " {id}: {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::<String>(),
|
||||||
|
o.body.len()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
o
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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<RootCertStore>) -> Report {
|
||||||
|
let mut outcomes = Vec::new();
|
||||||
|
for case in corpus() {
|
||||||
|
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") {
|
||||||
|
if 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;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
// 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 differential suite (ROADMAP §5 layer 1). Needs the `caddy` binary on PATH (or
|
||||||
|
//! `$IANITOR_CADDY_BIN`); without it the tests fail unless `IANITOR_ALLOW_SKIP=1`.
|
||||||
|
|
||||||
|
#![cfg(unix)]
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
use ianitor_diff::{
|
||||||
|
Env, break_caddy, break_edge, compile_pair, corpus, run_corpus, settle, start_caddy, start_edge,
|
||||||
|
};
|
||||||
|
use ianitor_testkit::proc::require_binary;
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn ianitor_and_caddy_answer_the_corpus_identically() {
|
||||||
|
let Some(caddy_bin) = require_binary("caddy") else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
corpus().len() >= 20,
|
||||||
|
"the seed corpus has at least 20 requests"
|
||||||
|
);
|
||||||
|
let env = Env::start().await;
|
||||||
|
let (edge_cfg, caddy_cfg) = compile_pair(&env);
|
||||||
|
let ianitor = start_edge(&env, "ianitor", &edge_cfg);
|
||||||
|
let caddy = start_caddy(&env, "caddy", &caddy_bin, &caddy_cfg);
|
||||||
|
settle().await;
|
||||||
|
|
||||||
|
let report = run_corpus(&ianitor, &caddy, env.roots()).await;
|
||||||
|
println!("{}", report.render("Ianitor vs Caddy"));
|
||||||
|
let statuses: Vec<u16> = report.outcomes.iter().map(|o| o.ianitor.status).collect();
|
||||||
|
assert!(
|
||||||
|
!statuses.contains(&0),
|
||||||
|
"every case got an answer: {statuses:?}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
report.mismatches().is_empty(),
|
||||||
|
"{}",
|
||||||
|
report.render("Ianitor vs Caddy")
|
||||||
|
);
|
||||||
|
|
||||||
|
// The corpus really exercises the interesting paths (and not, say, 404 everywhere).
|
||||||
|
for wanted in [101, 200, 204, 302, 308, 401, 403, 404, 500, 502, 503] {
|
||||||
|
assert!(
|
||||||
|
statuses.contains(&wanted),
|
||||||
|
"corpus covers status {wanted}: {statuses:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn a_deliberately_broken_compiler_is_caught() {
|
||||||
|
let Some(caddy_bin) = require_binary("caddy") else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let env = Env::start().await;
|
||||||
|
let (edge_cfg, caddy_cfg) = compile_pair(&env);
|
||||||
|
let (edge_cfg2, caddy_cfg2) = compile_pair(&env);
|
||||||
|
|
||||||
|
let ianitor = start_edge(&env, "ianitor", &edge_cfg);
|
||||||
|
let broken_caddy = start_caddy(&env, "caddy-broken", &caddy_bin, &break_caddy(&caddy_cfg));
|
||||||
|
let caddy = start_caddy(&env, "caddy", &caddy_bin, &caddy_cfg2);
|
||||||
|
let broken_ianitor = start_edge(&env, "ianitor-broken", &break_edge(&edge_cfg2));
|
||||||
|
settle().await;
|
||||||
|
|
||||||
|
let r1 = run_corpus(&ianitor, &broken_caddy, env.roots()).await;
|
||||||
|
println!(
|
||||||
|
"{}",
|
||||||
|
r1.render("Ianitor vs Caddy with response header rules dropped")
|
||||||
|
);
|
||||||
|
let diff1: Vec<&str> = r1.mismatches().iter().map(|o| o.name).collect();
|
||||||
|
assert!(!diff1.is_empty(), "broken Caddy compiler was not detected");
|
||||||
|
assert!(diff1.contains(&"plain GET"), "{diff1:?}");
|
||||||
|
|
||||||
|
let r2 = run_corpus(&broken_ianitor, &caddy, env.roots()).await;
|
||||||
|
println!(
|
||||||
|
"{}",
|
||||||
|
r2.render("Ianitor with request header rules dropped vs Caddy")
|
||||||
|
);
|
||||||
|
let diff2: Vec<&str> = r2.mismatches().iter().map(|o| o.name).collect();
|
||||||
|
assert!(!diff2.is_empty(), "broken edge compiler was not detected");
|
||||||
|
assert!(diff2.contains(&"request header overwritten"), "{diff2:?}");
|
||||||
|
assert!(
|
||||||
|
diff2.contains(&"secret header cannot be preset"),
|
||||||
|
"{diff2:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user