// 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/. //! Test upstreams on 127.0.0.1: an HTTP echo server and a websocket echo server. use std::convert::Infallible; use std::net::SocketAddr; use std::sync::atomic::{AtomicU16, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use bytes::Bytes; use futures_util::{SinkExt, StreamExt}; use http_body_util::{BodyExt, Full, StreamBody, combinators::BoxBody}; use hyper::body::{Frame, 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::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] = [ "host", "x-forwarded-for", "x-forwarded-proto", "x-forwarded-host", "x-static", "x-remove-me", "x-client", "remote-user", "remote-groups", "remote-email", "remote-name", "x-debug", ]; pub const HASHED_HEADERS: [&str; 2] = ["x-api-key", "authorization"]; #[derive(Debug, Clone)] pub struct Recorded { pub method: String, pub path: String, pub headers: Vec<(String, Vec)>, pub body: Vec, } impl Recorded { pub fn header(&self, name: &str) -> Option<&[u8]> { self.headers .iter() .find(|(n, _)| n.eq_ignore_ascii_case(name)) .map(|(_, v)| v.as_slice()) } } #[derive(Clone)] pub struct Echo { pub addr: SocketAddr, pub name: String, requests: Arc>>, /// Status answered on `/healthz`. pub health: Arc, } type Body = BoxBody; fn full(b: impl Into) -> Body { Full::new(b.into()).boxed() } impl Echo { pub async fn start(name: &str) -> Echo { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let echo = Echo { addr: listener.local_addr().unwrap(), name: name.to_owned(), requests: Arc::default(), health: Arc::new(AtomicU16::new(200)), }; let e = echo.clone(); tokio::spawn(async move { loop { let Ok((stream, _)) = listener.accept().await else { continue; }; let e = e.clone(); tokio::spawn(async move { let svc = service_fn(move |req| { let e = e.clone(); async move { Ok::<_, Infallible>(e.handle(req).await) } }); let _ = http1::Builder::new() .serve_connection(TokioIo::new(stream), svc) .await; }); } }); echo } pub fn url(&self) -> String { format!("http://{}", self.addr) } pub fn requests(&self) -> Vec { self.requests.lock().unwrap().clone() } /// Requests other than health checks. pub fn proxied(&self) -> Vec { self.requests() .into_iter() .filter(|r| r.path != "/healthz") .collect() } pub fn clear(&self) { self.requests.lock().unwrap().clear(); } async fn handle(&self, req: Request) -> Response { let (parts, body) = req.into_parts(); let body = body .collect() .await .map(|b| b.to_bytes()) .unwrap_or_default(); let path = parts.uri.path().to_owned(); let query = parts.uri.query().unwrap_or("").to_owned(); self.requests.lock().unwrap().push(Recorded { method: parts.method.to_string(), path: path.clone(), headers: parts .headers .iter() .map(|(n, v)| (n.as_str().to_owned(), v.as_bytes().to_vec())) .collect(), body: body.to_vec(), }); let base = |status: u16| { Response::builder() .status(status) .header("x-powered-by", "echo") .header("x-upstream", self.name.clone()) }; if path == "/healthz" { let s = self.health.load(Ordering::SeqCst); return base(s).body(full(format!("health {s}"))).unwrap(); } if let Some(code) = path .strip_prefix("/status/") .and_then(|c| c.parse::().ok()) { return base(code) .header("content-type", "text/plain") .body(full(format!("status {code}"))) .unwrap(); } if path == "/big" { let n: usize = query .strip_prefix("n=") .and_then(|n| n.parse().ok()) .unwrap_or(1024) .min(10 << 20); return base(200) .header("content-type", "application/octet-stream") .body(full(vec![b'x'; n])) .unwrap(); } if path == "/chunked" { let chunks = ["first,", "second,", "third"] .into_iter() .map(|c| Ok::<_, Infallible>(Frame::data(Bytes::from_static(c.as_bytes())))); let stream = futures_util::stream::iter(chunks); return base(200) .header("content-type", "text/plain") .body(BodyExt::boxed(StreamBody::new(stream))) .unwrap(); } if path == "/set-cookie" { return base(200) .header("set-cookie", "a=1; Path=/; HttpOnly") .header("set-cookie", "b=2; Path=/; Secure") .body(full("cookies")) .unwrap(); } if path == "/reflect" { // Copies one request header into the response: simulates an upstream that leaks. let name = query.strip_prefix("h=").unwrap_or("x-api-key"); let mut b = base(200); if let Some(v) = parts.headers.get(name) { b = b.header("x-reflected", v.clone()); } return b.body(full("reflected")).unwrap(); } let mut headers = serde_json::Map::new(); for h in ECHO_HEADERS { if let Some(v) = parts.headers.get(h) { headers.insert( h.to_owned(), String::from_utf8_lossy(v.as_bytes()).into_owned().into(), ); } } for h in HASHED_HEADERS { if let Some(v) = parts.headers.get(h) { headers.insert(format!("{h}#fnv"), fnv64(v.as_bytes()).into()); } } let json = serde_json::json!({ "upstream": self.name, "method": parts.method.as_str(), "path": path, "query": query, "body_len": body.len(), "body_fnv": fnv64(&body), "headers": headers, }); base(200) .header("content-type", "application/json") .body(full(json.to_string())) .unwrap() } } /// Websocket echo upstream: answers the upgrade, then echoes every text/binary message. #[derive(Clone)] pub struct WsEcho { pub addr: SocketAddr, connections: Arc, } impl WsEcho { pub async fn start() -> WsEcho { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let ws = WsEcho { addr: listener.local_addr().unwrap(), connections: Arc::default(), }; let conns = ws.connections.clone(); tokio::spawn(async move { loop { let Ok((stream, _)) = listener.accept().await else { continue; }; let conns = conns.clone(); tokio::spawn(async move { let Ok(mut ws) = tokio_tungstenite::accept_async(stream).await else { return; }; conns.fetch_add(1, Ordering::SeqCst); while let Some(Ok(msg)) = ws.next().await { if msg.is_text() || msg.is_binary() { if ws.send(msg).await.is_err() { break; } } else if msg.is_close() { break; } } }); } }); ws } pub fn url(&self) -> String { format!("http://{}", self.addr) } pub fn connections(&self) -> usize { self.connections.load(Ordering::SeqCst) } } /// A port on 127.0.0.1 that nothing listens on. pub fn closed_port() -> u16 { let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); l.local_addr().unwrap().port() }