[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 .await
.unwrap() .unwrap()
{ {
WsOutcome::Upgraded { status, echo } => { WsOutcome::Upgraded { status, echo, .. } => {
assert_eq!(status, 101); assert_eq!(status, 101);
assert_eq!(echo, "ping"); assert_eq!(echo, "ping");
} }
+352 -140
View File
@@ -58,7 +58,7 @@ impl Env {
let auth = MockAuthelia::start().await; let auth = MockAuthelia::start().await;
let site = format!( 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() auth.url()
); );
let rules = "\ 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 struct Case {
pub name: &'static str, pub name: &'static str,
pub action: Action, 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 { fn https(name: &'static str, sni: &'static str, req: Req) -> Case {
Case { Case {
name, name,
action: Action::Https { sni, req }, 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, /// 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> { pub fn corpus() -> Vec<Case> {
let p = "plain.test"; let p = "plain.test";
let a = "auth.test"; let a = "auth.test";
let good = ("cookie", "authelia_session=good"); let good = ("cookie", "authelia_session=good");
let session = |s: &str| format!("authelia_session={s}");
vec![ vec![
https("plain GET", p, Req::get(p, "/")), https("plain GET", p, Req::get(p, "/")),
https( https(
@@ -333,6 +341,13 @@ pub fn corpus() -> Vec<Case> {
p, p,
Req::get(p, "/").header("x-remove-me", "1"), 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( https(
"request header overwritten", "request header overwritten",
p, p,
@@ -368,50 +383,52 @@ pub fn corpus() -> Vec<Case> {
p, p,
Req::get("unknown.test", "/"), Req::get("unknown.test", "/"),
), ),
Case { https(
name: "HTTP redirects to HTTPS", "absolute-form target, same host",
action: Action::Http { p,
req: Req::get(p, "/a/b?c=d"), Req::get(p, "https://plain.test/abs?q=1"),
}, ),
headers: STD, https(
}, "absolute-form target, other host",
Case { p,
name: "HTTP unknown host", Req::get(p, "https://evil.test/x"),
action: Action::Http { ),
req: Req::get("unknown.test", "/"), http("HTTP redirects to HTTPS", Req::get(p, "/a/b?c=d")),
}, http("HTTP unknown host", Req::get("unknown.test", "/")),
headers: STD, http(
}, "HTTP unknown ACME token",
Case { Req::get(p, "/.well-known/acme-challenge/nope"),
name: "HTTP unknown ACME token", ),
action: Action::Http { http(
req: Req::get(p, "/.well-known/acme-challenge/nope"), "HTTP absolute-form, same host",
}, Req::get(p, "http://plain.test/x?y"),
headers: STD, ),
}, http(
Case { "HTTP absolute-form, other host",
name: "websocket upgrade", Req::get(p, "http://evil.test/x"),
action: Action::Websocket { ),
sni: "ws.test", ws("websocket upgrade", "ws.test", vec![]),
host: "ws.test", ws("websocket refused when disabled", "nows.test", vec![]),
headers: vec![],
},
headers: &["upgrade"],
},
Case {
name: "websocket refused when disabled",
action: Action::Websocket {
sni: "nows.test",
host: "nows.test",
headers: vec![],
},
headers: STD,
},
https( https(
"plain GET where websockets are disabled", "plain GET where websockets are disabled",
"nows.test", "nows.test",
Req::get("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 GET", "down.test", Req::get("down.test", "/")),
https( https(
"upstream down POST", "upstream down POST",
@@ -437,7 +454,7 @@ pub fn corpus() -> Vec<Case> {
https( https(
"auth forbidden", "auth forbidden",
a, a,
Req::get(a, "/").header("cookie", "authelia_session=forbidden"), Req::get(a, "/").header("cookie", &session("forbidden")),
), ),
https( https(
"auth allowed with session", "auth allowed with session",
@@ -451,11 +468,19 @@ pub fn corpus() -> Vec<Case> {
.header(good.0, good.1) .header(good.0, good.1)
.header("remote-user", "mallory"), .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( https(
"auth allowed without identity strips spoofed", "auth allowed without identity strips spoofed",
a, a,
Req::get(a, "/me") Req::get(a, "/me")
.header("cookie", "authelia_session=nameless") .header("cookie", &session("nameless"))
.header("remote-user", "mallory"), .header("remote-user", "mallory"),
), ),
https( https(
@@ -468,24 +493,40 @@ pub fn corpus() -> Vec<Case> {
a, a,
Req::get(a, "/search?q=a+b").header(good.0, good.1), Req::get(a, "/search?q=a+b").header(good.0, good.1),
), ),
Case { https(
name: "websocket denied by auth", "auth allowed POST keeps the body",
action: Action::Websocket { a,
sni: "wsauth.test", Req::new("POST", a, "/form")
host: "wsauth.test", .header(good.0, good.1)
headers: vec![], .body(b"field=value"),
}, ),
headers: STD, https(
}, "auth answers 100 Continue first",
Case { a,
name: "websocket allowed by auth", Req::get(a, "/").header("cookie", &session("continue-ok")),
action: Action::Websocket { ),
sni: "wsauth.test", https(
host: "wsauth.test", "auth answers 2xx with a 5 MB body",
headers: vec![good], a,
}, Req::get(a, "/").header("cookie", &session("big-ok")),
headers: &["upgrade"], ),
}, 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("healthy upstream", "hc.test", Req::get("hc.test", "/")),
https( https(
"all upstreams unhealthy", "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. /// What one engine answered, normalised for comparison.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct Observation { pub struct Observation {
@@ -505,56 +560,59 @@ pub struct Observation {
pub body: String, pub body: String,
} }
fn observe(resp: &Resp, case: &Case, t: &Target) -> Observation { fn observe_parts(status: u16, raw: &[(String, String)], body: &[u8], t: &Target) -> Observation {
let mut headers = BTreeMap::new(); let mut headers: BTreeMap<String, String> = BTreeMap::new();
for h in case.headers { for (n, v) in raw {
let all = resp.header_all(h); let n = n.to_ascii_lowercase();
if !all.is_empty() { if IGNORED_HEADERS.iter().any(|(i, _)| *i == n) {
// The two engines listen on different ports; Location carries the HTTPS port. continue;
let v = all
.join("\n")
.replace(&format!(":{}", t.https.port()), ":<https-port>");
headers.insert((*h).to_owned(), v);
} }
// 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 { Observation {
status: resp.status, status,
headers, 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 { pub async fn run_case(case: &Case, t: &Target, roots: Arc<RootCertStore>) -> Observation {
match &case.action { match &case.action {
Action::Https { sni, req } => match client::https(t.https, sni, roots, req).await { Action::Https { sni, req } => client::https(t.https, sni, roots, req)
Ok(r) => observe(&r, case, t), .await
Err(e) => Observation { .map_or_else(failed, |r| observe(&r, t)),
status: 0, Action::Http { req } => client::http(t.http, req)
headers: BTreeMap::new(), .await
body: format!("client error: {e}"), .map_or_else(failed, |r| observe(&r, t)),
},
},
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 } => { Action::Websocket { sni, host, headers } => {
match client::websocket(t.https, sni, roots, host, "/socket", headers, "ping").await { match client::websocket(t.https, sni, roots, host, "/socket", headers, "ping").await {
Ok(WsOutcome::Upgraded { status, echo }) => Observation { Ok(WsOutcome::Upgraded {
status, status,
headers: BTreeMap::new(), headers,
body: format!("echo: {echo}"), echo,
}, }) => observe_parts(status, &headers, format!("echo: {echo}").as_bytes(), t),
Ok(WsOutcome::Refused(r)) => observe(&r, case, t), Ok(WsOutcome::Refused(r)) => observe(&r, t),
Err(e) => Observation { Err(e) => failed(e),
status: 0,
headers: BTreeMap::new(),
body: format!("client error: {e}"),
},
} }
} }
} }
@@ -566,19 +624,116 @@ pub struct Outcome {
pub caddy: Observation, pub caddy: Observation,
} }
/// Documented, accepted differences between the engines, each with its reason. Anything /// How a documented divergence is recognised. Each rule is narrow on purpose.
/// else is a mismatch. pub enum Rule {
pub const KNOWN_DIVERGENCES: &[(&str, &str)] = &[( /// Caddy has `header` with one of `values` and Ianitor has no such header; with `only_if`,
"KD-1", /// Caddy's answer must also carry that header/value pair (the upstream's own report).
"Caddy (Go net/http) adds a sniffed Content-Type when the upstream sends none; \ ExtraHeaderInCaddy {
Ianitor passes the upstream response unchanged (no MIME sniffing).", 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. pub struct Divergence {
const SNIFFED: [&str; 3] = [ 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/plain; charset=utf-8",
"text/html; charset=utf-8", "text/html; charset=utf-8",
"application/octet-stream", "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 { impl Outcome {
@@ -586,24 +741,46 @@ impl Outcome {
self.ianitor == self.caddy self.ianitor == self.caddy
} }
/// `Some(id)` when the only difference is a documented divergence. /// The divergence ids that explain every difference, or `None`.
pub fn known_divergence(&self) -> Option<&'static str> { pub fn known_divergence(&self) -> Option<String> {
if self.same() { if self.same() {
return None; return None;
} }
let sniffed = self for d in KNOWN_DIVERGENCES {
.caddy if let Rule::Status {
.headers case,
.get("content-type") ianitor,
.is_some_and(|v| SNIFFED.contains(&v.as_str())); caddy,
if sniffed && !self.ianitor.headers.contains_key("content-type") { } = 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 c = self.caddy.clone();
c.headers.remove("content-type"); let mut ids = Vec::new();
if c == self.ianitor { for d in KNOWN_DIVERGENCES {
return Some("KD-1"); 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);
} }
} }
None }
(!ids.is_empty() && c == self.ianitor).then(|| ids.join("+"))
} }
pub fn mismatch(&self) -> bool { pub fn mismatch(&self) -> bool {
@@ -628,26 +805,37 @@ impl Report {
} }
pub fn render(&self, title: &str) -> String { 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!( 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.len(),
self.outcomes.iter().filter(|o| o.same()).count(), self.outcomes.iter().filter(|o| o.same()).count(),
self.known().len(), identity,
self.known().len() - identity,
self.mismatches().len() self.mismatches().len()
); );
for o in &self.outcomes { for o in &self.outcomes {
if o.same() { 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() { } 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 { } else {
let _ = writeln!(s, " DIFF {}", o.name); let _ = writeln!(s, " DIFF {}", o.name);
let _ = writeln!(s, " ianitor: {:?}", short(&o.ianitor)); for d in differences(&o.ianitor, &o.caddy) {
let _ = writeln!(s, " caddy: {:?}", short(&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 s
} }
@@ -721,3 +909,27 @@ pub fn break_edge(json: &str) -> String {
pub async fn settle() { pub async fn settle() {
tokio::time::sleep(Duration::from_millis(2500)).await; 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)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum WsOutcome { pub enum WsOutcome {
/// 101, the echoed message. /// 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. /// The upgrade was answered with a normal HTTP response.
Refused(Resp), Refused(Resp),
} }
@@ -212,6 +216,16 @@ pub async fn websocket(
match tokio_tungstenite::client_async(request, s).await { match tokio_tungstenite::client_async(request, s).await {
Ok((mut ws, resp)) => { Ok((mut ws, resp)) => {
let status = resp.status().as_u16(); 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)) ws.send(tungstenite::Message::text(message))
.await .await
.map_err(other)?; .map_err(other)?;
@@ -220,7 +234,11 @@ pub async fn websocket(
other_msg => return Err(other(format!("no echo: {other_msg:?}"))), other_msg => return Err(other(format!("no echo: {other_msg:?}"))),
}; };
let _ = ws.close(None).await; let _ = ws.close(None).await;
Ok(WsOutcome::Upgraded { status, echo }) Ok(WsOutcome::Upgraded {
status,
headers,
echo,
})
} }
Err(tungstenite::Error::Http(resp)) => { Err(tungstenite::Error::Http(resp)) => {
let status = resp.status().as_u16(); 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 /// 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. /// 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", "host",
"x-remove-me-too",
"x-forwarded-for", "x-forwarded-for",
"x-forwarded-proto", "x-forwarded-proto",
"x-forwarded-host", "x-forwarded-host",