[tests] Testkit: test CA, echo and websocket upstreams, mock Authelia, clients
This commit is contained in:
Generated
+2700
-13
File diff suppressed because it is too large
Load Diff
+16
-1
@@ -1,6 +1,6 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/core", "crates/edge", "crates/control", "tests/diff"]
|
||||
members = ["crates/core", "crates/edge", "crates/control", "tests/diff", "tests/support"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
@@ -12,11 +12,26 @@ publish = false
|
||||
[workspace.dependencies]
|
||||
ianitor-core = { path = "crates/core" }
|
||||
ianitor-edge = { path = "crates/edge" }
|
||||
ianitor-testkit = { path = "tests/support" }
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = "1.0.145"
|
||||
toml = "1.2.1"
|
||||
thiserror = "2.0.17"
|
||||
url = "2.5.7"
|
||||
tokio = { version = "1.48", features = ["full"] }
|
||||
bytes = "1.10"
|
||||
http = "1.3"
|
||||
log = "0.4.28"
|
||||
async-trait = "0.1.89"
|
||||
rustls = { version = "0.23.31", default-features = false, features = ["ring", "std", "tls12", "logging"] }
|
||||
rustls-pki-types = "1.12"
|
||||
tokio-rustls = { version = "0.26.4", default-features = false, features = ["ring", "tls12", "logging"] }
|
||||
hyper = { version = "1.7", features = ["http1", "client", "server"] }
|
||||
hyper-util = { version = "0.1.17", features = ["tokio"] }
|
||||
http-body-util = "0.1.3"
|
||||
rcgen = { version = "0.14.5", default-features = false, features = ["ring", "pem", "crypto"] }
|
||||
tokio-tungstenite = "0.29.0"
|
||||
futures-util = { version = "0.3.31", default-features = false, features = ["sink", "std"] }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "ianitor-testkit"
|
||||
description = "Shared test fixtures: test CA, upstreams, a mock Authelia, TLS/websocket clients, process helpers."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
tokio.workspace = true
|
||||
bytes.workspace = true
|
||||
http.workspace = true
|
||||
hyper.workspace = true
|
||||
hyper-util.workspace = true
|
||||
http-body-util.workspace = true
|
||||
rustls.workspace = true
|
||||
rustls-pki-types.workspace = true
|
||||
tokio-rustls.workspace = true
|
||||
rcgen.workspace = true
|
||||
tokio-tungstenite.workspace = true
|
||||
futures-util.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
[lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
@@ -0,0 +1,157 @@
|
||||
// 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 mock of Authelia's ForwardAuth endpoint (`GET /api/authz/forward-auth`), following
|
||||
//! Authelia's proxy-authorization guide: the proxy must send X-Forwarded-Method, -Proto, -Host
|
||||
//! and -URI; a 2xx answer allows the request and carries Remote-User, Remote-Groups,
|
||||
//! Remote-Email and Remote-Name; anything else is returned to the client as is.
|
||||
//!
|
||||
//! 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
|
||||
//! - otherwise GET/HEAD → 302 to the portal with `rd`, other methods → 401
|
||||
|
||||
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::upstream::Recorded;
|
||||
|
||||
pub const PATH: &str = "/api/authz/forward-auth";
|
||||
pub const PORTAL: &str = "https://auth.test/";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct MockAuthelia {
|
||||
pub addr: SocketAddr,
|
||||
requests: Arc<Mutex<Vec<Recorded>>>,
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
/// The `[forward_auth] url` for the site file.
|
||||
pub fn url(&self) -> String {
|
||||
format!("http://{}{PATH}", self.addr)
|
||||
}
|
||||
|
||||
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"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn percent(s: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for b in s.bytes() {
|
||||
if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
|
||||
out.push(char::from(b));
|
||||
} else {
|
||||
out.push_str(&format!("%{b:02X}"));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
// 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/.
|
||||
|
||||
//! Minimal HTTP/1.1 clients (plain, TLS with SNI, websocket) that send exactly the headers
|
||||
//! they are given, so both engines see byte-identical requests.
|
||||
|
||||
use std::io;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use http_body_util::{BodyExt, Full};
|
||||
use hyper_util::rt::TokioIo;
|
||||
use rustls::RootCertStore;
|
||||
use rustls_pki_types::ServerName;
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio_rustls::TlsConnector;
|
||||
use tokio_tungstenite::tungstenite;
|
||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Req {
|
||||
pub method: String,
|
||||
pub path: String,
|
||||
/// Sent in this order; include `host` yourself.
|
||||
pub headers: Vec<(String, String)>,
|
||||
pub body: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Req {
|
||||
pub fn get(host: &str, path: &str) -> Req {
|
||||
Req::new("GET", host, path)
|
||||
}
|
||||
|
||||
pub fn new(method: &str, host: &str, path: &str) -> Req {
|
||||
Req { method: method.into(), path: path.into(), headers: vec![("host".into(), host.into())], body: Vec::new() }
|
||||
}
|
||||
|
||||
pub fn header(mut self, name: &str, value: &str) -> Req {
|
||||
self.headers.push((name.into(), value.into()));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn body(mut self, body: &[u8]) -> Req {
|
||||
self.body = body.to_vec();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Resp {
|
||||
pub status: u16,
|
||||
/// Lowercase names, in received order.
|
||||
pub headers: Vec<(String, String)>,
|
||||
pub body: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Resp {
|
||||
pub fn header(&self, name: &str) -> Option<&str> {
|
||||
self.headers.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
pub fn header_all(&self, name: &str) -> Vec<&str> {
|
||||
self.headers.iter().filter(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str()).collect()
|
||||
}
|
||||
|
||||
pub fn text(&self) -> String {
|
||||
String::from_utf8_lossy(&self.body).into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
fn other(e: impl std::fmt::Display) -> io::Error {
|
||||
io::Error::other(e.to_string())
|
||||
}
|
||||
|
||||
pub fn tls_connector(roots: Arc<RootCertStore>) -> TlsConnector {
|
||||
crate::tls::install_crypto();
|
||||
let mut cfg = rustls::ClientConfig::builder().with_root_certificates(roots).with_no_client_auth();
|
||||
cfg.alpn_protocols = vec![b"http/1.1".to_vec()];
|
||||
TlsConnector::from(Arc::new(cfg))
|
||||
}
|
||||
|
||||
async fn tls_stream(
|
||||
addr: SocketAddr,
|
||||
sni: &str,
|
||||
roots: Arc<RootCertStore>,
|
||||
) -> io::Result<tokio_rustls::client::TlsStream<TcpStream>> {
|
||||
let tcp = TcpStream::connect(addr).await?;
|
||||
let name = ServerName::try_from(sni.to_owned()).map_err(other)?;
|
||||
tls_connector(roots).connect(name, tcp).await
|
||||
}
|
||||
|
||||
async fn send<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(io: S, req: &Req) -> io::Result<Resp> {
|
||||
let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(io)).await.map_err(other)?;
|
||||
tokio::spawn(async move {
|
||||
let _ = conn.await;
|
||||
});
|
||||
let mut b = hyper::Request::builder().method(req.method.as_str()).uri(req.path.as_str());
|
||||
for (n, v) in &req.headers {
|
||||
b = b.header(n.as_str(), v.as_str());
|
||||
}
|
||||
let request = b.body(Full::new(Bytes::from(req.body.clone()))).map_err(other)?;
|
||||
let resp = sender.send_request(request).await.map_err(other)?;
|
||||
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();
|
||||
let body = resp.into_body().collect().await.map_err(other)?.to_bytes().to_vec();
|
||||
Ok(Resp { status, headers, body })
|
||||
}
|
||||
|
||||
/// One request over a fresh TLS connection to `addr` with the given SNI.
|
||||
pub async fn https(addr: SocketAddr, sni: &str, roots: Arc<RootCertStore>, req: &Req) -> io::Result<Resp> {
|
||||
tokio::time::timeout(TIMEOUT, async {
|
||||
let s = tls_stream(addr, sni, roots).await?;
|
||||
send(s, req).await
|
||||
})
|
||||
.await
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
|
||||
}
|
||||
|
||||
/// One request over a fresh plain TCP connection.
|
||||
pub async fn http(addr: SocketAddr, req: &Req) -> io::Result<Resp> {
|
||||
tokio::time::timeout(TIMEOUT, async {
|
||||
let s = TcpStream::connect(addr).await?;
|
||||
send(s, req).await
|
||||
})
|
||||
.await
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum WsOutcome {
|
||||
/// 101, the echoed message.
|
||||
Upgraded { status: u16, echo: String },
|
||||
/// The upgrade was answered with a normal HTTP response.
|
||||
Refused(Resp),
|
||||
}
|
||||
|
||||
/// Open a websocket over TLS, send `message`, return the echo (or the refusal).
|
||||
pub async fn websocket(
|
||||
addr: SocketAddr,
|
||||
sni: &str,
|
||||
roots: Arc<RootCertStore>,
|
||||
host: &str,
|
||||
path: &str,
|
||||
extra: &[(&str, &str)],
|
||||
message: &str,
|
||||
) -> io::Result<WsOutcome> {
|
||||
tokio::time::timeout(TIMEOUT, async {
|
||||
let s = tls_stream(addr, sni, roots).await?;
|
||||
let mut request = format!("wss://{host}{path}").into_client_request().map_err(other)?;
|
||||
for (n, v) in extra {
|
||||
request.headers_mut().insert(
|
||||
http::HeaderName::from_bytes(n.as_bytes()).map_err(other)?,
|
||||
http::HeaderValue::from_str(v).map_err(other)?,
|
||||
);
|
||||
}
|
||||
match tokio_tungstenite::client_async(request, s).await {
|
||||
Ok((mut ws, resp)) => {
|
||||
let status = resp.status().as_u16();
|
||||
ws.send(tungstenite::Message::text(message)).await.map_err(other)?;
|
||||
let echo = match ws.next().await {
|
||||
Some(Ok(m)) => m.into_text().map_err(other)?.to_string(),
|
||||
other_msg => return Err(other(format!("no echo: {other_msg:?}"))),
|
||||
};
|
||||
let _ = ws.close(None).await;
|
||||
Ok(WsOutcome::Upgraded { status, echo })
|
||||
}
|
||||
Err(tungstenite::Error::Http(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();
|
||||
let body = resp.body().clone().unwrap_or_default();
|
||||
Ok(WsOutcome::Refused(Resp { status, headers, body }))
|
||||
}
|
||||
Err(e) => Err(other(e)),
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "websocket timed out"))?
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// 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 fixtures shared by the edge integration tests and the differential harness.
|
||||
//! Everything listens on 127.0.0.1 only. This is test code: panics are failures.
|
||||
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
pub mod authelia;
|
||||
pub mod client;
|
||||
pub mod proc;
|
||||
pub mod tls;
|
||||
pub mod upstream;
|
||||
|
||||
/// FNV-1a 64-bit, used to compare bodies and secret values without echoing them.
|
||||
pub fn fnv64(data: &[u8]) -> String {
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for b in data {
|
||||
h ^= u64::from(*b);
|
||||
h = h.wrapping_mul(0x0100_0000_01b3);
|
||||
}
|
||||
format!("{h:016x}")
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
// 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/.
|
||||
|
||||
//! Ports, temporary directories, external binaries and child processes.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Child;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// A port on 127.0.0.1 that was free a moment ago.
|
||||
pub fn free_port() -> u16 {
|
||||
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
|
||||
}
|
||||
|
||||
pub fn local(port: u16) -> SocketAddr {
|
||||
SocketAddr::from(([127, 0, 0, 1], port))
|
||||
}
|
||||
|
||||
/// Wait until something accepts TCP connections on `addr`.
|
||||
pub fn wait_for_port(addr: SocketAddr, timeout: Duration) -> bool {
|
||||
let deadline = Instant::now() + timeout;
|
||||
while Instant::now() < deadline {
|
||||
if std::net::TcpStream::connect_timeout(&addr, Duration::from_millis(200)).is_ok() {
|
||||
return true;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// A directory removed on drop (kept when `IANITOR_KEEP_TMP` is set, for debugging).
|
||||
pub struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
pub fn new(label: &str) -> TempDir {
|
||||
static N: AtomicU32 = AtomicU32::new(0);
|
||||
let p = std::env::temp_dir().join(format!(
|
||||
"ianitor-{label}-{}-{}",
|
||||
std::process::id(),
|
||||
N.fetch_add(1, Ordering::SeqCst)
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&p);
|
||||
std::fs::create_dir_all(&p).unwrap();
|
||||
TempDir(p)
|
||||
}
|
||||
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
|
||||
pub fn join(&self, p: &str) -> PathBuf {
|
||||
self.0.join(p)
|
||||
}
|
||||
|
||||
pub fn str(&self, p: &str) -> String {
|
||||
self.join(p).to_string_lossy().into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
if std::env::var_os("IANITOR_KEEP_TMP").is_none() {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Locate an external tool: `$IANITOR_<NAME>_BIN`, then `$PATH`.
|
||||
pub fn find_binary(name: &str) -> Option<PathBuf> {
|
||||
let var = format!("IANITOR_{}_BIN", name.to_ascii_uppercase().replace('-', "_"));
|
||||
if let Some(p) = std::env::var_os(&var) {
|
||||
return Some(PathBuf::from(p));
|
||||
}
|
||||
let path = std::env::var_os("PATH")?;
|
||||
std::env::split_paths(&path).map(|d| d.join(name)).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// Like [`find_binary`], but a missing tool fails the test, unless `IANITOR_ALLOW_SKIP=1`,
|
||||
/// in which case the test prints SKIPPED and the caller returns early.
|
||||
pub fn require_binary(name: &str) -> Option<PathBuf> {
|
||||
match find_binary(name) {
|
||||
Some(p) => Some(p),
|
||||
None if std::env::var("IANITOR_ALLOW_SKIP").as_deref() == Ok("1") => {
|
||||
eprintln!("SKIPPED: `{name}` not found (IANITOR_ALLOW_SKIP=1)");
|
||||
None
|
||||
}
|
||||
None => panic!(
|
||||
"`{name}` is needed for this test but was not found on PATH (or ${}). \
|
||||
In WSL: nix profile add nixpkgs#{name}. Set IANITOR_ALLOW_SKIP=1 to skip instead.",
|
||||
format!("IANITOR_{}_BIN", name.to_ascii_uppercase().replace('-', "_"))
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Kills the child on drop.
|
||||
pub struct ChildGuard(pub Child);
|
||||
|
||||
impl Drop for ChildGuard {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// 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 throw-away test CA (stands in for the Domi CA, which arrives in phase 3).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use rcgen::{
|
||||
BasicConstraints, CertificateParams, DistinguishedName, DnType, ExtendedKeyUsagePurpose, IsCa,
|
||||
Issuer, KeyPair, KeyUsagePurpose,
|
||||
};
|
||||
use rustls::RootCertStore;
|
||||
use rustls_pki_types::CertificateDer;
|
||||
use rustls_pki_types::pem::PemObject;
|
||||
|
||||
pub struct TestCa {
|
||||
pub cert_pem: String,
|
||||
issuer: Issuer<'static, KeyPair>,
|
||||
}
|
||||
|
||||
pub struct Leaf {
|
||||
pub cert_pem: String,
|
||||
pub key_pem: String,
|
||||
}
|
||||
|
||||
impl TestCa {
|
||||
pub fn new(common_name: &str) -> Self {
|
||||
let key = KeyPair::generate().unwrap();
|
||||
let mut params = CertificateParams::new(Vec::<String>::new()).unwrap();
|
||||
let mut dn = DistinguishedName::new();
|
||||
dn.push(DnType::CommonName, common_name);
|
||||
params.distinguished_name = dn;
|
||||
params.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
|
||||
params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign, KeyUsagePurpose::DigitalSignature];
|
||||
let cert = params.self_signed(&key).unwrap();
|
||||
TestCa { cert_pem: cert.pem(), issuer: Issuer::new(params, key) }
|
||||
}
|
||||
|
||||
/// A server certificate for the given DNS names (or IP literals).
|
||||
pub fn issue(&self, names: &[&str]) -> Leaf {
|
||||
let key = KeyPair::generate().unwrap();
|
||||
let mut params = CertificateParams::new(names.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>()).unwrap();
|
||||
let mut dn = DistinguishedName::new();
|
||||
dn.push(DnType::CommonName, names.first().copied().unwrap_or("test"));
|
||||
params.distinguished_name = dn;
|
||||
params.is_ca = IsCa::NoCa;
|
||||
params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth];
|
||||
params.key_usages = vec![KeyUsagePurpose::DigitalSignature];
|
||||
let cert = params.signed_by(&key, &self.issuer).unwrap();
|
||||
Leaf { cert_pem: cert.pem(), key_pem: key.serialize_pem() }
|
||||
}
|
||||
|
||||
pub fn roots(&self) -> Arc<RootCertStore> {
|
||||
roots_from_pem(&self.cert_pem)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn roots_from_pem(pem: &str) -> Arc<RootCertStore> {
|
||||
let mut roots = RootCertStore::empty();
|
||||
for c in CertificateDer::pem_slice_iter(pem.as_bytes()) {
|
||||
roots.add(c.unwrap()).unwrap();
|
||||
}
|
||||
Arc::new(roots)
|
||||
}
|
||||
|
||||
/// rustls needs a process-wide crypto provider; install ring once.
|
||||
pub fn install_crypto() {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
// 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<u8>)>,
|
||||
pub body: Vec<u8>,
|
||||
}
|
||||
|
||||
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<Mutex<Vec<Recorded>>>,
|
||||
/// Status answered on `/healthz`.
|
||||
pub health: Arc<AtomicU16>,
|
||||
}
|
||||
|
||||
type Body = BoxBody<Bytes, Infallible>;
|
||||
|
||||
fn full(b: impl Into<Bytes>) -> 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<Recorded> {
|
||||
self.requests.lock().unwrap().clone()
|
||||
}
|
||||
|
||||
/// Requests other than health checks.
|
||||
pub fn proxied(&self) -> Vec<Recorded> {
|
||||
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<Incoming>) -> Response<Body> {
|
||||
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::<u16>().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<AtomicUsize>,
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
Reference in New Issue
Block a user