use std::collections::HashMap;
use std::time::Duration;
use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper_util::rt::TokioIo;
use indexmap::IndexMap;
use reqwest::header::HeaderValue;
use reqwest::{header::HeaderMap, redirect::Policy, Client, Method};
use serde::{Deserialize, Serialize};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::TcpStream;
use tokio::time::timeout;
use crate::error::{NoctisError, Result};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpResult {
pub status: u16,
pub headers: HashMap<String, String>,
pub body: String,
pub duration_ms: u64,
pub url: String,
}
pub struct HttpCheck {
client: Client,
follow_redirects: bool,
tls_insecure: bool,
timeout: Duration,
}
const MAX_REDIRECTS: usize = 10;
impl HttpCheck {
pub fn new(follow_redirects: bool, tls_insecure: bool, timeout_secs: u64) -> Result<Self> {
let redirect = if follow_redirects {
Policy::limited(10)
} else {
Policy::none()
};
let client = Client::builder()
.redirect(redirect)
.timeout(Duration::from_secs(timeout_secs))
.danger_accept_invalid_certs(tls_insecure)
.build()
.map_err(NoctisError::Http)?;
Ok(Self {
client,
follow_redirects,
tls_insecure,
timeout: Duration::from_secs(timeout_secs),
})
}
pub async fn run(
&self,
method: &str,
url: &str,
headers: &IndexMap<String, String>,
body: Option<&str>,
) -> Result<HttpResult> {
let method = Method::from_bytes(method.as_bytes()).map_err(|_| NoctisError::StepError {
test: String::new(),
step: String::new(),
message: format!("invalid HTTP method: {method}"),
})?;
let mut req = self.client.request(method.clone(), url);
let mut header_map = HeaderMap::new();
for (k, v) in headers {
if let (Ok(name), Ok(value)) = (
reqwest::header::HeaderName::from_bytes(k.as_bytes()),
reqwest::header::HeaderValue::from_str(v),
) {
header_map.insert(name, value);
}
}
req = req.headers(header_map);
if let Some(b) = body {
req = req.body(b.to_string());
}
let start = std::time::Instant::now();
let resp = match req.send().await {
Ok(r) => r,
Err(e)
if e.is_connect()
&& !e.is_timeout()
&& self.tls_insecure
&& url.starts_with("https://") =>
{
match self.run_legacy(method, url, headers, body).await {
Ok(r) => return Ok(r),
Err(le) => {
tracing::debug!("legacy TLS retry failed: {le}");
return Err(NoctisError::Http(e));
}
}
}
Err(e) => return Err(NoctisError::Http(e)),
};
let status = resp.status().as_u16();
let url_final = resp.url().to_string();
let mut resp_headers = HashMap::new();
for (k, v) in resp.headers() {
resp_headers.insert(k.to_string(), v.to_str().unwrap_or("<binary>").to_string());
}
let body = resp.text().await.map_err(NoctisError::Http)?;
let duration_ms = start.elapsed().as_millis() as u64;
Ok(HttpResult {
status,
headers: resp_headers,
body,
duration_ms,
url: url_final,
})
}
}
impl HttpCheck {
async fn run_legacy(
&self,
method: Method,
url: &str,
headers: &IndexMap<String, String>,
body: Option<&str>,
) -> std::result::Result<HttpResult, String> {
let start = std::time::Instant::now();
let exchange = async {
let mut url = reqwest::Url::parse(url).map_err(|e| e.to_string())?;
let mut method = method;
let mut body = body.map(|b| b.to_string());
let mut headers = headers.clone();
let mut hops = 0;
loop {
let resp = legacy_send(&method, &url, &headers, body.as_deref()).await?;
let status = resp.status().as_u16();
let next = match resp.headers().get(hyper::header::LOCATION) {
Some(loc)
if self.follow_redirects
&& matches!(status, 301 | 302 | 303 | 307 | 308) =>
{
loc.to_str().ok().and_then(|l| url.join(l).ok())
}
_ => None,
};
let Some(next) = next else {
return Ok::<_, String>((resp, url));
};
hops += 1;
if hops > MAX_REDIRECTS {
return Err("too many redirects".to_string());
}
if (status == 303 && method != Method::HEAD)
|| (matches!(status, 301 | 302) && method == Method::POST)
{
method = Method::GET;
body = None;
headers.retain(|k, _| {
![
"content-type",
"content-length",
"content-encoding",
"transfer-encoding",
]
.iter()
.any(|h| k.eq_ignore_ascii_case(h))
});
}
if next.scheme() != url.scheme()
|| next.host_str() != url.host_str()
|| next.port_or_known_default() != url.port_or_known_default()
{
headers.retain(|k, _| {
![
"authorization",
"cookie",
"cookie2",
"proxy-authorization",
"www-authenticate",
]
.iter()
.any(|h| k.eq_ignore_ascii_case(h))
});
}
url = next;
}
};
let (resp, final_url) = timeout(self.timeout, exchange)
.await
.map_err(|_| "timed out".to_string())??;
let status = resp.status().as_u16();
let mut resp_headers = HashMap::new();
for (k, v) in resp.headers() {
resp_headers.insert(k.to_string(), v.to_str().unwrap_or("<binary>").to_string());
}
let remaining = self.timeout.saturating_sub(start.elapsed());
let bytes = timeout(remaining, resp.into_body().collect())
.await
.map_err(|_| "timed out reading the body".to_string())?
.map_err(|e| e.to_string())?
.to_bytes();
let duration_ms = start.elapsed().as_millis() as u64;
Ok(HttpResult {
status,
headers: resp_headers,
body: String::from_utf8_lossy(&bytes).into_owned(),
duration_ms,
url: final_url.to_string(),
})
}
}
trait LegacyIo: AsyncRead + AsyncWrite + Unpin + Send {}
impl<T: AsyncRead + AsyncWrite + Unpin + Send> LegacyIo for T {}
async fn legacy_send(
method: &Method,
url: &reqwest::Url,
headers: &IndexMap<String, String>,
body: Option<&str>,
) -> std::result::Result<hyper::Response<hyper::body::Incoming>, String> {
let host = url.host_str().ok_or("URL without host")?;
let port = url.port_or_known_default().ok_or("URL without port")?;
let bare = host.trim_start_matches('[').trim_end_matches(']');
let tcp = TcpStream::connect((bare, port))
.await
.map_err(|e| format!("connect: {e}"))?;
let io: Box<dyn LegacyIo> = match url.scheme() {
"https" => Box::new(super::legacy_tls::legacy_handshake(tcp, bare).await?),
"http" => Box::new(tcp),
other => return Err(format!("unsupported scheme {other}")),
};
let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(io))
.await
.map_err(|e| e.to_string())?;
tokio::spawn(async move {
let _ = conn.await;
});
let target = match url.query() {
Some(q) => format!("{}?{q}", url.path()),
None => url.path().to_string(),
};
let mut req = hyper::Request::builder()
.method(method.as_str())
.uri(target);
let h = req.headers_mut().ok_or("bad request")?;
let host_value = match url.port() {
Some(p) => format!("{host}:{p}"),
None => host.to_string(),
};
if let Ok(v) = HeaderValue::from_str(&host_value) {
h.insert(hyper::header::HOST, v);
}
h.insert(hyper::header::ACCEPT, HeaderValue::from_static("*/*"));
for (k, v) in headers {
if let (Ok(name), Ok(value)) = (
reqwest::header::HeaderName::from_bytes(k.as_bytes()),
HeaderValue::from_str(v),
) {
h.insert(name, value);
}
}
let req = req
.body(Full::new(Bytes::from(body.unwrap_or("").to_string())))
.map_err(|e| e.to_string())?;
sender.send_request(req).await.map_err(|e| e.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
#[tokio::test]
async fn duration_covers_streamed_body() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
let (mut sock, _) = listener.accept().await.unwrap();
let mut buf = [0u8; 1024];
let _ = sock.read(&mut buf).await;
sock.write_all(
b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n5\r\nhello\r\n",
)
.await
.unwrap();
sock.flush().await.unwrap();
tokio::time::sleep(Duration::from_millis(800)).await;
sock.write_all(b"6\r\n world\r\n0\r\n\r\n").await.unwrap();
sock.flush().await.unwrap();
});
let check = HttpCheck::new(false, true, 10).unwrap();
let res = check
.run("GET", &format!("http://{addr}/"), &IndexMap::new(), None)
.await
.unwrap();
assert_eq!(res.status, 200);
assert_eq!(res.body, "hello world");
assert!(
res.duration_ms >= 700,
"duration_ms {} stops before the delayed body chunk",
res.duration_ms
);
}
use crate::checks::legacy_tls::test_server::{spawn, Mode};
#[tokio::test]
async fn legacy_tls_server_is_queried() {
for mode in [Mode::RsaKex, Mode::Tls10] {
let port = spawn(mode).await;
let check = HttpCheck::new(true, true, 10).unwrap();
let mut headers = IndexMap::new();
headers.insert("X-Probe".to_string(), "1".to_string());
let res = check
.run(
"GET",
&format!("https://127.0.0.1:{port}/a?b=c"),
&headers,
None,
)
.await
.unwrap();
assert_eq!(res.status, 200);
assert_eq!(
res.body,
format!("legacy-ok GET /a?b=c HTTP/1.1\nhost=127.0.0.1:{port}")
);
assert_eq!(res.headers.get("x-legacy").map(String::as_str), Some("yes"));
}
}
#[tokio::test]
async fn legacy_tls_redirects_are_followed() {
let port = spawn(Mode::RsaKex).await;
let check = HttpCheck::new(true, true, 10).unwrap();
let res = check
.run(
"GET",
&format!("https://127.0.0.1:{port}/redirect"),
&IndexMap::new(),
None,
)
.await
.unwrap();
assert_eq!(res.status, 200);
assert!(
res.body.starts_with("legacy-ok GET /final "),
"{}",
res.body
);
assert_eq!(res.url, format!("https://127.0.0.1:{port}/final"));
let check = HttpCheck::new(false, true, 10).unwrap();
let res = check
.run(
"GET",
&format!("https://127.0.0.1:{port}/redirect"),
&IndexMap::new(),
None,
)
.await
.unwrap();
assert_eq!(res.status, 302);
}
#[tokio::test]
async fn legacy_retry_needs_tls_insecure() {
let port = spawn(Mode::RsaKex).await;
let check = HttpCheck::new(true, false, 10).unwrap();
let res = check
.run(
"GET",
&format!("https://127.0.0.1:{port}/"),
&IndexMap::new(),
None,
)
.await;
assert!(res.is_err());
}
#[tokio::test]
async fn legacy_post_carries_the_body() {
let port = spawn(Mode::RsaKex).await;
let check = HttpCheck::new(true, true, 10).unwrap();
let res = check
.run(
"POST",
&format!("https://127.0.0.1:{port}/p"),
&IndexMap::new(),
Some("x=1"),
)
.await
.unwrap();
assert!(res.body.starts_with("legacy-ok POST /p "), "{}", res.body);
}
async fn echo_server() -> u16 {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
while let Ok((mut sock, _)) = listener.accept().await {
let mut buf = vec![0u8; 4096];
let n = sock.read(&mut buf).await.unwrap_or(0);
let req = String::from_utf8_lossy(&buf[..n]).to_string();
let reply = format!(
"HTTP/1.0 200 OK\r\nContent-Length: {}\r\n\r\n{req}",
req.len()
);
let _ = sock.write_all(reply.as_bytes()).await;
}
});
port
}
#[tokio::test]
async fn legacy_redirect_to_other_origin_drops_credentials() {
let port = spawn(Mode::RsaKex).await;
let plain = echo_server().await;
let check = HttpCheck::new(true, true, 10).unwrap();
let mut headers = IndexMap::new();
headers.insert("Authorization".to_string(), "Basic c2VjcmV0".to_string());
headers.insert("Cookie".to_string(), "sid=secret".to_string());
headers.insert("Content-Type".to_string(), "text/plain".to_string());
headers.insert("X-Keep".to_string(), "1".to_string());
let res = check
.run(
"POST",
&format!("https://127.0.0.1:{port}/away?to=http://127.0.0.1:{plain}/landed"),
&headers,
Some("x=1"),
)
.await
.unwrap();
let echoed = res.body.to_ascii_lowercase();
assert!(echoed.starts_with("get /landed http/1.1"), "{echoed}");
assert!(echoed.contains("x-keep: 1"), "{echoed}");
for gone in ["authorization", "cookie", "content-type", "x=1"] {
assert!(!echoed.contains(gone), "{gone} kept: {echoed}");
}
assert_eq!(res.url, format!("http://127.0.0.1:{plain}/landed"));
}
}