mod redirect_dns;
use redirect_dns::redirect_dns_check_blocks;
use reqwest::Client;
use std::sync::Arc;
use std::time::Duration;
const DEFAULT_TIMEOUT: u64 = 30;
const DEFAULT_POOL_MAX_IDLE_PER_HOST: usize = 10;
const DEFAULT_POOL_IDLE_TIMEOUT: u64 = 90;
pub(crate) const DEFAULT_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
const DEFAULT_MAX_REDIRECTS: u8 = 10;
const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
pub(crate) fn connect_timeout_for(total_timeout: Duration) -> Duration {
total_timeout.min(DEFAULT_CONNECT_TIMEOUT)
}
pub fn create_http_client_with_timeout(timeout_secs: u64) -> Client {
create_client(timeout_secs, DEFAULT_MAX_REDIRECTS)
}
pub fn create_http_client() -> Arc<Client> {
Arc::new(create_client(DEFAULT_TIMEOUT, DEFAULT_MAX_REDIRECTS))
}
pub fn create_http_client_with_redirects(timeout_secs: u64, max_redirects: u8) -> Client {
create_client(timeout_secs, max_redirects)
}
pub fn create_http_client_no_redirects() -> Client {
Client::builder()
.user_agent(DEFAULT_USER_AGENT)
.timeout(Duration::from_secs(DEFAULT_TIMEOUT))
.connect_timeout(connect_timeout_for(Duration::from_secs(DEFAULT_TIMEOUT)))
.pool_max_idle_per_host(DEFAULT_POOL_MAX_IDLE_PER_HOST)
.pool_idle_timeout(Duration::from_secs(DEFAULT_POOL_IDLE_TIMEOUT))
.redirect(reqwest::redirect::Policy::none())
.build()
.unwrap_or_else(|e| {
log::error!("Failed to build HTTP client (no-redirect): {}", e);
panic!("HTTP client build failed: {}", e);
})
}
fn create_client(timeout_secs: u64, max_redirects: u8) -> Client {
let redirect_policy = create_ssrf_safe_redirect_policy(max_redirects);
Client::builder()
.user_agent(DEFAULT_USER_AGENT)
.timeout(Duration::from_secs(timeout_secs))
.connect_timeout(connect_timeout_for(Duration::from_secs(timeout_secs)))
.pool_max_idle_per_host(DEFAULT_POOL_MAX_IDLE_PER_HOST)
.pool_idle_timeout(Duration::from_secs(DEFAULT_POOL_IDLE_TIMEOUT))
.redirect(redirect_policy)
.build()
.unwrap_or_else(|e| {
log::error!("Failed to build SSRF-safe HTTP client: {}", e);
panic!("SSRF-safe HTTP client build failed: {}", e);
})
}
pub fn create_ssrf_safe_redirect_policy(max_redirects: u8) -> reqwest::redirect::Policy {
if crate::infrastructure::security::ssrf::ssrf_protection_disabled() {
return reqwest::redirect::Policy::limited(max_redirects as usize);
}
use crate::infrastructure::security::ssrf::is_internal_url;
reqwest::redirect::Policy::custom(move |attempt| {
if attempt.previous().len() >= max_redirects as usize {
log::warn!(
"Redirect limit ({}) exceeded, stopping redirect chain",
max_redirects
);
return attempt.stop();
}
let redirect_url = attempt.url();
if redirect_url.scheme() != "http" && redirect_url.scheme() != "https" {
log::warn!(
"SSRF protection: Blocking redirect with non-HTTP scheme: {}",
redirect_url.scheme()
);
return attempt.stop();
}
if is_internal_url(redirect_url.as_str()) {
log::warn!(
"SSRF protection: Blocking redirect to internal URL: {}",
redirect_url
);
return attempt.stop();
}
if redirect_dns_check_blocks(redirect_url) {
return attempt.stop();
}
log::debug!(
"Following redirect {} -> {}",
attempt
.previous()
.last()
.map(|u| u.to_string())
.unwrap_or_else(|| "unknown".to_string()),
redirect_url
);
attempt.follow()
})
}
#[derive(Debug)]
pub enum BodyReadError {
LimitExceeded {
max_bytes: usize,
},
Network(reqwest::Error),
}
impl std::fmt::Display for BodyReadError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
BodyReadError::LimitExceeded { max_bytes } => {
write!(f, "response body exceeds {} byte limit", max_bytes)
}
BodyReadError::Network(e) => write!(f, "failed to read response body: {}", e),
}
}
}
impl std::error::Error for BodyReadError {}
async fn accumulate_limited<S, B>(mut stream: S, max_bytes: usize) -> Result<Vec<u8>, BodyReadError>
where
S: futures::Stream<Item = Result<B, reqwest::Error>> + Unpin,
B: AsRef<[u8]>,
{
use futures::StreamExt;
let mut buf: Vec<u8> = Vec::new();
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(BodyReadError::Network)?;
let chunk = chunk.as_ref();
if buf.len() + chunk.len() > max_bytes {
return Err(BodyReadError::LimitExceeded { max_bytes });
}
buf.extend_from_slice(chunk);
}
Ok(buf)
}
pub async fn read_body_limited(
resp: reqwest::Response,
max_bytes: usize,
) -> Result<String, BodyReadError> {
let charset = resp
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.and_then(|ct| {
ct.split(';')
.map(|part| part.trim())
.find_map(|part| part.strip_prefix("charset="))
})
.map(|s| s.trim().trim_matches('"').to_string());
if let Some(len) = resp.content_length() {
if len as usize > max_bytes {
return Err(BodyReadError::LimitExceeded { max_bytes });
}
}
let bytes = accumulate_limited(Box::pin(resp.bytes_stream()), max_bytes).await?;
let decoded = match charset.as_deref() {
Some(label) => {
let encoding =
encoding_rs::Encoding::for_label(label.as_bytes()).unwrap_or(encoding_rs::UTF_8);
let (text, _, _) = encoding.decode(&bytes);
text.into_owned()
}
None => String::from_utf8_lossy(&bytes).into_owned(),
};
Ok(decoded)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_http_client_with_timeout() {
let client = create_http_client_with_timeout(60);
let _ = client.clone();
}
#[test]
fn test_create_default_http_client() {
let client = create_http_client();
let _ = client.clone();
}
#[test]
fn test_create_http_client_no_redirects() {
let client = create_http_client_no_redirects();
let _ = client.clone();
}
#[test]
fn test_create_http_client_with_redirects() {
let client = create_http_client_with_redirects(30, 5);
let _ = client.clone();
}
#[test]
fn test_default_constants_values() {
assert_eq!(DEFAULT_TIMEOUT, 30);
assert_eq!(DEFAULT_POOL_MAX_IDLE_PER_HOST, 10);
assert_eq!(DEFAULT_POOL_IDLE_TIMEOUT, 90);
assert_eq!(DEFAULT_MAX_REDIRECTS, 10);
assert!(!DEFAULT_USER_AGENT.is_empty());
}
#[test]
fn connect_timeout_capped_at_upper_bound() {
assert_eq!(
connect_timeout_for(Duration::from_secs(30)),
Duration::from_secs(10)
);
assert_eq!(
connect_timeout_for(Duration::from_secs(60)),
Duration::from_secs(10)
);
}
#[test]
fn connect_timeout_never_exceeds_total() {
assert_eq!(
connect_timeout_for(Duration::from_secs(5)),
Duration::from_secs(5)
);
assert_eq!(connect_timeout_for(Duration::ZERO), Duration::ZERO);
}
#[test]
fn test_create_http_client_with_zero_timeout() {
let client = create_http_client_with_timeout(0);
let _ = client.clone();
}
#[test]
fn test_create_http_client_with_large_timeout() {
let client = create_http_client_with_timeout(86400);
let _ = client.clone();
}
#[test]
fn test_create_http_client_with_zero_redirects() {
let client = create_http_client_with_redirects(30, 0);
let _ = client.clone();
}
#[test]
fn test_create_http_client_with_max_redirects() {
let client = create_http_client_with_redirects(30, u8::MAX);
let _ = client.clone();
}
#[test]
fn test_create_ssrf_safe_redirect_policy_returns_policy() {
let _policy = create_ssrf_safe_redirect_policy(5);
let _policy_zero = create_ssrf_safe_redirect_policy(0);
let _policy_max = create_ssrf_safe_redirect_policy(u8::MAX);
}
#[test]
fn test_default_http_client_is_arc_wrapped() {
let client = create_http_client();
let client2 = client.clone();
assert!(std::sync::Arc::ptr_eq(&client, &client2));
}
#[test]
fn test_no_redirect_client_follows_no_redirects() {
let _client = create_http_client_no_redirects();
}
#[tokio::test]
async fn test_ssrf_safe_redirect_policy_blocks_redirect_to_internal_url() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/redirect"))
.respond_with(
ResponseTemplate::new(302)
.insert_header("Location", "http://127.0.0.1:1/destination"),
)
.mount(&mock_server)
.await;
let client = create_http_client_with_redirects(5, 10);
let url = format!("{}/redirect", mock_server.uri());
let response = client
.get(&url)
.send()
.await
.expect("request should succeed");
assert_eq!(
response.status().as_u16(),
302,
"redirect to internal URL should be blocked (302 returned, not followed)"
);
}
#[tokio::test]
async fn test_ssrf_safe_redirect_policy_zero_max_redirects() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/redirect"))
.respond_with(
ResponseTemplate::new(302)
.insert_header("Location", "http://127.0.0.1:1/destination"),
)
.mount(&mock_server)
.await;
let client = create_http_client_with_redirects(5, 0);
let url = format!("{}/redirect", mock_server.uri());
let response = client
.get(&url)
.send()
.await
.expect("request should succeed");
assert_eq!(
response.status().as_u16(),
302,
"with max_redirects=0, redirect should not be followed"
);
}
#[tokio::test]
async fn test_client_with_ssrf_policy_successful_non_redirect_request() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/normal"))
.respond_with(ResponseTemplate::new(200).set_body_string("ok"))
.mount(&mock_server)
.await;
let client = create_http_client_with_redirects(5, 10);
let url = format!("{}/normal", mock_server.uri());
let response = client
.get(&url)
.send()
.await
.expect("request should succeed");
assert_eq!(response.status().as_u16(), 200);
let body = response.text().await.expect("body should be readable");
assert_eq!(body, "ok");
}
#[tokio::test]
async fn test_ssrf_safe_redirect_policy_blocks_redirect_to_localhost() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/redirect-localhost"))
.respond_with(
ResponseTemplate::new(301)
.insert_header("Location", "http://localhost:1/destination"),
)
.mount(&mock_server)
.await;
let client = create_http_client_with_redirects(5, 10);
let url = format!("{}/redirect-localhost", mock_server.uri());
let response = client
.get(&url)
.send()
.await
.expect("request should succeed");
assert_eq!(
response.status().as_u16(),
301,
"redirect to localhost should be blocked"
);
}
#[tokio::test]
async fn test_ssrf_safe_redirect_policy_blocks_redirect_to_private_ip() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/redirect-private"))
.respond_with(
ResponseTemplate::new(302)
.insert_header("Location", "http://10.0.0.1:8080/internal"),
)
.mount(&mock_server)
.await;
let client = create_http_client_with_redirects(5, 10);
let url = format!("{}/redirect-private", mock_server.uri());
let response = client
.get(&url)
.send()
.await
.expect("request should succeed");
assert_eq!(
response.status().as_u16(),
302,
"redirect to private IP (10.0.0.1) should be blocked"
);
}
#[tokio::test]
async fn test_ssrf_safe_redirect_policy_blocks_redirect_to_172_16() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/redirect-172"))
.respond_with(
ResponseTemplate::new(301).insert_header("Location", "http://172.16.0.1:80/dest"),
)
.mount(&mock_server)
.await;
let client = create_http_client_with_redirects(5, 10);
let url = format!("{}/redirect-172", mock_server.uri());
let response = client
.get(&url)
.send()
.await
.expect("request should succeed");
assert_eq!(
response.status().as_u16(),
301,
"redirect to 172.16.0.0/12 should be blocked"
);
}
#[tokio::test]
async fn test_ssrf_safe_redirect_policy_blocks_redirect_to_192_168() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/redirect-192"))
.respond_with(
ResponseTemplate::new(302).insert_header("Location", "http://192.168.1.1:80/dest"),
)
.mount(&mock_server)
.await;
let client = create_http_client_with_redirects(5, 10);
let url = format!("{}/redirect-192", mock_server.uri());
let response = client
.get(&url)
.send()
.await
.expect("request should succeed");
assert_eq!(
response.status().as_u16(),
302,
"redirect to 192.168.0.0/16 should be blocked"
);
}
#[tokio::test]
async fn test_ssrf_safe_redirect_policy_blocks_redirect_to_ipv6_loopback() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/redirect-ipv6"))
.respond_with(
ResponseTemplate::new(302).insert_header("Location", "http://[::1]:80/dest"),
)
.mount(&mock_server)
.await;
let client = create_http_client_with_redirects(5, 10);
let url = format!("{}/redirect-ipv6", mock_server.uri());
let response = client
.get(&url)
.send()
.await
.expect("request should succeed");
assert_eq!(
response.status().as_u16(),
302,
"redirect to [::1] should be blocked"
);
}
#[tokio::test]
async fn test_ssrf_safe_redirect_policy_blocks_redirect_to_169_254() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/redirect-link-local"))
.respond_with(
ResponseTemplate::new(302)
.insert_header("Location", "http://169.254.169.254/latest/meta-data/"),
)
.mount(&mock_server)
.await;
let client = create_http_client_with_redirects(5, 10);
let url = format!("{}/redirect-link-local", mock_server.uri());
let response = client
.get(&url)
.send()
.await
.expect("request should succeed");
assert_eq!(
response.status().as_u16(),
302,
"redirect to 169.254.169.254 should be blocked"
);
}
#[tokio::test]
async fn test_ssrf_safe_redirect_policy_blocks_redirect_to_0_0_0_0() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/redirect-zero"))
.respond_with(
ResponseTemplate::new(302).insert_header("Location", "http://0.0.0.0:80/dest"),
)
.mount(&mock_server)
.await;
let client = create_http_client_with_redirects(5, 10);
let url = format!("{}/redirect-zero", mock_server.uri());
let response = client
.get(&url)
.send()
.await
.expect("request should succeed");
assert_eq!(
response.status().as_u16(),
302,
"redirect to 0.0.0.0 should be blocked"
);
}
#[tokio::test]
async fn test_ssrf_safe_redirect_policy_blocks_non_http_scheme() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/redirect-file"))
.respond_with(
ResponseTemplate::new(302).insert_header("Location", "file:///etc/passwd"),
)
.mount(&mock_server)
.await;
let client = create_http_client_with_redirects(5, 10);
let url = format!("{}/redirect-file", mock_server.uri());
let response = client
.get(&url)
.send()
.await
.expect("request should succeed");
assert_eq!(
response.status().as_u16(),
302,
"redirect to file:// scheme should be blocked"
);
}
#[tokio::test]
async fn test_no_redirect_client_returns_redirect_response() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/redirect"))
.respond_with(
ResponseTemplate::new(302).insert_header("Location", "http://127.0.0.1:1/dest"),
)
.mount(&mock_server)
.await;
let client = create_http_client_no_redirects();
let url = format!("{}/redirect", mock_server.uri());
let response = client
.get(&url)
.send()
.await
.expect("request should succeed");
assert_eq!(
response.status().as_u16(),
302,
"no-redirect client should return 302 without following"
);
}
#[tokio::test]
async fn test_client_with_ssrf_policy_handles_post_request() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/submit"))
.respond_with(ResponseTemplate::new(200).set_body_string("accepted"))
.mount(&mock_server)
.await;
let client = create_http_client_with_redirects(5, 10);
let url = format!("{}/submit", mock_server.uri());
let response = client
.post(&url)
.body("data")
.send()
.await
.expect("request should succeed");
assert_eq!(response.status().as_u16(), 200);
assert_eq!(response.text().await.unwrap(), "accepted");
}
#[tokio::test]
async fn test_client_with_ssrf_policy_follows_safe_redirect_to_mock_server() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/destination"))
.respond_with(ResponseTemplate::new(200).set_body_string("reached"))
.mount(&mock_server)
.await;
Mock::given(method("GET"))
.and(path("/redirect-to-dest"))
.respond_with(
ResponseTemplate::new(302)
.insert_header("Location", format!("{}/destination", mock_server.uri())),
)
.mount(&mock_server)
.await;
let client = create_http_client_with_redirects(5, 10);
let url = format!("{}/redirect-to-dest", mock_server.uri());
let response = client
.get(&url)
.send()
.await
.expect("request should succeed");
assert_eq!(
response.status().as_u16(),
302,
"redirect to 127.0.0.1 (mock server) should be blocked by SSRF policy"
);
}
#[test]
fn test_default_user_agent_is_chrome_like() {
assert!(DEFAULT_USER_AGENT.contains("Chrome"));
assert!(DEFAULT_USER_AGENT.contains("Mozilla"));
}
#[test]
fn test_create_ssrf_safe_redirect_policy_with_different_limits() {
for limit in [1u8, 2, 5, 10, 20, 50, 100, 200] {
let _policy = create_ssrf_safe_redirect_policy(limit);
}
}
#[test]
fn test_http_client_functions_return_usable_clients() {
let c1 = create_http_client_with_timeout(10);
let c2 = create_http_client();
let c3 = create_http_client_no_redirects();
let c4 = create_http_client_with_redirects(10, 5);
let _ = c1.clone();
let _ = c2.clone();
let _ = c3.clone();
let _ = c4.clone();
}
use crate::test_utils::ensure_debug_logger;
#[tokio::test]
async fn test_ssrf_block_logs_warning_with_logger_initialized() {
ensure_debug_logger();
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/redirect-logged"))
.respond_with(
ResponseTemplate::new(302)
.insert_header("Location", "http://127.0.0.1:1/destination"),
)
.mount(&mock_server)
.await;
let client = create_http_client_with_redirects(5, 10);
let url = format!("{}/redirect-logged", mock_server.uri());
let response = client
.get(&url)
.send()
.await
.expect("request should succeed");
assert_eq!(
response.status().as_u16(),
302,
"redirect to internal URL should be blocked (302 returned)"
);
}
#[tokio::test]
async fn test_redirect_limit_exceeded_logs_warning_with_logger() {
ensure_debug_logger();
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/redirect-limit-logged"))
.respond_with(
ResponseTemplate::new(301).insert_header("Location", "http://127.0.0.1:1/dest"),
)
.mount(&mock_server)
.await;
let client = create_http_client_with_redirects(5, 0);
let url = format!("{}/redirect-limit-logged", mock_server.uri());
let response = client
.get(&url)
.send()
.await
.expect("request should succeed");
assert_eq!(
response.status().as_u16(),
301,
"with max_redirects=0, redirect should not be followed"
);
}
#[tokio::test]
async fn test_ssrf_block_localhost_logs_warning_with_logger() {
ensure_debug_logger();
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/redirect-localhost-logged"))
.respond_with(
ResponseTemplate::new(301)
.insert_header("Location", "http://localhost:1/destination"),
)
.mount(&mock_server)
.await;
let client = create_http_client_with_redirects(5, 10);
let url = format!("{}/redirect-localhost-logged", mock_server.uri());
let response = client
.get(&url)
.send()
.await
.expect("request should succeed");
assert_eq!(response.status().as_u16(), 301);
}
#[tokio::test]
async fn test_ssrf_block_private_ip_logs_warning_with_logger() {
ensure_debug_logger();
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/redirect-private-logged"))
.respond_with(
ResponseTemplate::new(302)
.insert_header("Location", "http://10.0.0.1:8080/internal"),
)
.mount(&mock_server)
.await;
let client = create_http_client_with_redirects(5, 10);
let url = format!("{}/redirect-private-logged", mock_server.uri());
let response = client
.get(&url)
.send()
.await
.expect("request should succeed");
assert_eq!(response.status().as_u16(), 302);
}
#[tokio::test]
async fn test_ssrf_safe_redirect_policy_follows_external_redirect() {
ensure_debug_logger();
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/redirect-external-follow"))
.respond_with(
ResponseTemplate::new(302)
.insert_header("Location", "http://192.0.2.1:1/destination"),
)
.mount(&mock_server)
.await;
let client = create_http_client_with_redirects(2, 10);
let url = format!("{}/redirect-external-follow", mock_server.uri());
let result = client.get(&url).send().await;
assert!(
result.is_err(),
"redirect to unreachable external URL should fail after attempt.follow()"
);
}
#[tokio::test]
async fn test_read_body_limited_within_limit() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/small"))
.respond_with(ResponseTemplate::new(200).set_body_string("hello world"))
.mount(&mock_server)
.await;
let client = create_http_client_with_redirects(5, 10);
let resp = client
.get(format!("{}/small", mock_server.uri()))
.send()
.await
.expect("request should succeed");
let body = read_body_limited(resp, 1024).await.expect("within limit");
assert_eq!(body, "hello world");
}
#[tokio::test]
async fn test_read_body_limited_rejects_oversized_content_length() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock_server = MockServer::start().await;
let big = "x".repeat(2048);
Mock::given(method("GET"))
.and(path("/big"))
.respond_with(ResponseTemplate::new(200).set_body_raw(big.as_str(), "text/plain"))
.mount(&mock_server)
.await;
let client = create_http_client_with_redirects(5, 10);
let resp = client
.get(format!("{}/big", mock_server.uri()))
.send()
.await
.expect("request should succeed");
let err = read_body_limited(resp, 1024)
.await
.expect_err("should reject oversized content_length before reading");
assert!(
matches!(err, BodyReadError::LimitExceeded { max_bytes: 1024 }),
"expected LimitExceeded, got {:?}",
err
);
}
#[tokio::test]
async fn test_accumulate_limited_within_limit() {
let chunks: Vec<Result<bytes::Bytes, reqwest::Error>> = vec![
Ok(bytes::Bytes::from_static(b"hello ")),
Ok(bytes::Bytes::from_static(b"world")),
];
let out = accumulate_limited(futures::stream::iter(chunks), 1024)
.await
.expect("within limit");
assert_eq!(out, b"hello world");
}
#[tokio::test]
async fn test_accumulate_limited_exact_boundary_is_allowed() {
let chunks: Vec<Result<bytes::Bytes, reqwest::Error>> = vec![
Ok(bytes::Bytes::from_static(b"aaaa")),
Ok(bytes::Bytes::from_static(b"bbbb")),
];
let out = accumulate_limited(futures::stream::iter(chunks), 8)
.await
.expect("body of exactly max_bytes must be allowed");
assert_eq!(out, b"aaaabbbb");
}
#[tokio::test]
async fn test_accumulate_limited_exceeds_returns_error() {
let chunks: Vec<Result<bytes::Bytes, reqwest::Error>> = vec![
Ok(bytes::Bytes::from_static(b"aaaa")),
Ok(bytes::Bytes::from_static(b"bbbb")),
Ok(bytes::Bytes::from_static(b"cccc")),
];
let err = accumulate_limited(futures::stream::iter(chunks), 8)
.await
.expect_err("should exceed limit on third chunk");
assert!(
matches!(err, BodyReadError::LimitExceeded { max_bytes: 8 }),
"expected LimitExceeded, got {:?}",
err
);
}
}