use super::error::{FetchError, HeaderField, TransportError};
use super::resolver::SsrfSafeResolver;
use super::response::FeedHttpResponse;
use super::validation::validate_url;
use crate::error::Result;
use crate::limits::ParserLimits;
use reqwest::blocking::{Client, Response};
use reqwest::header::{
ACCEPT, ACCEPT_ENCODING, HeaderMap, HeaderName, HeaderValue, IF_MODIFIED_SINCE, IF_NONE_MATCH,
USER_AGENT,
};
use std::collections::HashMap;
use std::io::Read;
use std::sync::Arc;
use std::time::Duration;
const MAX_REDIRECTS: usize = 10;
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
pub struct FeedHttpClient {
client: Client,
user_agent: String,
timeout: Duration,
max_body_size: usize,
}
impl FeedHttpClient {
pub fn new() -> Result<Self> {
let client = Client::builder()
.timeout(DEFAULT_TIMEOUT)
.gzip(true)
.deflate(true)
.brotli(true)
.redirect(Self::redirect_policy())
.dns_resolver(Arc::new(SsrfSafeResolver))
.no_proxy()
.build()
.map_err(|e| FetchError::Transport(TransportError::new(e)))?;
Ok(Self {
client,
user_agent: format!(
"feedparser-rs/{} (+https://github.com/bug-ops/feedparser-rs)",
env!("CARGO_PKG_VERSION")
),
timeout: DEFAULT_TIMEOUT,
max_body_size: ParserLimits::default().max_feed_size_bytes,
})
}
fn should_follow_redirect(
next_url: &str,
previous_hops: usize,
) -> std::result::Result<(), FetchError> {
if previous_hops > MAX_REDIRECTS {
return Err(FetchError::TooManyRedirects);
}
validate_url(next_url)?;
Ok(())
}
fn redirect_policy() -> reqwest::redirect::Policy {
reqwest::redirect::Policy::custom(|attempt| {
match Self::should_follow_redirect(attempt.url().as_str(), attempt.previous().len()) {
Ok(()) => attempt.follow(),
Err(e) => attempt.error(e),
}
})
}
#[must_use]
pub fn with_user_agent(mut self, mut agent: String) -> Self {
const MAX_USER_AGENT_LEN: usize = 512;
agent.truncate(agent.floor_char_boundary(MAX_USER_AGENT_LEN));
self.user_agent = agent;
self
}
#[must_use]
pub const fn with_timeout(mut self, timeout: Duration) -> Self {
const MAX_TIMEOUT_SECS: u64 = 3600;
self.timeout = if timeout.as_secs() > MAX_TIMEOUT_SECS {
Duration::from_secs(MAX_TIMEOUT_SECS)
} else {
timeout
};
self
}
#[must_use]
pub const fn with_max_body_size(mut self, max_bytes: usize) -> Self {
self.max_body_size = max_bytes;
self
}
#[cfg(test)]
pub(crate) const fn max_body_size(&self) -> usize {
self.max_body_size
}
#[inline]
fn insert_header(
headers: &mut HeaderMap,
name: HeaderName,
value: &str,
field: HeaderField,
) -> std::result::Result<(), FetchError> {
headers.insert(
name,
HeaderValue::from_str(value).map_err(|_| FetchError::InvalidHeader { name: field })?,
);
Ok(())
}
pub fn get(
&self,
url: &str,
etag: Option<&str>,
modified: Option<&str>,
extra_headers: Option<&HeaderMap>,
) -> Result<FeedHttpResponse> {
let validated_url = validate_url(url)?;
let url_str = validated_url.as_str();
let mut headers = HeaderMap::new();
Self::insert_header(
&mut headers,
USER_AGENT,
&self.user_agent,
HeaderField::UserAgent,
)?;
headers.insert(
ACCEPT,
HeaderValue::from_static(
"application/rss+xml, application/atom+xml, application/xml, text/xml, */*",
),
);
headers.insert(
ACCEPT_ENCODING,
HeaderValue::from_static("gzip, deflate, br"),
);
if let Some(etag_val) = etag {
const MAX_ETAG_LEN: usize = 1024;
let sanitized_etag = truncate_at_char_boundary(etag_val, MAX_ETAG_LEN);
Self::insert_header(
&mut headers,
IF_NONE_MATCH,
sanitized_etag,
HeaderField::IfNoneMatch,
)?;
}
if let Some(modified_val) = modified {
const MAX_MODIFIED_LEN: usize = 64;
let sanitized_modified = truncate_at_char_boundary(modified_val, MAX_MODIFIED_LEN);
Self::insert_header(
&mut headers,
IF_MODIFIED_SINCE,
sanitized_modified,
HeaderField::IfModifiedSince,
)?;
}
if let Some(extra) = extra_headers {
headers.extend(extra.clone());
}
let request = self.build_request(url_str, headers)?;
let response = self
.client
.execute(request)
.map_err(FetchError::from_request_error)?;
self.build_response(response)
}
fn build_request(
&self,
url_str: &str,
headers: HeaderMap,
) -> std::result::Result<reqwest::blocking::Request, FetchError> {
self.client
.get(url_str)
.headers(headers)
.timeout(self.timeout)
.build()
.map_err(FetchError::from_request_error)
}
fn build_response(&self, response: Response) -> Result<FeedHttpResponse> {
let status = response.status().as_u16();
let url = response.url().to_string();
let mut headers_map = HashMap::with_capacity(response.headers().len());
for (name, value) in response.headers() {
if let Ok(val_str) = value.to_str() {
headers_map.insert(name.to_string(), val_str.to_string());
}
}
let etag = headers_map.get("etag").cloned();
let last_modified = headers_map.get("last-modified").cloned();
let content_type = headers_map.get("content-type").cloned();
let body = if status == 304 {
Vec::new()
} else {
self.read_body(status, response)?
};
Ok(FeedHttpResponse {
status,
url,
headers: headers_map,
body,
etag,
last_modified,
content_type,
})
}
fn read_body(&self, status: u16, body: impl Read) -> Result<Vec<u8>> {
let max = self.max_body_size;
let read_limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1);
let mut bytes = Vec::new();
body.take(read_limit)
.read_to_end(&mut bytes)
.map_err(|e| FetchError::Transport(TransportError::new(e)))?;
if status >= 400 {
bytes.truncate(max);
} else if bytes.len() > max {
return Err(FetchError::BodyTooLarge { limit: max }.into());
}
Ok(bytes)
}
}
fn truncate_at_char_boundary(s: &str, max: usize) -> &str {
s.get(..s.floor_char_boundary(max)).unwrap_or(s)
}
#[cfg(test)]
mod tests {
use super::*;
use flate2::{Compression, write::GzEncoder};
use std::io::Write as _;
#[test]
fn test_truncate_at_char_boundary() {
assert_eq!(truncate_at_char_boundary("abc", 4), "abc");
assert_eq!(truncate_at_char_boundary("abc", 3), "abc");
assert_eq!(truncate_at_char_boundary("abcd", 3), "abc");
assert_eq!(truncate_at_char_boundary("aéé", 4), "aé");
assert_eq!(truncate_at_char_boundary("é", 1), "");
}
#[expect(
clippy::significant_drop_tightening,
reason = "the mockito server must outlive the request under test"
)]
fn fetch_local(
client: &FeedHttpClient,
body: &[u8],
content_encoding: Option<&str>,
) -> Result<FeedHttpResponse> {
let mut server = mockito::Server::new();
let mut mock = server.mock("GET", "/feed").with_body(body);
if let Some(encoding) = content_encoding {
mock = mock.with_header("content-encoding", encoding);
}
let _mock = mock.create();
let response = client
.client
.get(format!("{}/feed", server.url()))
.send()
.unwrap();
client.build_response(response)
}
fn assert_too_large(result: Result<FeedHttpResponse>, max: usize) {
let message = result.map(|response| response.body.len()).unwrap_err();
assert!(
message
.to_string()
.contains(&format!("Response body exceeds the limit of {max} bytes")),
"{message}"
);
}
#[test]
fn test_body_limit_applies_to_decompressed_bytes() {
let mut encoder = GzEncoder::new(Vec::new(), Compression::best());
encoder.write_all(&vec![b'a'; 1024 * 1024]).unwrap();
let bomb = encoder.finish().unwrap();
assert!(bomb.len() < 4096);
let client = FeedHttpClient::new().unwrap().with_max_body_size(4096);
assert_too_large(fetch_local(&client, &bomb, Some("gzip")), 4096);
}
#[test]
fn test_body_limit_boundaries() {
let client = |max| FeedHttpClient::new().unwrap().with_max_body_size(max);
let exact = fetch_local(&client(4), b"abcd", None).unwrap();
assert_eq!(exact.body, b"abcd");
assert_too_large(fetch_local(&client(3), b"abcd", None), 3);
assert_too_large(fetch_local(&client(0), b"a", None), 0);
assert!(fetch_local(&client(0), b"", None).is_ok());
let unbounded = fetch_local(&client(usize::MAX), b"abcd", None).unwrap();
assert_eq!(unbounded.body, b"abcd");
}
#[test]
fn test_body_limit_default_matches_parser_limits() {
let client = FeedHttpClient::new().unwrap();
assert_eq!(
client.max_body_size(),
ParserLimits::default().max_feed_size_bytes
);
}
#[test]
fn test_client_creation() {
let client = FeedHttpClient::new();
assert!(client.is_ok());
}
#[test]
fn test_redirect_rejects_metadata_endpoint() {
let result =
FeedHttpClient::should_follow_redirect("http://169.254.169.254/latest/meta-data/", 1);
assert!(result.is_err());
}
#[test]
fn test_redirect_rejects_private_ip() {
let result = FeedHttpClient::should_follow_redirect("http://10.0.0.5/admin", 1);
assert!(result.is_err());
}
#[test]
fn test_redirect_allows_public_ip_within_hop_limit() {
let result = FeedHttpClient::should_follow_redirect("http://8.8.8.8/", 1);
assert!(result.is_ok());
}
#[test]
fn test_redirect_rejects_over_hop_limit_even_for_safe_url() {
let result = FeedHttpClient::should_follow_redirect("http://8.8.8.8/", MAX_REDIRECTS + 1);
assert!(result.is_err());
}
#[test]
fn test_redirect_allows_at_hop_limit() {
let result = FeedHttpClient::should_follow_redirect("http://8.8.8.8/", MAX_REDIRECTS);
assert!(result.is_ok());
}
#[expect(
clippy::significant_drop_tightening,
reason = "the mockito server must outlive the request under test"
)]
#[test]
fn test_redirect_to_metadata_endpoint_rejected_end_to_end() {
let mut server = mockito::Server::new();
let mock = server
.mock("GET", "/redirect")
.with_status(302)
.with_header("location", "http://169.254.169.254/latest/meta-data/")
.create();
let client = Client::builder()
.redirect(FeedHttpClient::redirect_policy())
.build()
.unwrap();
let url = format!("{}/redirect", server.url());
let result = client.get(&url).send();
let err = result.expect_err("redirect to a metadata IP must be rejected");
let description = crate::http::error_chain(&err);
assert!(
description.contains("Link-local address not allowed"),
"expected the SSRF rejection reason in the error chain, got: {description}"
);
mock.assert();
}
#[expect(
clippy::significant_drop_tightening,
reason = "the mockito server must outlive the request under test"
)]
#[test]
fn test_redirect_follows_legitimate_multi_hop_chain() {
let mut server = mockito::Server::new();
let addr = server.socket_address();
let mock1 = server
.mock("GET", "/hop1")
.with_status(302)
.with_header("location", "http://public.test/hop2")
.create();
let mock2 = server
.mock("GET", "/hop2")
.with_status(302)
.with_header("location", "http://public.test/hop3")
.create();
let mock3 = server
.mock("GET", "/hop3")
.with_status(200)
.with_body("ok")
.create();
let client = Client::builder()
.redirect(FeedHttpClient::redirect_policy())
.dns_resolver(Arc::new(SsrfSafeResolver))
.resolve("public.test", addr)
.build()
.unwrap();
let url = format!("http://public.test:{}/hop1", addr.port());
let response = client.get(&url).send().unwrap();
assert_eq!(response.status().as_u16(), 200);
mock1.assert();
mock2.assert();
mock3.assert();
}
#[expect(
clippy::significant_drop_tightening,
reason = "the mockito server must outlive the request under test"
)]
#[test]
fn test_redirect_chain_rejects_metadata_after_legitimate_hops() {
let mut server = mockito::Server::new();
let addr = server.socket_address();
let mock1 = server
.mock("GET", "/hop1")
.with_status(302)
.with_header("location", "http://public.test/hop2")
.create();
let mock2 = server
.mock("GET", "/hop2")
.with_status(302)
.with_header("location", "http://169.254.169.254/latest/meta-data/")
.create();
let client = Client::builder()
.redirect(FeedHttpClient::redirect_policy())
.dns_resolver(Arc::new(SsrfSafeResolver))
.resolve("public.test", addr)
.build()
.unwrap();
let url = format!("http://public.test:{}/hop1", addr.port());
let err = client.get(&url).send().expect_err(
"a chain ending at a metadata IP must be rejected, even after legitimate hops",
);
let description = crate::http::error_chain(&err);
assert!(
description.contains("Link-local address not allowed"),
"expected the SSRF rejection reason to survive a multi-hop chain, got: {description}"
);
mock1.assert();
mock2.assert();
}
#[test]
fn test_dns_resolver_wired_into_client_rejects_loopback() {
let client = Client::builder()
.dns_resolver(Arc::new(SsrfSafeResolver))
.build()
.unwrap();
let result = client.get("http://localhost/").send();
assert!(result.is_err());
}
#[test]
fn test_custom_user_agent() {
let client = FeedHttpClient::new()
.unwrap()
.with_user_agent("CustomBot/1.0".to_string());
assert_eq!(client.user_agent, "CustomBot/1.0");
}
#[test]
fn test_user_agent_truncated_to_512_bytes_at_char_boundary() {
let client = FeedHttpClient::new()
.unwrap()
.with_user_agent("é".repeat(300));
assert_eq!(client.user_agent, "é".repeat(256));
let client = FeedHttpClient::new()
.unwrap()
.with_user_agent("a".repeat(511) + "é");
assert_eq!(client.user_agent, "a".repeat(511));
let exact = "b".repeat(512);
let client = FeedHttpClient::new()
.unwrap()
.with_user_agent(exact.clone());
assert_eq!(client.user_agent, exact);
}
#[test]
fn test_custom_timeout() {
let timeout = Duration::from_mins(1);
let client = FeedHttpClient::new().unwrap().with_timeout(timeout);
assert_eq!(client.timeout, timeout);
}
#[test]
fn test_with_timeout_clamps_absurd_duration() {
let client = FeedHttpClient::new().unwrap().with_timeout(Duration::MAX);
assert_eq!(client.timeout, Duration::from_hours(1));
}
#[test]
fn test_build_request_applies_configured_timeout() {
let timeout = Duration::from_secs(7);
let client = FeedHttpClient::new().unwrap().with_timeout(timeout);
let request = client
.build_request("https://example.test/feed.xml", HeaderMap::new())
.unwrap();
assert_eq!(request.timeout(), Some(&timeout));
}
fn local_client(addr: std::net::SocketAddr, timeout: Duration) -> FeedHttpClient {
let client = Client::builder()
.dns_resolver(Arc::new(SsrfSafeResolver))
.resolve("public.test", addr)
.build()
.unwrap();
FeedHttpClient {
client,
user_agent: "test-agent".to_string(),
timeout,
max_body_size: usize::MAX,
}
}
#[expect(
clippy::significant_drop_tightening,
reason = "the mockito server must outlive the request under test"
)]
#[test]
fn test_url_parsing_bounds_download_by_feed_size_limit() {
let mut server = mockito::Server::new();
let addr = server.socket_address();
let mock = server
.mock("GET", "/big")
.with_body("a".repeat(100))
.create();
let options = crate::ParseOptions {
limits: ParserLimits {
max_feed_size_bytes: 10,
..ParserLimits::default()
},
..crate::ParseOptions::default()
};
let client = local_client(addr, Duration::from_secs(5));
let url = format!("http://public.test:{}/big", addr.port());
let message = crate::fetch_and_parse(client, &url, None, None, None, &options)
.map(|feed| feed.version)
.unwrap_err()
.to_string();
assert!(
message.contains("Response body exceeds the limit of 10 bytes"),
"{message}"
);
mock.assert();
}
#[expect(
clippy::significant_drop_tightening,
reason = "the mockito server must outlive the request under test"
)]
#[test]
fn test_error_status_survives_oversized_body() {
let mut server = mockito::Server::new();
let addr = server.socket_address();
let mock = server
.mock("GET", "/missing")
.with_status(404)
.with_body("a".repeat(100))
.expect(2)
.create();
let url = format!("http://public.test:{}/missing", addr.port());
let client = || local_client(addr, Duration::from_secs(5));
let response = client()
.with_max_body_size(10)
.get(&url, None, None, None)
.unwrap();
assert_eq!(response.status, 404);
assert_eq!(response.body, b"aaaaaaaaaa");
let options = crate::ParseOptions {
limits: ParserLimits {
max_feed_size_bytes: 10,
..ParserLimits::default()
},
..crate::ParseOptions::default()
};
let message = crate::fetch_and_parse(client(), &url, None, None, None, &options)
.map(|feed| feed.version)
.unwrap_err()
.to_string();
assert!(message.contains("HTTP 404"), "{message}");
mock.assert();
}
#[expect(
clippy::significant_drop_tightening,
reason = "the mockito server must outlive the request under test"
)]
#[test]
fn test_with_timeout_enforced_on_slow_response() {
let mut server = mockito::Server::new();
let addr = server.socket_address();
let mock = server
.mock("GET", "/slow")
.with_chunked_body(|w| {
std::thread::sleep(Duration::from_millis(500));
w.write_all(b"too slow")
})
.create();
let client = local_client(addr, Duration::from_millis(100));
let url = format!("http://public.test:{}/slow", addr.port());
let started = std::time::Instant::now();
client
.get(&url, None, None, None)
.expect_err("a response slower than the configured 100ms timeout must fail");
let elapsed = started.elapsed();
assert!(
elapsed < Duration::from_millis(400),
"request did not fail until {elapsed:?}; timeout was not enforced"
);
mock.assert();
}
#[test]
#[expect(
clippy::significant_drop_tightening,
reason = "the mockito server must outlive the request under test"
)]
fn test_with_timeout_allows_fast_response() {
let mut server = mockito::Server::new();
let addr = server.socket_address();
let mock = server
.mock("GET", "/fast")
.with_status(200)
.with_body("ok")
.create();
let client = local_client(addr, Duration::from_secs(5));
let url = format!("http://public.test:{}/fast", addr.port());
let response = client
.get(&url, None, None, None)
.expect("a response faster than the configured timeout must succeed");
assert_eq!(response.status, 200);
mock.assert();
}
#[test]
fn test_reject_localhost_url() {
let client = FeedHttpClient::new().unwrap();
let result = client.get("http://localhost/feed.xml", None, None, None);
assert!(result.is_err());
let err_msg = result.err().unwrap().to_string();
assert!(err_msg.contains("Localhost domain not allowed"));
}
#[test]
fn test_reject_private_ip() {
let client = FeedHttpClient::new().unwrap();
let result = client.get("http://192.168.1.1/feed.xml", None, None, None);
assert!(result.is_err());
let err_msg = result.err().unwrap().to_string();
assert!(err_msg.contains("Private IP address not allowed"));
}
#[test]
fn test_reject_metadata_endpoint() {
let client = FeedHttpClient::new().unwrap();
let result = client.get("http://169.254.169.254/latest/meta-data/", None, None, None);
assert!(result.is_err());
let err_msg = result.err().unwrap().to_string();
assert!(err_msg.contains("metadata") || err_msg.contains("Link-local"));
}
#[test]
fn test_reject_file_scheme() {
let client = FeedHttpClient::new().unwrap();
let result = client.get("file:///etc/passwd", None, None, None);
assert!(result.is_err());
let err_msg = result.err().unwrap().to_string();
assert!(err_msg.contains("Unsupported URL scheme"));
}
#[test]
fn test_reject_internal_domain() {
let client = FeedHttpClient::new().unwrap();
let result = client.get("http://server.local/feed.xml", None, None, None);
assert!(result.is_err());
let err_msg = result.err().unwrap().to_string();
assert!(err_msg.contains("Internal domain TLD not allowed"));
}
#[test]
fn test_insert_header_valid() {
let mut headers = HeaderMap::new();
let result = FeedHttpClient::insert_header(
&mut headers,
USER_AGENT,
"TestBot/1.0",
HeaderField::UserAgent,
);
assert!(result.is_ok());
assert_eq!(headers.get(USER_AGENT).unwrap(), "TestBot/1.0");
}
#[test]
fn test_insert_header_invalid_value() {
let mut headers = HeaderMap::new();
let result = FeedHttpClient::insert_header(
&mut headers,
USER_AGENT,
"Invalid\nHeader",
HeaderField::UserAgent,
);
assert!(matches!(
result,
Err(FetchError::InvalidHeader {
name: HeaderField::UserAgent
})
));
assert_eq!(
result.unwrap_err().to_string(),
"Invalid User-Agent header value"
);
}
#[test]
fn test_insert_header_multiple_headers() {
let mut headers = HeaderMap::new();
FeedHttpClient::insert_header(
&mut headers,
USER_AGENT,
"TestBot/1.0",
HeaderField::UserAgent,
)
.unwrap();
FeedHttpClient::insert_header(
&mut headers,
IF_NONE_MATCH,
"\"abc\"",
HeaderField::IfNoneMatch,
)
.unwrap();
assert_eq!(headers.len(), 2);
assert_eq!(headers.get(USER_AGENT).unwrap(), "TestBot/1.0");
assert_eq!(headers.get(IF_NONE_MATCH).unwrap(), "\"abc\"");
}
}