[edge] Tests first: QC repros for 1xx, auth timeout, name resolution, Upgrade tokens, Remote-* stripping (red)

This commit is contained in:
2026-11-07 15:36:00 +01:00
parent fd4b4a7775
commit d42c178a13
6 changed files with 414 additions and 134 deletions
+93
View File
@@ -255,3 +255,96 @@ async fn unreachable_auth_server_fails_closed() {
assert_eq!(r.status, 502);
assert!(echo.proxied().is_empty());
}
/// QC B2a, B2b, m3: misbehaving auth servers. Edge fails closed and never crashes or hangs.
#[tokio::test(flavor = "multi_thread")]
async fn misbehaving_auth_answers_fail_closed() {
let authelia = MockAuthelia::start().await;
let echo = Echo::start("app").await;
let site = site(&authelia.url());
let edge = start(EdgeSpec {
site: &site,
hosts: vec![host_file(
"auth.test",
&format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", echo.url()),
)],
..Default::default()
});
let go = |session: &'static str| {
let roots = edge.roots();
let addr = edge.https;
async move {
let cookie = format!("authelia_session={session}");
client::https(addr, "auth.test", roots, &Req::get("auth.test", "/").header("cookie", &cookie)).await
}
};
// 100 Continue before the real answer is skipped, like any HTTP client does.
let r = go("continue-ok").await.expect("edge answers after a 1xx from the auth server");
assert_eq!(r.status, 200);
assert_eq!(echo.proxied().len(), 1);
assert_eq!(echo.proxied()[0].header("remote-user"), Some(b"alice".as_slice()));
echo.clear();
// 101 is a final answer but not an allow: denied with 502.
assert_eq!(go("switch").await.unwrap().status, 502);
// Oversized or truncated auth answers: 502, never forwarded.
assert_eq!(go("big-ok").await.unwrap().status, 502);
assert_eq!(go("big-deny").await.unwrap().status, 502);
assert_eq!(go("truncated-ok").await.unwrap().status, 502);
assert!(echo.proxied().is_empty(), "{:?}", echo.proxied());
// An auth server that never answers: 502 once the 10 s auth timeout passes.
let t = std::time::Instant::now();
let r = go("hang").await.expect("edge answers a hanging auth server");
assert_eq!(r.status, 502);
assert!(t.elapsed() < std::time::Duration::from_secs(14), "took {:?}", t.elapsed());
assert!(echo.proxied().is_empty());
// Still serving afterwards.
assert_eq!(go("good").await.unwrap().status, 200);
}
/// QC m5: client-sent Remote-* headers never reach a forward-auth upstream, whatever
/// copy_headers says.
#[tokio::test(flavor = "multi_thread")]
async fn remote_headers_are_stripped_even_with_a_custom_copy_list() {
let authelia = MockAuthelia::start().await;
let echo = Echo::start("app").await;
for copy in ["[]", "[\"Remote-User\"]"] {
echo.clear();
let site = format!("[forward_auth]\nurl = \"{}\"\ncopy_headers = {copy}\n", authelia.url());
let edge = start(EdgeSpec {
site: &site,
hosts: vec![host_file(
"auth.test",
&format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", echo.url()),
)],
..Default::default()
});
let r = client::https(
edge.https,
"auth.test",
edge.roots(),
&Req::get("auth.test", "/")
.header("cookie", "authelia_session=good")
.header("remote-user", "mallory")
.header("remote-groups", "root")
.header("remote-email", "m@evil.test")
.header("remote-name", "Mallory"),
)
.await
.unwrap();
assert_eq!(r.status, 200);
let up = &echo.proxied()[0];
let user = up.header("remote-user");
if copy == "[]" {
assert_eq!(user, None, "copy_headers = []");
} else {
assert_eq!(user, Some(b"alice".as_slice()));
}
for h in ["remote-groups", "remote-email", "remote-name"] {
assert_eq!(up.header(h), None, "{h} with copy_headers = {copy}");
}
}
}
+103
View File
@@ -0,0 +1,103 @@
// 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/.
//! Upstream handling: name resolution at connect time, health checks that survive odd
//! answers, websocket refusal on every Upgrade token, absolute-form requests.
#![cfg(unix)]
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod common;
use std::time::{Duration, Instant};
use common::{EdgeSpec, host_file, start};
use ianitor_testkit::client::{self, Req};
use ianitor_testkit::raw::{RawServer, Reply, response};
use ianitor_testkit::upstream::Echo;
/// QC M1: `localhost` may resolve to ::1 first while the service listens on 127.0.0.1 only.
#[tokio::test(flavor = "multi_thread")]
async fn upstream_names_are_resolved_at_connect_time_trying_every_address() {
let echo = Echo::start("app").await;
let edge = start(EdgeSpec {
hosts: vec![
host_file("local.test", &format!("upstreams = [\"http://localhost:{}\"]\n", echo.addr.port())),
host_file("gone.test", "upstreams = [\"http://no-such-host.invalid:8080\"]\n"),
],
..Default::default()
});
let r = client::https(edge.https, "local.test", edge.roots(), &Req::get("local.test", "/")).await.unwrap();
assert_eq!(r.status, 200, "{}", edge.stderr());
// An upstream that does not resolve is a 502 for that host, not a startup failure.
let r = client::https(edge.https, "gone.test", edge.roots(), &Req::get("gone.test", "/")).await.unwrap();
assert_eq!(r.status, 502);
}
/// QC B2a: a health endpoint that sends a 1xx must not kill health checking.
#[tokio::test(flavor = "multi_thread")]
async fn health_checks_survive_informational_answers() {
let started = Instant::now();
let up = RawServer::start(move |req| {
if req.path == "/healthz" && started.elapsed() < Duration::from_secs(3) {
let mut b = b"HTTP/1.1 102 Processing\r\n\r\n".to_vec();
b.extend(response(200, "OK", &[], b"ok"));
Reply::Bytes(b)
} else {
Reply::Bytes(response(500, "Internal Server Error", &[], b"broken"))
}
})
.await;
let edge = start(EdgeSpec {
hosts: vec![host_file(
"hc.test",
&format!("upstreams = [\"{}\"]\n[health_check]\npath = \"/healthz\"\ninterval_secs = 1\n", up.url()),
)],
..Default::default()
});
tokio::time::sleep(Duration::from_millis(5500)).await;
let r = client::https(edge.https, "hc.test", edge.roots(), &Req::get("hc.test", "/")).await.unwrap();
assert_eq!(r.status, 503, "health checks kept running and marked the upstream down\n{}", edge.stderr());
assert!(up.requests().iter().filter(|r| r.path == "/healthz").count() >= 4);
}
/// QC m4: every Upgrade header and every comma-separated token counts.
#[tokio::test(flavor = "multi_thread")]
async fn websocket_refusal_checks_every_upgrade_token() {
let echo = Echo::start("app").await;
let edge = start(EdgeSpec {
hosts: vec![host_file("nows.test", &format!("upstreams = [\"{}\"]\nwebsockets = false\n", echo.url()))],
..Default::default()
});
let cases = [
Req::get("nows.test", "/").header("connection", "upgrade").header("upgrade", "h2c").header("upgrade", "websocket"),
Req::get("nows.test", "/").header("connection", "upgrade").header("upgrade", "websocket, h2c"),
Req::get("nows.test", "/").header("connection", "upgrade").header("upgrade", "h2c , WebSocket"),
];
for req in &cases {
let r = client::https(edge.https, "nows.test", edge.roots(), req).await.unwrap();
assert_eq!(r.status, 403, "{req:?}");
}
assert!(echo.proxied().is_empty());
}
/// QC nit: absolute-form request targets are answered and routed by the URI's host
/// (RFC 9112 §3.2.2), as Go/Caddy do.
#[tokio::test(flavor = "multi_thread")]
async fn absolute_form_requests_are_answered() {
let echo = Echo::start("app").await;
let edge = start(EdgeSpec {
hosts: vec![host_file("plain.test", &format!("upstreams = [\"{}\"]\n", echo.url()))],
..Default::default()
});
let r = client::http(edge.http, &Req::get("plain.test", "http://evil.test/x")).await.unwrap();
assert_eq!(r.status, 404, "plain HTTP");
let r = client::https(edge.https, "plain.test", edge.roots(), &Req::get("plain.test", "https://evil.test/x"))
.await
.unwrap();
assert_eq!(r.status, 404, "HTTPS");
let r = client::http(edge.http, &Req::get("evil.test", "http://plain.test/x?y")).await.unwrap();
assert_eq!(r.status, 308);
assert!(echo.proxied().is_empty());
}
+103 -134
View File
@@ -9,61 +9,124 @@
//!
//! Decisions of the mock (the real Authelia decides from its access-control rules):
//! - `Authorization: Bearer good` → 200 with identity; any other Authorization → 401 + WWW-Authenticate
//! - cookie `authelia_session=good` → 200 with identity
//! - cookie `authelia_session=nameless` → 200 without identity headers
//! - cookie `authelia_session=forbidden` → 403
//! - cookie `authelia_session=good` → 200 with identity; `nameless` → 200 without identity;
//! `forbidden` → 403
//! - misbehaving answers, by cookie: `continue-ok` (100 Continue, then 200), `big-ok` /
//! `big-deny` (200 / 401 with a 5 MB body), `truncated-ok` (200 whose body is cut short),
//! `switch` (101 Switching Protocols), `hang` (never answers)
//! - otherwise GET/HEAD → 302 to the portal with `rd`, other methods → 401
//!
//! Every answer says in `x-sent-content-type` which Content-Type the mock sent (or `none`).
use std::convert::Infallible;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex};
use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper::body::Incoming;
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{Request, Response};
use hyper_util::rt::TokioIo;
use tokio::net::TcpListener;
use crate::raw::{RawServer, Reply, response};
use crate::upstream::Recorded;
pub const PATH: &str = "/api/authz/forward-auth";
pub const PORTAL: &str = "https://auth.test/";
const IDENTITY: [(&str, &str); 4] = [
("Remote-User", "alice"),
("Remote-Groups", "admins,dev"),
("Remote-Email", "alice@example.org"),
("Remote-Name", "Alice Example"),
];
const BIG: usize = 5_000_000;
#[derive(Clone)]
pub struct MockAuthelia {
pub addr: SocketAddr,
requests: Arc<Mutex<Vec<Recorded>>>,
server: RawServer,
}
fn h(req: &Recorded, name: &str) -> Option<String> {
req.header(name).map(|v| String::from_utf8_lossy(v).into_owned())
}
fn text(status: u16, reason: &str, body: &str) -> Vec<u8> {
response(
status,
reason,
&[("Content-Type", "text/plain; charset=utf-8"), ("X-Sent-Content-Type", "text/plain; charset=utf-8")],
body.as_bytes(),
)
}
fn allowed(identity: bool) -> Vec<u8> {
let mut hs: Vec<(&str, &str)> = vec![("X-Sent-Content-Type", "none")];
if identity {
hs.extend(IDENTITY);
}
response(200, "OK", &hs, b"")
}
fn decide(req: &Recorded) -> Reply {
if req.method != "GET" || req.path != PATH {
return Reply::Bytes(text(404, "Not Found", "404 page not found"));
}
let (Some(method), Some(proto), Some(host), Some(uri)) =
(h(req, "x-forwarded-method"), h(req, "x-forwarded-proto"), h(req, "x-forwarded-host"), h(req, "x-forwarded-uri"))
else {
return Reply::Bytes(text(400, "Bad Request", "missing X-Forwarded headers"));
};
if let Some(auth) = h(req, "authorization") {
return Reply::Bytes(if auth == "Bearer good" {
allowed(true)
} else {
response(
401,
"Unauthorized",
&[("WWW-Authenticate", "Basic realm=\"Authorization Required\""), ("X-Sent-Content-Type", "none")],
b"401 Unauthorized",
)
});
}
let cookie = h(req, "cookie").unwrap_or_default();
let session = cookie.split(';').filter_map(|c| c.trim().strip_prefix("authelia_session=")).next().unwrap_or("");
Reply::Bytes(match session {
"good" => allowed(true),
"nameless" => allowed(false),
"forbidden" => text(403, "Forbidden", "403 Forbidden"),
"continue-ok" => {
let mut b = b"HTTP/1.1 100 Continue\r\n\r\n".to_vec();
b.extend(allowed(true));
b
}
"big-ok" => {
let mut hs: Vec<(&str, &str)> = vec![("X-Sent-Content-Type", "none")];
hs.extend(IDENTITY);
response(200, "OK", &hs, &vec![b'a'; BIG])
}
"big-deny" => response(401, "Unauthorized", &[("X-Sent-Content-Type", "none")], &vec![b'a'; BIG]),
"truncated-ok" => {
b"HTTP/1.1 200 OK\r\nRemote-User: alice\r\nContent-Length: 1000\r\nConnection: close\r\n\r\nonly-a-bit".to_vec()
}
"switch" => b"HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n".to_vec(),
"hang" => return Reply::Hang,
_ if method == "GET" || method == "HEAD" => {
let rd = format!("{proto}://{host}{uri}");
let location = format!("{PORTAL}?rd={}", percent(&rd));
let body = format!("<a href=\"{location}\">302 Found</a>");
response(
302,
"Found",
&[
("Location", &location),
("Set-Cookie", "authelia_flow=1; Path=/; HttpOnly"),
("Content-Type", "text/html; charset=utf-8"),
("X-Sent-Content-Type", "text/html; charset=utf-8"),
],
body.as_bytes(),
)
}
_ => text(401, "Unauthorized", "401 Unauthorized"),
})
}
impl MockAuthelia {
pub async fn start() -> MockAuthelia {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let m = MockAuthelia {
addr: listener.local_addr().unwrap(),
requests: Arc::default(),
};
let mm = m.clone();
tokio::spawn(async move {
loop {
let Ok((stream, _)) = listener.accept().await else {
continue;
};
let mm = mm.clone();
tokio::spawn(async move {
let svc = service_fn(move |req| {
let mm = mm.clone();
async move { Ok::<_, Infallible>(mm.handle(req).await) }
});
let _ = http1::Builder::new()
.serve_connection(TokioIo::new(stream), svc)
.await;
});
}
});
m
let server = RawServer::start(decide).await;
MockAuthelia { addr: server.addr, server }
}
/// The `[forward_auth] url` for the site file.
@@ -72,101 +135,7 @@ impl MockAuthelia {
}
pub fn requests(&self) -> Vec<Recorded> {
self.requests.lock().unwrap().clone()
}
async fn handle(&self, req: Request<Incoming>) -> Response<Full<Bytes>> {
let (parts, body) = req.into_parts();
let body = body
.collect()
.await
.map(|b| b.to_bytes())
.unwrap_or_default();
self.requests.lock().unwrap().push(Recorded {
method: parts.method.to_string(),
path: parts.uri.path().to_owned(),
headers: parts
.headers
.iter()
.map(|(n, v)| (n.as_str().to_owned(), v.as_bytes().to_vec()))
.collect(),
body: body.to_vec(),
});
let h = |name: &str| {
parts
.headers
.get(name)
.and_then(|v| v.to_str().ok())
.map(str::to_owned)
};
let text = |status: u16, body: &str| {
Response::builder()
.status(status)
.header("content-type", "text/plain; charset=utf-8")
.body(Full::new(Bytes::from(body.to_owned())))
.unwrap()
};
if parts.method != hyper::Method::GET || parts.uri.path() != PATH {
return text(404, "404 page not found");
}
let (Some(method), Some(proto), Some(host), Some(uri)) = (
h("x-forwarded-method"),
h("x-forwarded-proto"),
h("x-forwarded-host"),
h("x-forwarded-uri"),
) else {
return text(400, "missing X-Forwarded headers");
};
let allowed = |identity: bool| {
let mut b = Response::builder().status(200);
if identity {
b = b
.header("remote-user", "alice")
.header("remote-groups", "admins,dev")
.header("remote-email", "alice@example.org")
.header("remote-name", "Alice Example");
}
b.body(Full::new(Bytes::new())).unwrap()
};
if let Some(auth) = h("authorization") {
return if auth == "Bearer good" {
allowed(true)
} else {
Response::builder()
.status(401)
.header("www-authenticate", "Basic realm=\"Authorization Required\"")
.body(Full::new(Bytes::from_static(b"401 Unauthorized")))
.unwrap()
};
}
let cookie = h("cookie").unwrap_or_default();
let session = cookie
.split(';')
.filter_map(|c| c.trim().strip_prefix("authelia_session="))
.next()
.unwrap_or("");
match session {
"good" => allowed(true),
"nameless" => allowed(false),
"forbidden" => text(403, "403 Forbidden"),
_ if method == "GET" || method == "HEAD" => {
let rd = format!("{proto}://{host}{uri}");
let location = format!("{PORTAL}?rd={}", percent(&rd));
Response::builder()
.status(302)
.header("location", location.clone())
.header("set-cookie", "authelia_flow=1; Path=/; HttpOnly")
.header("content-type", "text/html; charset=utf-8")
.body(Full::new(Bytes::from(format!(
"<a href=\"{location}\">302 Found</a>"
))))
.unwrap()
}
_ => text(401, "401 Unauthorized"),
}
self.server.requests()
}
}
+1
View File
@@ -10,6 +10,7 @@
pub mod authelia;
pub mod client;
pub mod proc;
pub mod raw;
pub mod tls;
pub mod upstream;
+101
View File
@@ -0,0 +1,101 @@
// 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/.
//! A raw TCP HTTP/1.1 server that answers with scripted bytes: 1xx heads, truncated bodies,
//! hangs. One request per connection, then the connection is closed.
use std::net::SocketAddr;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
use crate::upstream::Recorded;
pub enum Reply {
/// Write these bytes, then close.
Bytes(Vec<u8>),
/// Accept, read the request, never answer (until the peer gives up).
Hang,
}
/// A complete response with Content-Length and `Connection: close`.
pub fn response(status: u16, reason: &str, headers: &[(&str, &str)], body: &[u8]) -> Vec<u8> {
let mut out = format!("HTTP/1.1 {status} {reason}\r\n");
for (n, v) in headers {
out.push_str(&format!("{n}: {v}\r\n"));
}
out.push_str(&format!("Content-Length: {}\r\nConnection: close\r\n\r\n", body.len()));
let mut bytes = out.into_bytes();
bytes.extend_from_slice(body);
bytes
}
type Handler = dyn Fn(&Recorded) -> Reply + Send + Sync;
#[derive(Clone)]
pub struct RawServer {
pub addr: SocketAddr,
requests: Arc<Mutex<Vec<Recorded>>>,
}
impl RawServer {
pub async fn start(handler: impl Fn(&Recorded) -> Reply + Send + Sync + 'static) -> RawServer {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let server = RawServer { addr: listener.local_addr().unwrap(), requests: Arc::default() };
let handler: Arc<Handler> = Arc::new(handler);
let requests = server.requests.clone();
tokio::spawn(async move {
loop {
let Ok((mut stream, _)) = listener.accept().await else { continue };
let handler = handler.clone();
let requests = requests.clone();
tokio::spawn(async move {
let mut buf = Vec::new();
let mut chunk = [0u8; 4096];
while !buf.windows(4).any(|w| w == b"\r\n\r\n") && buf.len() < 65536 {
match stream.read(&mut chunk).await {
Ok(0) | Err(_) => return,
Ok(n) => buf.extend_from_slice(&chunk[..n]),
}
}
let Some(req) = parse(&buf) else { return };
requests.lock().unwrap().push(req.clone());
match handler(&req) {
Reply::Bytes(b) => {
let _ = stream.write_all(&b).await;
let _ = stream.shutdown().await;
}
Reply::Hang => tokio::time::sleep(Duration::from_secs(600)).await,
}
});
}
});
server
}
pub fn requests(&self) -> Vec<Recorded> {
self.requests.lock().unwrap().clone()
}
pub fn url(&self) -> String {
format!("http://{}", self.addr)
}
}
fn parse(buf: &[u8]) -> Option<Recorded> {
let end = buf.windows(4).position(|w| w == b"\r\n\r\n")?;
let head = std::str::from_utf8(&buf[..end]).ok()?;
let mut lines = head.split("\r\n");
let mut first = lines.next()?.split(' ');
let method = first.next()?.to_owned();
let target = first.next()?.to_owned();
let path = target.split('?').next().unwrap_or("").to_owned();
let headers = lines
.filter_map(|l| l.split_once(':'))
.map(|(n, v)| (n.trim().to_ascii_lowercase(), v.trim().as_bytes().to_vec()))
.collect();
Some(Recorded { method, path, headers, body: Vec::new() })
}
+13
View File
@@ -121,7 +121,20 @@ impl Echo {
self.requests.lock().unwrap().clear();
}
/// Every answer says in `x-sent-content-type` which Content-Type it carried (or `none`),
/// so the diff harness can tell what the engines added.
async fn handle(&self, req: Request<Incoming>) -> Response<Body> {
let mut resp = self.answer(req).await;
let sent = resp
.headers()
.get("content-type")
.cloned()
.unwrap_or_else(|| hyper::header::HeaderValue::from_static("none"));
resp.headers_mut().insert("x-sent-content-type", sent);
resp
}
async fn answer(&self, req: Request<Incoming>) -> Response<Body> {
let (parts, body) = req.into_parts();
let body = body
.collect()