Files
ianitor/tests/support/src/client.rs
T

504 lines
16 KiB
Rust

// 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,
headers: Vec<(String, String)>,
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();
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))
.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,
headers,
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"))?
}
/// A client identity for mTLS: a PEM chain (leaf first) and its PEM private key.
#[derive(Debug, Clone)]
pub struct ClientCert {
pub chain_pem: String,
pub key_pem: String,
/// Offer only TLS 1.2 (client certificates take a different path there).
pub tls12_only: bool,
}
/// One request over a fresh TLS connection that presents `cert` if the server asks for one.
pub async fn https_with_cert(
addr: SocketAddr,
sni: &str,
roots: Arc<RootCertStore>,
cert: &ClientCert,
req: &Req,
) -> io::Result<Resp> {
use rustls_pki_types::pem::PemObject;
use rustls_pki_types::{CertificateDer, PrivateKeyDer};
crate::tls::install_crypto();
let chain: Vec<CertificateDer<'static>> =
CertificateDer::pem_slice_iter(cert.chain_pem.as_bytes())
.collect::<Result<_, _>>()
.map_err(other)?;
let key = PrivateKeyDer::from_pem_slice(cert.key_pem.as_bytes()).map_err(other)?;
let versions: &[&rustls::SupportedProtocolVersion] = if cert.tls12_only {
&[&rustls::version::TLS12]
} else {
rustls::DEFAULT_VERSIONS
};
let mut cfg = rustls::ClientConfig::builder_with_protocol_versions(versions)
.with_root_certificates(roots)
.with_client_auth_cert(chain, key)
.map_err(other)?;
cfg.alpn_protocols = vec![b"http/1.1".to_vec()];
let connector = TlsConnector::from(Arc::new(cfg));
tokio::time::timeout(TIMEOUT, async {
let tcp = TcpStream::connect(addr).await?;
let name = ServerName::try_from(sni.to_owned()).map_err(other)?;
let s = connector.connect(name, tcp).await?;
send(s, req).await
})
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
}
// ------------------------------------------------------------------ pipelining
/// The request as bytes: request line, the headers as given, `content-length` for a body.
pub fn encode(req: &Req) -> Vec<u8> {
let mut out = format!("{} {} HTTP/1.1\r\n", req.method, req.path).into_bytes();
for (n, v) in &req.headers {
out.extend_from_slice(format!("{n}: {v}\r\n").as_bytes());
}
if !req.body.is_empty() {
out.extend_from_slice(format!("content-length: {}\r\n", req.body.len()).as_bytes());
}
out.extend_from_slice(b"\r\n");
out.extend_from_slice(&req.body);
out
}
fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
hay.windows(needle.len()).position(|w| w == needle)
}
/// Parse one response from the front of `buf` (`head`: the request was a HEAD). `Ok(None)`:
/// not complete yet; with `eof`, a body without a length ends at the end of the data.
fn parse_one(buf: &[u8], head: bool, eof: bool) -> io::Result<Option<(Resp, usize)>> {
let Some(end) = find(buf, b"\r\n\r\n") else {
return Ok(None);
};
let text = String::from_utf8_lossy(&buf[..end]).into_owned();
let mut lines = text.split("\r\n");
let status_line = lines.next().unwrap_or_default();
let status: u16 = status_line
.split(' ')
.nth(1)
.and_then(|s| s.parse().ok())
.ok_or_else(|| other(format!("bad status line: {status_line}")))?;
let headers: Vec<(String, String)> = lines
.filter_map(|l| l.split_once(':'))
.map(|(n, v)| (n.trim().to_ascii_lowercase(), v.trim().to_owned()))
.collect();
let get = |n: &str| headers.iter().find(|(k, _)| k == n).map(|(_, v)| v.clone());
let start = end + 4;
let no_body = head || status < 200 || status == 204 || status == 304;
let (body, used) = if no_body {
(Vec::new(), start)
} else if get("transfer-encoding").is_some_and(|t| t.eq_ignore_ascii_case("chunked")) {
let mut at = start;
let mut body = Vec::new();
loop {
let Some(nl) = find(&buf[at..], b"\r\n") else {
return Ok(None);
};
let size_text = String::from_utf8_lossy(&buf[at..at + nl]).into_owned();
let size = usize::from_str_radix(size_text.split(';').next().unwrap_or("").trim(), 16)
.map_err(|_| other(format!("bad chunk size: {size_text}")))?;
at += nl + 2;
if size == 0 {
// No trailers expected: the empty line ends the message.
if buf.len() < at + 2 {
return Ok(None);
}
at += 2;
break;
}
if buf.len() < at + size + 2 {
return Ok(None);
}
body.extend_from_slice(&buf[at..at + size]);
at += size + 2;
}
(body, at)
} else if let Some(len) = get("content-length") {
let len: usize = len
.parse()
.map_err(|_| other(format!("bad content-length: {len}")))?;
if buf.len() < start + len {
return Ok(None);
}
(buf[start..start + len].to_vec(), start + len)
} else if eof {
(buf[start..].to_vec(), buf.len())
} else {
return Ok(None);
};
Ok(Some((
Resp {
status,
headers,
body,
},
used,
)))
}
/// Send every request back to back in one write on one connection (HTTP/1.1 pipelining), then
/// read the answers in order until the server closes or `idle` passes without data. Interim
/// (1xx) answers are skipped.
pub async fn pipelined_on<S: AsyncRead + AsyncWrite + Unpin>(
mut io: S,
reqs: &[Req],
idle: Duration,
) -> io::Result<Vec<Resp>> {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let mut all = Vec::new();
for r in reqs {
all.extend(encode(r));
}
io.write_all(&all).await?;
io.flush().await?;
let mut buf = Vec::new();
let mut out = Vec::new();
let mut chunk = [0u8; 16 * 1024];
let mut eof = false;
while out.len() < reqs.len() {
let head = reqs[out.len()].method.eq_ignore_ascii_case("HEAD");
if let Some((resp, used)) = parse_one(&buf, head, eof)? {
buf.drain(..used);
if resp.status >= 200 {
out.push(resp);
}
continue;
}
if eof {
break;
}
match tokio::time::timeout(idle, io.read(&mut chunk)).await {
Ok(Ok(0)) | Ok(Err(_)) => eof = true,
Ok(Ok(n)) => buf.extend_from_slice(&chunk[..n]),
Err(_) => break,
}
}
Ok(out)
}
/// [`pipelined_on`] over a fresh plain TCP connection.
pub async fn http_pipelined(addr: SocketAddr, reqs: &[Req]) -> io::Result<Vec<Resp>> {
let s = TcpStream::connect(addr).await?;
pipelined_on(s, reqs, Duration::from_secs(3)).await
}
/// [`pipelined_on`] over a fresh TLS connection with the given SNI.
pub async fn https_pipelined(
addr: SocketAddr,
sni: &str,
roots: Arc<RootCertStore>,
reqs: &[Req],
) -> io::Result<Vec<Resp>> {
let s = tls_stream(addr, sni, roots).await?;
pipelined_on(s, reqs, Duration::from_secs(3)).await
}
#[cfg(test)]
mod pipeline_tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn responses_are_split_by_length_and_chunks() {
let raw = b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\nhiHTTP/1.1 404 Not Found\r\n\
transfer-encoding: chunked\r\n\r\n3\r\nabc\r\n0\r\n\r\nHTTP/1.1 308 x\r\n\
location: /\r\ncontent-length: 0\r\n\r\n";
let (a, used) = parse_one(raw, false, false).unwrap().unwrap();
assert_eq!((a.status, a.text().as_str()), (200, "hi"));
let rest = &raw[used..];
let (b, used2) = parse_one(rest, false, false).unwrap().unwrap();
assert_eq!((b.status, b.text().as_str()), (404, "abc"));
let (c, _) = parse_one(&rest[used2..], false, false).unwrap().unwrap();
assert_eq!(c.status, 308);
assert!(
parse_one(
b"HTTP/1.1 200 OK\r\ncontent-length: 5\r\n\r\nab",
false,
false
)
.unwrap()
.is_none()
);
}
}
/// One request over a fresh connection to a Unix socket (edge's proxy socket, control's UI
/// socket).
#[cfg(unix)]
pub async fn unix(path: &std::path::Path, req: &Req) -> io::Result<Resp> {
tokio::time::timeout(TIMEOUT, async {
let s = tokio::net::UnixStream::connect(path).await?;
send(s, req).await
})
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
}