[diff] Corpus: 57 cases, all headers compared, narrow named divergences, misbehaving-auth and Upgrade-token cases

This commit is contained in:
2026-11-07 15:53:38 +01:00
parent a272e476b7
commit bcf94928c9
4 changed files with 381 additions and 150 deletions
+1 -1
View File
@@ -147,7 +147,7 @@ async fn injected_secret_never_appears_in_a_response_or_log() {
.await
.unwrap()
{
WsOutcome::Upgraded { status, echo } => {
WsOutcome::Upgraded { status, echo, .. } => {
assert_eq!(status, 101);
assert_eq!(echo, "ping");
}
+358 -146
View File
@@ -58,7 +58,7 @@ impl Env {
let auth = MockAuthelia::start().await;
let site = format!(
"secrets = [\"api_key\"]\n\n[forward_auth]\nurl = \"{}\"\n",
"secrets = [\"api_key\"]\n\n[forward_auth]\nurl = \"{}\"\ncopy_headers = [\"Remote-User\", \"Remote-Groups\"]\n",
auth.url()
);
let rules = "\
@@ -276,37 +276,45 @@ pub enum Action {
},
}
/// 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,
/// 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,
}
}
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, health checks.
/// auth denied and allowed, misbehaving auth server, health checks, odd request targets.
pub fn corpus() -> Vec<Case> {
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(
@@ -333,6 +341,13 @@ pub fn corpus() -> Vec<Case> {
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,
@@ -368,50 +383,52 @@ pub fn corpus() -> Vec<Case> {
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(
"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",
@@ -437,7 +454,7 @@ pub fn corpus() -> Vec<Case> {
https(
"auth forbidden",
a,
Req::get(a, "/").header("cookie", "authelia_session=forbidden"),
Req::get(a, "/").header("cookie", &session("forbidden")),
),
https(
"auth allowed with session",
@@ -451,11 +468,19 @@ pub fn corpus() -> Vec<Case> {
.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", "authelia_session=nameless")
.header("cookie", &session("nameless"))
.header("remote-user", "mallory"),
),
https(
@@ -468,24 +493,40 @@ pub fn corpus() -> Vec<Case> {
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(
"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 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",
@@ -497,6 +538,20 @@ pub fn corpus() -> Vec<Case> {
]
}
/// 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 {
@@ -505,56 +560,59 @@ pub struct Observation {
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);
fn observe_parts(status: u16, raw: &[(String, String)], body: &[u8], t: &Target) -> Observation {
let mut headers: BTreeMap<String, String> = 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()), ":<https-port>");
headers
.entry(n)
.and_modify(|e| {
e.push('\n');
e.push_str(&v)
})
.or_insert(v);
}
Observation {
status: resp.status,
status,
headers,
body: String::from_utf8_lossy(&resp.body).into_owned(),
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<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::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, echo }) => Observation {
Ok(WsOutcome::Upgraded {
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}"),
},
headers,
echo,
}) => observe_parts(status, &headers, format!("echo: {echo}").as_bytes(), t),
Ok(WsOutcome::Refused(r)) => observe(&r, t),
Err(e) => failed(e),
}
}
}
@@ -566,19 +624,116 @@ pub struct Outcome {
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).",
)];
/// 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,
},
}
/// 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",
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",
},
];
impl Outcome {
@@ -586,24 +741,46 @@ impl Outcome {
self.ianitor == self.caddy
}
/// `Some(id)` when the only difference is a documented divergence.
pub fn known_divergence(&self) -> Option<&'static str> {
/// The divergence ids that explain every difference, or `None`.
pub fn known_divergence(&self) -> Option<String> {
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");
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());
}
}
None
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 {
@@ -628,26 +805,37 @@ impl Report {
}
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, {} known divergence, {} differ\n",
"== {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(),
self.known().len(),
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);
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);
let _ = writeln!(s, " {kd:<10} {: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));
let _ = writeln!(s, " DIFF {}", o.name);
for d in differences(&o.ianitor, &o.caddy) {
let _ = writeln!(s, " {d}");
}
}
}
for (id, why) in KNOWN_DIVERGENCES {
let _ = writeln!(s, " {id}: {why}");
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
}
@@ -721,3 +909,27 @@ pub fn break_edge(json: &str) -> String {
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<String> {
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
}
+20 -2
View File
@@ -183,7 +183,11 @@ pub async fn http(addr: SocketAddr, req: &Req) -> io::Result<Resp> {
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WsOutcome {
/// 101, the echoed message.
Upgraded { status: u16, echo: String },
Upgraded {
status: u16,
headers: Vec<(String, String)>,
echo: String,
},
/// The upgrade was answered with a normal HTTP response.
Refused(Resp),
}
@@ -212,6 +216,16 @@ pub async fn websocket(
match tokio_tungstenite::client_async(request, s).await {
Ok((mut ws, resp)) => {
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();
ws.send(tungstenite::Message::text(message))
.await
.map_err(other)?;
@@ -220,7 +234,11 @@ pub async fn websocket(
other_msg => return Err(other(format!("no echo: {other_msg:?}"))),
};
let _ = ws.close(None).await;
Ok(WsOutcome::Upgraded { status, echo })
Ok(WsOutcome::Upgraded {
status,
headers,
echo,
})
}
Err(tungstenite::Error::Http(resp)) => {
let status = resp.status().as_u16();
+2 -1
View File
@@ -23,8 +23,9 @@ use crate::fnv64;
/// Request headers the echo server reports back (lowercase). Secret-carrying headers are
/// reported as a hash only, so a passing test never needs the value in a response body.
pub const ECHO_HEADERS: [&str; 12] = [
pub const ECHO_HEADERS: [&str; 13] = [
"host",
"x-remove-me-too",
"x-forwarded-for",
"x-forwarded-proto",
"x-forwarded-host",