diff --git a/crates/edge/src/fetch.rs b/crates/edge/src/fetch.rs index f0172eb..ee9e900 100644 --- a/crates/edge/src/fetch.rs +++ b/crates/edge/src/fetch.rs @@ -3,7 +3,14 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! Small HTTP client on Pingora's connector, for forward-auth subrequests and health checks. +//! +//! - The whole exchange is bounded by one deadline (Pingora's connector ignores the peer's +//! read timeout, so the deadline is enforced here with `tokio::time::timeout`). +//! - Informational answers (100, 102, 103) are skipped; `101` is returned as the final head +//! without a body, for the caller to reject. +//! - Every resolved address is tried in order until one accepts the connection. +use std::net::SocketAddr; use std::time::Duration; use bytes::{Bytes, BytesMut}; @@ -21,14 +28,17 @@ pub struct Fetched { /// Dial timeout, matching Caddy's reverse_proxy default. pub const DIAL_TIMEOUT: Duration = Duration::from_secs(3); +/// More 1xx heads than this before a final answer is treated as a broken server. +const MAX_INFORMATIONAL: usize = 8; -pub fn peer(u: &UpstreamRt) -> HttpPeer { - let mut p = HttpPeer::new(u.addr, u.tls, u.sni.clone()); +pub fn peer(addr: SocketAddr, u: &UpstreamRt) -> HttpPeer { + let mut p = HttpPeer::new(addr, u.tls, u.sni.clone()); p.options.connection_timeout = Some(DIAL_TIMEOUT); p } -/// Send `req` without a body; read the whole response, at most `max_body` bytes of body. +/// Send `req` without a body; read the whole response, at most `max_body` bytes of body, +/// all within `timeout`. pub async fn fetch( connector: &Connector, u: &UpstreamRt, @@ -36,18 +46,76 @@ pub async fn fetch( max_body: usize, timeout: Duration, ) -> Result { - let mut p = peer(u); - p.options.read_timeout = Some(timeout); - p.options.write_timeout = Some(timeout); - p.options.total_connection_timeout = Some(timeout); - let (mut http, _reused) = connector.get_http_session(&p).await?; + match tokio::time::timeout(timeout, exchange(connector, u, req, max_body, timeout)).await { + Ok(r) => r, + Err(_) => Error::e_explain( + ErrorType::ReadTimedout, + format!("no complete answer within {timeout:?}"), + ), + } +} + +async fn exchange( + connector: &Connector, + u: &UpstreamRt, + req: RequestHeader, + max_body: usize, + timeout: Duration, +) -> Result { + let addrs = u.resolve().await.map_err(|e| { + Error::explain( + ErrorType::ConnectNoRoute, + format!("cannot resolve {}: {e}", u.authority), + ) + })?; + let mut last = None; + let mut session = None; + for addr in addrs { + let mut p = peer(addr, u); + p.options.total_connection_timeout = Some(timeout); + match connector.get_http_session(&p).await { + Ok((s, _reused)) => { + session = Some(s); + break; + } + Err(e) => last = Some(e), + } + } + let Some(mut http) = session else { + return Err(last.unwrap_or_else(|| { + Error::explain(ErrorType::ConnectError, "no address to connect to") + })); + }; + http.set_read_timeout(Some(timeout)); + http.set_write_timeout(Some(timeout)); http.write_request_header(Box::new(req)).await?; http.finish_request_body().await?; - http.read_response_header().await?; - let header = http - .response_header() - .cloned() - .ok_or_else(|| Error::explain(ErrorType::InvalidHTTPHeader, "no response header"))?; + + let mut header = None; + for _ in 0..=MAX_INFORMATIONAL { + http.read_response_header().await?; + let h = http + .response_header() + .cloned() + .ok_or_else(|| Error::explain(ErrorType::InvalidHTTPHeader, "no response header"))?; + let s = h.status.as_u16(); + if (100..200).contains(&s) && s != 101 { + continue; + } + header = Some(h); + break; + } + let header = header.ok_or_else(|| { + Error::explain(ErrorType::InvalidHTTPHeader, "only informational answers") + })?; + if header.status.as_u16() == 101 { + // Switching protocols: there is no HTTP body to read. + return Ok(Fetched { + header, + body: Bytes::new(), + }); + } + let mut body = BytesMut::new(); while let Some(chunk) = http.read_response_body().await? { if body.len() + chunk.len() > max_body { diff --git a/crates/edge/src/forward_auth.rs b/crates/edge/src/forward_auth.rs index 6f7b0a5..275714c 100644 --- a/crates/edge/src/forward_auth.rs +++ b/crates/edge/src/forward_auth.rs @@ -19,10 +19,10 @@ use std::time::Duration; use bytes::Bytes; use http::header::{self, HeaderName, HeaderValue}; -use pingora::Result; use pingora::connectors::http::Connector; use pingora::http::{RequestHeader, ResponseHeader}; use pingora::proxy::Session; +use pingora::{Error, ErrorType, Result}; use crate::fetch::fetch; use crate::runtime::ForwardAuthRt; @@ -82,6 +82,13 @@ pub async fn check( let got = fetch(connector, &fa.upstream, sub, MAX_AUTH_BODY, AUTH_TIMEOUT).await?; let status = got.header.status.as_u16(); + if status < 200 { + // 101 (or any 1xx left over) is not an answer we can pass on or treat as an allow. + return Error::e_explain( + ErrorType::InvalidHTTPHeader, + format!("auth server answered {status}"), + ); + } if (200..300).contains(&status) { let copy = fa .copy_headers diff --git a/crates/edge/src/health.rs b/crates/edge/src/health.rs index 648a53d..0195d99 100644 --- a/crates/edge/src/health.rs +++ b/crates/edge/src/health.rs @@ -35,25 +35,40 @@ async fn probe(connector: &Connector, u: &UpstreamRt, path: &str) -> bool { { return false; } - match tokio::time::timeout(TIMEOUT, fetch(connector, u, req, 64 * 1024, TIMEOUT)).await { - Ok(Ok(f)) => f.header.status.is_success(), - _ => false, + match fetch(connector, u, req, 64 * 1024, TIMEOUT).await { + Ok(f) => f.header.status.is_success(), + Err(_) => false, + } +} + +/// One round over a host's upstreams. Each probe runs in its own task, so a panic inside a +/// probe (e.g. a library bug on an odd answer) marks that upstream unhealthy instead of +/// ending health checks. +async fn round(host: &Arc, path: &str, connector: &Arc) { + for i in 0..host.upstreams.len() { + let (h, p, c) = (host.clone(), path.to_owned(), connector.clone()); + let ok = match tokio::spawn(async move { probe(&c, &h.upstreams[i], &p).await }).await { + Ok(ok) => ok, + Err(e) => { + log::error!(target: "ianitor::health", "{}: health check of {} crashed ({e}); counting it as failed", host.cfg.hostname, host.upstreams[i].authority); + false + } + }; + let u = &host.upstreams[i]; + if u.healthy.swap(ok, Ordering::Relaxed) != ok { + if ok { + log::info!(target: "ianitor::health", "{}: upstream {} is healthy again", host.cfg.hostname, u.authority); + } else { + log::warn!(target: "ianitor::health", "{}: upstream {} failed its health check", host.cfg.hostname, u.authority); + } + } } } async fn watch(host: Arc, path: String, every: Duration) { - let connector = Connector::new(None); + let connector = Arc::new(Connector::new(None)); loop { - for u in &host.upstreams { - let ok = probe(&connector, u, &path).await; - if u.healthy.swap(ok, Ordering::Relaxed) != ok { - if ok { - log::info!(target: "ianitor::health", "{}: upstream {} is healthy again", host.cfg.hostname, u.authority); - } else { - log::warn!(target: "ianitor::health", "{}: upstream {} failed its health check", host.cfg.hostname, u.authority); - } - } - } + round(&host, &path, &connector).await; tokio::time::sleep(every).await; } } @@ -61,16 +76,39 @@ async fn watch(host: Arc, path: String, every: Duration) { #[async_trait] impl BackgroundService for HealthChecks { async fn start(&self, mut shutdown: ShutdownWatch) { - let mut tasks = Vec::new(); - for host in self.rt.hosts.values() { - if let Some(hc) = &host.cfg.health_check { - let every = Duration::from_secs(u64::from(hc.interval_secs.max(1))); - tasks.push(tokio::spawn(watch(host.clone(), hc.path.clone(), every))); + let checked: Vec<(Arc, String, Duration)> = self + .rt + .hosts + .values() + .filter_map(|h| { + h.cfg.health_check.as_ref().map(|hc| { + ( + h.clone(), + hc.path.clone(), + Duration::from_secs(u64::from(hc.interval_secs.max(1))), + ) + }) + }) + .collect(); + let mut tasks = tokio::task::JoinSet::new(); + let mut which = std::collections::HashMap::new(); + for (i, (h, p, every)) in checked.iter().enumerate() { + which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i); + } + // A watcher never returns; if one ends anyway, say so and start it again. + loop { + tokio::select! { + _ = shutdown.changed() => break, + Some(done) = tasks.join_next_with_id() => { + let id = match &done { Ok((id, ())) => *id, Err(e) => e.id() }; + if let Some(i) = which.remove(&id) { + let (h, p, every) = &checked[i]; + log::error!(target: "ianitor::health", "{}: health checker stopped; restarting it", h.cfg.hostname); + which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i); + } + } } } - let _ = shutdown.changed().await; - for t in tasks { - t.abort(); - } + tasks.abort_all(); } } diff --git a/crates/edge/src/http_app.rs b/crates/edge/src/http_app.rs index bae8e31..82c0492 100644 --- a/crates/edge/src/http_app.rs +++ b/crates/edge/src/http_app.rs @@ -10,8 +10,11 @@ use std::time::Instant; use async_trait::async_trait; use http::{Response, StatusCode, header}; -use pingora::apps::http_app::ServeHttp; +use pingora::ErrorType; +use pingora::apps::{HttpPersistentSettings, HttpServerApp, ReusedHttpStream}; +use pingora::http::ResponseHeader; use pingora::protocols::http::ServerSession; +use pingora::server::ShutdownWatch; use crate::acme::Challenges; use crate::logging::{AccessRecord, now_secs, truncate_ip}; @@ -32,7 +35,44 @@ fn empty(status: StatusCode) -> Response> { } #[async_trait] -impl ServeHttp for HttpApp { +impl HttpServerApp for HttpApp { + /// Like Pingora's `ServeHttp` driver, but a request Pingora refuses to parse (for example + /// an absolute-form target whose authority differs from Host) gets a 400 instead of a + /// silently closed connection, as on the HTTPS listener. + async fn process_new_http( + self: &Arc, + mut http: ServerSession, + shutdown: &ShutdownWatch, + ) -> Option { + match http.read_request().await { + Ok(true) => {} + Ok(false) => return None, + Err(e) => { + if matches!(e.etype(), ErrorType::InvalidHTTPHeader) { + log::debug!(target: "ianitor::http", "bad request: {e}"); + let _ = http.respond_error(400).await; + } + return None; + } + } + http.set_keepalive(if *shutdown.borrow() { None } else { Some(60) }); + let (parts, body) = self.response(&mut http).await.into_parts(); + let header: ResponseHeader = parts.into(); + if http.write_response_header(Box::new(header)).await.is_err() { + return None; + } + if !body.is_empty() && http.write_response_body(body.into(), true).await.is_err() { + return None; + } + let settings = HttpPersistentSettings::for_session(&http); + match http.finish().await { + Ok(c) => c.map(|s| ReusedHttpStream::from_reusable_stream(s, settings)), + Err(_) => None, + } + } +} + +impl HttpApp { async fn response(&self, session: &mut ServerSession) -> Response> { let start = Instant::now(); let req = session.req_header(); diff --git a/crates/edge/src/proxy.rs b/crates/edge/src/proxy.rs index 9016b7f..a2d666d 100644 --- a/crates/edge/src/proxy.rs +++ b/crates/edge/src/proxy.rs @@ -30,18 +30,27 @@ pub struct EdgeProxy { pub struct Ctx { host: Option>, + /// Chosen upstream and its resolved addresses; connect failures move to the next address. + upstream: Option, + addrs: Vec, + addr_idx: usize, /// The Host header as the client sent it (with port, if any). host_header: String, start: Instant, } -/// Host header (HTTP/1) or :authority (HTTP/2). +/// The request's host: the authority of an absolute-form target (or HTTP/2 :authority) wins +/// over the Host header, as RFC 9112 §3.2.2 requires and Go/Caddy do. pub fn host_header(req: &RequestHeader) -> String { - req.headers - .get(header::HOST) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned) - .or_else(|| req.uri.authority().map(|a| a.as_str().to_owned())) + req.uri + .authority() + .map(|a| a.as_str().to_owned()) + .or_else(|| { + req.headers + .get(header::HOST) + .and_then(|v| v.to_str().ok()) + .map(str::to_owned) + }) .unwrap_or_default() } @@ -89,11 +98,13 @@ fn apply( Ok(()) } -fn is_websocket_upgrade(req: &RequestHeader) -> bool { - req.headers - .get(header::UPGRADE) - .and_then(|v| v.to_str().ok()) - .is_some_and(|v| v.trim().eq_ignore_ascii_case("websocket")) +/// Any `Upgrade` field, any comma-separated token, equal to `websocket` (case-insensitive). +pub fn is_websocket_upgrade(req: &RequestHeader) -> bool { + req.headers.get_all(header::UPGRADE).iter().any(|v| { + String::from_utf8_lossy(v.as_bytes()) + .split(',') + .any(|t| t.trim().eq_ignore_ascii_case("websocket")) + }) } #[async_trait] @@ -103,6 +114,9 @@ impl ProxyHttp for EdgeProxy { fn new_ctx(&self) -> Ctx { Ctx { host: None, + upstream: None, + addrs: Vec::new(), + addr_idx: 0, host_header: String::new(), start: Instant::now(), } @@ -120,6 +134,11 @@ impl ProxyHttp for EdgeProxy { let fa = self.rt.forward_auth.as_ref().ok_or_else(|| { Error::explain(ErrorType::HTTPStatus(500), "forward-auth is not configured") })?; + // Client-sent identity headers never survive, whatever copy_headers says. + let req = session.req_header_mut(); + for name in &fa.strip_headers { + req.remove_header(name); + } let ip = client_ip(session).map(|i| i.to_string()); let outcome = match forward_auth::check( &self.connector, @@ -171,27 +190,60 @@ impl ProxyHttp for EdgeProxy { async fn upstream_peer(&self, _session: &mut Session, ctx: &mut Ctx) -> Result> { let host = ctx .host - .as_ref() + .clone() .ok_or_else(|| Error::explain(ErrorType::HTTPStatus(500), "no host"))?; - let n = host.upstreams.len(); - let first = host.next.fetch_add(1, Ordering::Relaxed); - let chosen = (0..n) - .map(|i| &host.upstreams[(first + i) % n]) - .find(|u| u.healthy.load(Ordering::Relaxed)) - .ok_or_else(|| Error::explain(ErrorType::HTTPStatus(503), "no healthy upstream"))?; - log::debug!(target: "ianitor::proxy", "{}: upstream {}", host.cfg.hostname, chosen.authority); - Ok(Box::new(fetch::peer(chosen))) + let idx = match ctx.upstream { + // A retry after a failed connect: same upstream, next address. + Some(i) => i, + None => { + let n = host.upstreams.len(); + let first = host.next.fetch_add(1, Ordering::Relaxed); + let i = (0..n) + .map(|k| (first + k) % n) + .find(|&k| host.upstreams[k].healthy.load(Ordering::Relaxed)) + .ok_or_else(|| { + Error::explain(ErrorType::HTTPStatus(503), "no healthy upstream") + })?; + let up = &host.upstreams[i]; + ctx.addrs = match up.resolve().await { + Ok(a) => a, + Err(e) => { + log::warn!(target: "ianitor::proxy", "{}: cannot resolve upstream {}: {e}", host.cfg.hostname, up.authority); + return Err(Error::explain( + ErrorType::HTTPStatus(502), + "upstream does not resolve", + )); + } + }; + ctx.upstream = Some(i); + ctx.addr_idx = 0; + i + } + }; + let up = &host.upstreams[idx]; + let addr = *ctx + .addrs + .get(ctx.addr_idx) + .ok_or_else(|| Error::explain(ErrorType::HTTPStatus(502), "no address left"))?; + log::debug!(target: "ianitor::proxy", "{}: upstream {} at {addr}", host.cfg.hostname, up.authority); + Ok(Box::new(fetch::peer(addr, up))) } fn fail_to_connect( &self, _s: &mut Session, _p: &HttpPeer, - _c: &mut Ctx, + ctx: &mut Ctx, mut e: Box, ) -> Box { - // Like Caddy's default (no lb_try_duration): one attempt, then 502. - e.set_retry(false); + // Like Caddy's dialer: try every address of the chosen upstream, then 502. Other + // upstreams are not tried (Caddy's default has no lb_try_duration). + if ctx.addr_idx + 1 < ctx.addrs.len() { + ctx.addr_idx += 1; + e.set_retry(true); + } else { + e.set_retry(false); + } e } @@ -201,6 +253,19 @@ impl ProxyHttp for EdgeProxy { req: &mut RequestHeader, ctx: &mut Ctx, ) -> Result<()> { + // Origin-form target and the routed host, also for absolute-form requests. + if req.uri.authority().is_some() { + let pq = req + .uri + .path_and_query() + .map_or("/", |p| p.as_str()) + .to_owned(); + let uri = pq + .parse::() + .map_err(|_| Error::explain(ErrorType::HTTPStatus(400), "bad request target"))?; + req.set_uri(uri); + } + req.insert_header(header::HOST, ctx.host_header.as_str())?; // Forwarding headers are always edge's own; client-supplied values are replaced. match client_ip(session) { Some(ip) => req.insert_header("X-Forwarded-For", ip.to_string())?, diff --git a/crates/edge/src/runtime.rs b/crates/edge/src/runtime.rs index 5661836..0c0f904 100644 --- a/crates/edge/src/runtime.rs +++ b/crates/edge/src/runtime.rs @@ -6,7 +6,7 @@ //! parsed header names, secrets loaded, certificates loaded. Built once at startup. use std::collections::{BTreeSet, HashMap}; -use std::net::{SocketAddr, ToSocketAddrs}; +use std::net::SocketAddr; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize}; @@ -27,7 +27,9 @@ pub enum Op { } pub struct UpstreamRt { - pub addr: SocketAddr, + /// Host name or IP literal (IPv6 without brackets). + pub host: String, + pub port: u16, /// `host:port` as configured; the Host header of health checks. pub authority: String, pub tls: bool, @@ -49,6 +51,8 @@ pub struct ForwardAuthRt { pub upstream: UpstreamRt, pub path_and_query: String, pub copy_headers: Vec, + /// Removed from every client request on a forward-auth host before anything else. + pub strip_headers: Vec, } pub struct Runtime { @@ -97,19 +101,25 @@ pub fn read_config(path: &Path) -> Result { } fn upstream(u: &EdgeUpstream) -> Result { - let err = |reason: String| EdgeError::Upstream { + let err = |reason: &str| EdgeError::Upstream { address: u.address.clone(), - reason, + reason: reason.to_owned(), }; - // Resolved once at startup; Pingora peers need a socket address. - let addr = u + let (host, port) = u .address - .to_socket_addrs() - .map_err(|e| err(format!("cannot resolve: {e}")))? - .next() - .ok_or_else(|| err("resolves to no address".into()))?; + .rsplit_once(':') + .ok_or_else(|| err("expected host:port"))?; + let port: u16 = port.parse().map_err(|_| err("bad port"))?; + let host = host + .strip_prefix('[') + .and_then(|h| h.strip_suffix(']')) + .unwrap_or(host); + if host.is_empty() { + return Err(err("empty host")); + } Ok(UpstreamRt { - addr, + host: host.to_owned(), + port, authority: u.address.clone(), tls: u.tls, sni: u.sni.clone(), @@ -117,6 +127,26 @@ fn upstream(u: &EdgeUpstream) -> Result { }) } +impl UpstreamRt { + /// Addresses to try, in resolver order. Names are resolved at connect time (like Caddy's + /// dialer), so DNS changes and unresolvable names only affect requests, not startup. + pub async fn resolve(&self) -> std::io::Result> { + if let Ok(ip) = self.host.parse::() { + return Ok(vec![SocketAddr::new(ip, self.port)]); + } + let addrs: Vec = tokio::net::lookup_host((self.host.as_str(), self.port)) + .await? + .collect(); + if addrs.is_empty() { + return Err(std::io::Error::new( + std::io::ErrorKind::NotFound, + "name resolves to no address", + )); + } + Ok(addrs) + } +} + fn header_name(name: &str) -> Result { HeaderName::from_bytes(name.as_bytes()).map_err(|_| EdgeError::Header { name: name.to_owned(), @@ -225,6 +255,11 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result>()?, + strip_headers: fa + .strip_headers + .iter() + .map(|h| header_name(h)) + .collect::>()?, }), None => None, }; diff --git a/crates/edge/tests/forward_auth.rs b/crates/edge/tests/forward_auth.rs index f6bfa77..336920f 100644 --- a/crates/edge/tests/forward_auth.rs +++ b/crates/edge/tests/forward_auth.rs @@ -266,7 +266,10 @@ async fn misbehaving_auth_answers_fail_closed() { site: &site, hosts: vec![host_file( "auth.test", - &format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", echo.url()), + &format!( + "upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", + echo.url() + ), )], ..Default::default() }); @@ -275,15 +278,26 @@ async fn misbehaving_auth_answers_fail_closed() { 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 + 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"); + 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())); + 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. @@ -296,9 +310,15 @@ async fn misbehaving_auth_answers_fail_closed() { // 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"); + 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!( + t.elapsed() < std::time::Duration::from_secs(14), + "took {:?}", + t.elapsed() + ); assert!(echo.proxied().is_empty()); // Still serving afterwards. @@ -313,12 +333,18 @@ async fn remote_headers_are_stripped_even_with_a_custom_copy_list() { 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 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()), + &format!( + "upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", + echo.url() + ), )], ..Default::default() }); diff --git a/crates/edge/tests/upstreams.rs b/crates/edge/tests/upstreams.rs index 30afee2..123113e 100644 --- a/crates/edge/tests/upstreams.rs +++ b/crates/edge/tests/upstreams.rs @@ -23,15 +23,35 @@ 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"), + 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(); + 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(); + let r = client::https( + edge.https, + "gone.test", + edge.roots(), + &Req::get("gone.test", "/"), + ) + .await + .unwrap(); assert_eq!(r.status, 502); } @@ -52,14 +72,35 @@ async fn health_checks_survive_informational_answers() { let edge = start(EdgeSpec { hosts: vec![host_file( "hc.test", - &format!("upstreams = [\"{}\"]\n[health_check]\npath = \"/healthz\"\ninterval_secs = 1\n", up.url()), + &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); + 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. @@ -67,37 +108,81 @@ async fn health_checks_survive_informational_answers() { 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()))], + 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"), + 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(); + 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. +/// QC nit: absolute-form request targets are answered, never dropped. Pingora refuses a target +/// whose authority differs from Host (400, on both listeners); a consistent one is routed and +/// sent upstream in origin form. #[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()))], + hosts: vec![host_file( + "plain.test", + &format!( + "upstreams = [\"{}\"] +", + 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")) + let r = client::http(edge.http, &Req::get("plain.test", "http://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_eq!(r.status, 400, "plain HTTP, Host differs from the target"); + let r = client::https( + edge.https, + "plain.test", + edge.roots(), + &Req::get("plain.test", "https://evil.test/x"), + ) + .await + .unwrap(); + assert_eq!(r.status, 400, "HTTPS, Host differs from the target"); assert!(echo.proxied().is_empty()); + + let r = client::http(edge.http, &Req::get("plain.test", "http://plain.test/x?y")) + .await + .unwrap(); + assert_eq!(r.status, 308); + assert_eq!( + r.header("location"), + Some(format!("https://plain.test:{}/x?y", edge.https.port()).as_str()) + ); + let r = client::https( + edge.https, + "plain.test", + edge.roots(), + &Req::get("plain.test", "https://plain.test/abs?q=1"), + ) + .await + .unwrap(); + assert_eq!(r.status, 200); + assert!(r.text().contains("\"path\":\"/abs\""), "{}", r.text()); } diff --git a/tests/support/src/authelia.rs b/tests/support/src/authelia.rs index e453d78..90ac385 100644 --- a/tests/support/src/authelia.rs +++ b/tests/support/src/authelia.rs @@ -40,14 +40,18 @@ pub struct MockAuthelia { } fn h(req: &Recorded, name: &str) -> Option { - req.header(name).map(|v| String::from_utf8_lossy(v).into_owned()) + req.header(name) + .map(|v| String::from_utf8_lossy(v).into_owned()) } fn text(status: u16, reason: &str, body: &str) -> Vec { response( status, reason, - &[("Content-Type", "text/plain; charset=utf-8"), ("X-Sent-Content-Type", "text/plain; charset=utf-8")], + &[ + ("Content-Type", "text/plain; charset=utf-8"), + ("X-Sent-Content-Type", "text/plain; charset=utf-8"), + ], body.as_bytes(), ) } @@ -64,9 +68,12 @@ 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 { + 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") { @@ -76,13 +83,20 @@ fn decide(req: &Recorded) -> Reply { response( 401, "Unauthorized", - &[("WWW-Authenticate", "Basic realm=\"Authorization Required\""), ("X-Sent-Content-Type", "none")], + &[ + ("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(""); + 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), @@ -126,7 +140,10 @@ fn decide(req: &Recorded) -> Reply { impl MockAuthelia { pub async fn start() -> MockAuthelia { let server = RawServer::start(decide).await; - MockAuthelia { addr: server.addr, server } + MockAuthelia { + addr: server.addr, + server, + } } /// The `[forward_auth] url` for the site file. diff --git a/tests/support/src/raw.rs b/tests/support/src/raw.rs index 89fdb36..2b47172 100644 --- a/tests/support/src/raw.rs +++ b/tests/support/src/raw.rs @@ -27,7 +27,10 @@ pub fn response(status: u16, reason: &str, headers: &[(&str, &str)], body: &[u8] 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())); + 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 @@ -44,12 +47,17 @@ pub struct RawServer { 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 server = RawServer { + addr: listener.local_addr().unwrap(), + requests: Arc::default(), + }; let handler: Arc = Arc::new(handler); let requests = server.requests.clone(); tokio::spawn(async move { loop { - let Ok((mut stream, _)) = listener.accept().await else { continue }; + let Ok((mut stream, _)) = listener.accept().await else { + continue; + }; let handler = handler.clone(); let requests = requests.clone(); tokio::spawn(async move { @@ -97,5 +105,10 @@ fn parse(buf: &[u8]) -> Option { .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() }) + Some(Recorded { + method, + path, + headers, + body: Vec::new(), + }) }