use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::{Arc, OnceLock};
use std::time::Duration;
use reqwest::{Method, StatusCode};
use serde::Serialize;
use serde::de::DeserializeOwned;
#[derive(Debug, thiserror::Error)]
pub enum HttpError {
#[error("http request failed: {0}")]
Request(#[from] reqwest::Error),
#[error("invalid request: {0}")]
Invalid(String),
#[error("blocked: {0} is not a public address")]
Blocked(String),
#[error("invalid json response: {0}")]
Json(#[from] serde_json::Error),
}
pub struct Http;
impl Http {
pub fn get(url: &str) -> PendingRequest {
PendingRequest::new(Method::GET, url)
}
pub fn post(url: &str) -> PendingRequest {
PendingRequest::new(Method::POST, url)
}
pub fn put(url: &str) -> PendingRequest {
PendingRequest::new(Method::PUT, url)
}
pub fn patch(url: &str) -> PendingRequest {
PendingRequest::new(Method::PATCH, url)
}
pub fn delete(url: &str) -> PendingRequest {
PendingRequest::new(Method::DELETE, url)
}
}
enum Body {
None,
Json(serde_json::Value),
Form(serde_json::Value),
}
pub struct PendingRequest {
method: Method,
url: String,
headers: Vec<(String, String)>,
body: Body,
bearer: Option<String>,
timeout: Option<Duration>,
attempts: u32,
delay: Duration,
err: Option<String>,
redirects: bool,
public_only: bool,
}
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
impl PendingRequest {
fn new(method: Method, url: &str) -> Self {
Self {
method,
url: url.into(),
headers: Vec::new(),
body: Body::None,
bearer: None,
timeout: Some(DEFAULT_TIMEOUT),
attempts: 1,
delay: Duration::ZERO,
err: None,
redirects: false,
public_only: false,
}
}
pub fn follow_redirects(mut self) -> Self {
self.redirects = true;
self
}
pub fn public_only(mut self) -> Self {
self.public_only = true;
self
}
pub fn bearer_token(mut self, token: &str) -> Self {
self.bearer = Some(token.into());
self
}
pub fn with_header(mut self, name: &str, value: &str) -> Self {
self.headers.push((name.into(), value.into()));
self
}
pub fn json<T: Serialize>(mut self, body: &T) -> Self {
match serde_json::to_value(body) {
Ok(v) => self.body = Body::Json(v),
Err(e) => self.err = Some(e.to_string()),
}
self
}
pub fn form<T: Serialize>(mut self, body: &T) -> Self {
match serde_json::to_value(body) {
Ok(v) => self.body = Body::Form(v),
Err(e) => self.err = Some(e.to_string()),
}
self
}
pub fn timeout(mut self, d: Duration) -> Self {
self.timeout = Some(d);
self
}
pub fn retry(mut self, times: u32, delay: Duration) -> Self {
self.attempts = times.max(1);
self.delay = delay;
self
}
pub async fn send(self) -> Result<Response, HttpError> {
if let Some(e) = self.err {
return Err(HttpError::Invalid(e));
}
if self.public_only {
check_literal(&self.url)?;
}
let client = client(self.redirects, self.public_only);
let mut attempt = 1;
loop {
let mut rb = client.request(self.method.clone(), &self.url);
for (k, v) in &self.headers {
rb = rb.header(k, v);
}
if let Some(t) = &self.bearer {
rb = rb.bearer_auth(t);
}
if let Some(t) = self.timeout {
rb = rb.timeout(t);
}
rb = match &self.body {
Body::None => rb,
Body::Json(v) => rb.json(v),
Body::Form(v) => rb
.header("content-type", "application/x-www-form-urlencoded")
.body(urlencode(v)),
};
let last = attempt >= self.attempts;
match rb.send().await {
Ok(res) if res.status().is_server_error() && !last => {}
Ok(res) => {
let status = res.status();
let headers = res.headers().clone();
let body = res.bytes().await?.to_vec();
return Ok(Response {
status,
headers,
body,
});
}
Err(e) if e.is_connect() && !last => {}
Err(e) => return Err(e.into()),
}
attempt += 1;
tokio::time::sleep(self.delay).await;
}
}
}
fn client(redirects: bool, public_only: bool) -> &'static reqwest::Client {
static CLIENTS: [OnceLock<reqwest::Client>; 4] = [
OnceLock::new(),
OnceLock::new(),
OnceLock::new(),
OnceLock::new(),
];
CLIENTS[redirects as usize * 2 + public_only as usize].get_or_init(|| {
let mut b = reqwest::Client::builder().redirect(if redirects {
reqwest::redirect::Policy::custom(|a| {
let same = a.previous().last().is_some_and(|p| {
p.scheme() == a.url().scheme()
&& p.host_str() == a.url().host_str()
&& p.port_or_known_default() == a.url().port_or_known_default()
});
if a.previous().len() >= 5 || !same {
a.stop()
} else {
a.follow()
}
})
} else {
reqwest::redirect::Policy::none()
});
if public_only {
b = b.no_proxy().dns_resolver(Arc::new(PublicOnly));
}
b.build().expect("http client")
})
}
struct PublicOnly;
impl reqwest::dns::Resolve for PublicOnly {
fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
Box::pin(async move {
let host = name.as_str().to_string();
let all = tokio::net::lookup_host((host.as_str(), 0)).await?;
let public: Vec<SocketAddr> = all.filter(|a| is_public(a.ip())).collect();
if public.is_empty() {
return Err(format!("{host} resolves only to internal addresses").into());
}
Ok(Box::new(public.into_iter()) as reqwest::dns::Addrs)
})
}
}
fn check_literal(url: &str) -> Result<(), HttpError> {
let u = reqwest::Url::parse(url).map_err(|e| HttpError::Invalid(e.to_string()))?;
let ip = u.host_str().and_then(|h| {
h.trim_matches(|c| c == '[' || c == ']')
.parse::<IpAddr>()
.ok()
});
match ip {
Some(ip) if !is_public(ip) => Err(HttpError::Blocked(ip.to_string())),
_ => Ok(()),
}
}
pub fn is_public(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(a) => public_v4(a),
IpAddr::V6(a) => public_v6(a),
}
}
fn public_v4(a: Ipv4Addr) -> bool {
let o = a.octets();
!(a.is_unspecified()
|| a.is_loopback()
|| a.is_private()
|| a.is_link_local()
|| a.is_broadcast()
|| a.is_multicast()
|| a.is_documentation()
|| o[0] == 0 || (o[0] == 100 && (64..128).contains(&o[1])) || (o[0] == 198 && (o[1] == 18 || o[1] == 19)) || o[0] >= 240) }
fn public_v6(a: Ipv6Addr) -> bool {
if let Some(v4) = a.to_ipv4_mapped() {
return public_v4(v4);
}
let s = a.segments();
if s[0] == 0x64 && s[1] == 0xff9b && s[2..6] == [0; 4] {
return public_v4(Ipv4Addr::new(
(s[6] >> 8) as u8,
s[6] as u8,
(s[7] >> 8) as u8,
s[7] as u8,
));
}
if s[0] == 0x2002 {
return public_v4(Ipv4Addr::new(
(s[1] >> 8) as u8,
s[1] as u8,
(s[2] >> 8) as u8,
s[2] as u8,
));
}
!(a.is_unspecified()
|| a.is_loopback()
|| a.is_multicast()
|| (s[0] & 0xfe00) == 0xfc00 || (s[0] & 0xffc0) == 0xfe80 || (s[0] == 0x2001 && s[1] == 0x0db8)) }
#[derive(Debug, Clone)]
pub struct Response {
status: StatusCode,
headers: reqwest::header::HeaderMap,
body: Vec<u8>,
}
impl Response {
pub fn status(&self) -> StatusCode {
self.status
}
pub fn ok(&self) -> bool {
self.status == StatusCode::OK
}
pub fn successful(&self) -> bool {
self.status.is_success()
}
pub fn failed(&self) -> bool {
self.status.is_client_error() || self.status.is_server_error()
}
pub fn header(&self, name: &str) -> Option<&str> {
self.headers.get(name)?.to_str().ok()
}
pub fn bytes(&self) -> &[u8] {
&self.body
}
pub fn text(&self) -> String {
String::from_utf8_lossy(&self.body).into_owned()
}
pub fn json<T: DeserializeOwned>(&self) -> Result<T, HttpError> {
Ok(serde_json::from_slice(&self.body)?)
}
}
fn urlencode(v: &serde_json::Value) -> String {
fn enc(s: &str) -> String {
let mut o = String::new();
for b in s.bytes() {
match b {
b' ' => o.push('+'),
b if b.is_ascii_alphanumeric() || b"-._~".contains(&b) => o.push(b as char),
b => o.push_str(&format!("%{b:02X}")),
}
}
o
}
let Some(map) = v.as_object() else {
return String::new();
};
map.iter()
.filter(|(_, v)| !v.is_null())
.map(|(k, v)| {
let val = v
.as_str()
.map(str::to_owned)
.unwrap_or_else(|| v.to_string());
format!("{}={}", enc(k), enc(&val))
})
.collect::<Vec<_>>()
.join("&")
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{
Json, Router,
http::HeaderMap,
routing::{get, post},
};
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
async fn serve(app: Router) -> String {
let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = l.local_addr().unwrap();
tokio::spawn(async move { axum::serve(l, app).await.unwrap() });
format!("http://{addr}")
}
#[tokio::test]
async fn verbs_headers_json_form() {
let app = Router::new()
.route(
"/echo",
post(
|h: HeaderMap, Json(b): Json<serde_json::Value>| async move {
Json(serde_json::json!({
"auth": h["authorization"].to_str().unwrap(),
"x": h["x-test"].to_str().unwrap(),
"body": b,
}))
},
)
.get(|| async { "plain" })
.delete(|| async { axum::http::StatusCode::NOT_FOUND }),
)
.route("/form", post(|body: String| async move { body }));
let base = serve(app).await;
let r = Http::post(&format!("{base}/echo"))
.bearer_token("tok")
.with_header("x-test", "1")
.json(&serde_json::json!({"a": 1}))
.send()
.await
.unwrap();
assert!(r.ok() && r.successful() && !r.failed());
let v: serde_json::Value = r.json().unwrap();
assert_eq!(v["auth"], "Bearer tok");
assert_eq!(v["x"], "1");
assert_eq!(v["body"]["a"], 1);
let r = Http::get(&format!("{base}/echo")).send().await.unwrap();
assert_eq!(r.text(), "plain");
let r = Http::delete(&format!("{base}/echo")).send().await.unwrap();
assert!(r.failed() && !r.successful() && r.status() == 404);
let r = Http::post(&format!("{base}/form"))
.form(&serde_json::json!({"k": "a b"}))
.send()
.await
.unwrap();
assert_eq!(r.text(), "k=a+b");
}
#[tokio::test]
async fn retries_5xx_but_not_4xx() {
let n = Arc::new(AtomicU32::new(0));
let (n1, n2) = (n.clone(), n.clone());
let app = Router::new()
.route(
"/flaky",
get(move || {
let n = n1.clone();
async move {
if n.fetch_add(1, Ordering::SeqCst) < 2 {
axum::http::StatusCode::BAD_GATEWAY
} else {
axum::http::StatusCode::OK
}
}
}),
)
.route(
"/bad",
get(move || {
let n = n2.clone();
async move {
n.fetch_add(100, Ordering::SeqCst);
axum::http::StatusCode::BAD_REQUEST
}
}),
);
let base = serve(app).await;
let r = Http::get(&format!("{base}/flaky"))
.retry(3, Duration::from_millis(1))
.send()
.await
.unwrap();
assert!(r.ok());
assert_eq!(n.load(Ordering::SeqCst), 3);
n.store(0, Ordering::SeqCst);
let r = Http::get(&format!("{base}/bad"))
.retry(3, Duration::from_millis(1))
.send()
.await
.unwrap();
assert_eq!(r.status(), 400);
assert_eq!(n.load(Ordering::SeqCst), 100);
n.store(0, Ordering::SeqCst);
let r = Http::get(&format!("{base}/flaky"))
.retry(2, Duration::ZERO)
.send()
.await
.unwrap();
assert_eq!(r.status(), 502);
}
#[test]
fn requests_have_a_default_timeout() {
assert_eq!(DEFAULT_TIMEOUT, Duration::from_secs(30));
assert_eq!(
PendingRequest::new(Method::GET, "http://x.test").timeout,
Some(DEFAULT_TIMEOUT)
);
assert_eq!(
PendingRequest::new(Method::GET, "http://x.test")
.timeout(Duration::from_secs(2))
.timeout,
Some(Duration::from_secs(2))
);
}
#[tokio::test]
async fn connect_error_is_error_after_retries_and_timeout_applies() {
let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = l.local_addr().unwrap();
drop(l);
let e = Http::get(&format!("http://{addr}/"))
.retry(2, Duration::from_millis(1))
.send()
.await;
assert!(matches!(e, Err(HttpError::Request(_))));
let base = serve(Router::new().route(
"/slow",
get(|| async {
tokio::time::sleep(Duration::from_secs(5)).await;
}),
))
.await;
let e = Http::get(&format!("{base}/slow"))
.timeout(Duration::from_millis(50))
.send()
.await;
assert!(matches!(e, Err(HttpError::Request(ref e)) if e.is_timeout()));
}
#[test]
fn internal_addresses_are_not_public() {
for ip in [
"127.0.0.1",
"10.1.2.3",
"172.16.0.1",
"192.168.1.1",
"169.254.169.254",
"0.0.0.0",
"100.64.0.1",
"255.255.255.255",
"224.0.0.1",
"::1",
"::",
"fe80::1",
"fc00::1",
"fd12::1",
"::ffff:127.0.0.1",
"::ffff:10.0.0.1",
"64:ff9b::7f00:1",
"2002:7f00:1::1",
"ff02::1",
] {
assert!(!is_public(ip.parse().unwrap()), "{ip} must be blocked");
}
for ip in [
"8.8.8.8",
"93.184.216.34",
"2606:4700:4700::1111",
"::ffff:8.8.8.8",
] {
assert!(is_public(ip.parse().unwrap()), "{ip} must be allowed");
}
}
#[tokio::test]
async fn public_only_blocks_every_spelling_of_an_internal_address() {
for url in [
"http://127.0.0.1:1/",
"http://2130706433:1/",
"http://0x7f.1:1/",
"http://0177.0.0.1:1/",
"http://127.1:1/",
"http://[::ffff:127.0.0.1]:1/",
"http://user@127.0.0.1:1/",
"http://169.254.169.254/latest/meta-data/",
"http://[::1]:1/",
] {
let r = Http::get(url).public_only().send().await;
assert!(matches!(r, Err(HttpError::Blocked(_))), "{url}: {r:?}");
}
let base = serve(Router::new().route("/", get(|| async { "internal" }))).await;
let port = base.rsplit(':').next().unwrap();
let r = Http::get(&format!("http://localhost:{port}/"))
.public_only()
.send()
.await;
assert!(matches!(r, Err(HttpError::Request(_))), "{r:?}");
assert_eq!(
Http::get(&format!("{base}/")).send().await.unwrap().text(),
"internal"
);
}
#[tokio::test]
async fn redirects_are_not_followed_unless_asked_and_never_across_origins() {
let secret = serve(Router::new().route(
"/x",
get(|h: HeaderMap| async move { format!("{:?}", h.get("x-api-key")) }),
))
.await;
let to = format!("{secret}/x");
let hop = Router::new()
.route(
"/other",
get(move || {
let to = to.clone();
async move { axum::response::Redirect::temporary(&to) }
}),
)
.route(
"/a",
get(|| async { axum::response::Redirect::temporary("/b") }),
)
.route("/b", get(|| async { "landed" }));
let base = serve(hop).await;
let r = Http::get(&format!("{base}/other"))
.with_header("x-api-key", "K")
.send()
.await
.unwrap();
assert_eq!(
r.status(),
307,
"default: the redirect is returned, not followed"
);
let r = Http::get(&format!("{base}/other"))
.with_header("x-api-key", "K")
.follow_redirects()
.send()
.await
.unwrap();
assert_eq!(
r.status(),
307,
"another origin (port) is never followed, so the header never leaves"
);
let r = Http::get(&format!("{base}/a")).send().await.unwrap();
assert_eq!(r.status(), 307);
let r = Http::get(&format!("{base}/a"))
.follow_redirects()
.send()
.await
.unwrap();
assert_eq!(r.text(), "landed", "same origin is followed");
}
}