Skip to main content

feedparser_rs/http/
client.rs

1use super::error::{FetchError, HeaderField, TransportError};
2use super::resolver::SsrfSafeResolver;
3use super::response::FeedHttpResponse;
4use super::validation::validate_url;
5use crate::error::Result;
6use crate::limits::ParserLimits;
7use reqwest::blocking::{Client, Response};
8use reqwest::header::{
9    ACCEPT, ACCEPT_ENCODING, HeaderMap, HeaderName, HeaderValue, IF_MODIFIED_SINCE, IF_NONE_MATCH,
10    USER_AGENT,
11};
12use std::collections::HashMap;
13use std::io::Read;
14use std::sync::Arc;
15use std::time::Duration;
16
17/// Maximum number of redirects to follow before aborting, matching the hop
18/// count `reqwest::redirect::Policy::limited` used to enforce. A custom
19/// policy does not get this for free, so [`FeedHttpClient::redirect_policy`]
20/// enforces it explicitly alongside SSRF re-validation.
21const MAX_REDIRECTS: usize = 10;
22
23/// Default per-request timeout used both to build the underlying
24/// `reqwest::blocking::Client` in [`FeedHttpClient::new`] and to seed
25/// [`FeedHttpClient::timeout`], so the two never drift apart.
26const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
27
28/// HTTP client for fetching feeds
29pub struct FeedHttpClient {
30    client: Client,
31    user_agent: String,
32    timeout: Duration,
33    max_body_size: usize,
34}
35
36impl FeedHttpClient {
37    /// Creates a new HTTP client with default settings
38    ///
39    /// Default settings:
40    /// - 30 second timeout
41    /// - Gzip, deflate, and brotli compression enabled
42    /// - Maximum 10 redirects, each re-validated against the SSRF checks
43    /// - DNS resolution re-validated against the SSRF checks to close
44    ///   DNS-rebinding gaps between validation and connect time
45    /// - No system/environment proxy (`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`)
46    ///   is honored: a proxy connects through a hostname that is resolved by
47    ///   the proxy itself, not by the DNS-rebinding-safe resolver above,
48    ///   which would silently defeat that protection
49    /// - Custom User-Agent
50    /// - Response bodies capped at [`ParserLimits::max_feed_size_bytes`]'s default
51    ///   (see [`Self::with_max_body_size`])
52    ///
53    /// # Errors
54    ///
55    /// Returns `FeedError::Fetch` if the underlying HTTP client cannot be created.
56    pub fn new() -> Result<Self> {
57        let client = Client::builder()
58            .timeout(DEFAULT_TIMEOUT)
59            .gzip(true)
60            .deflate(true)
61            .brotli(true)
62            .redirect(Self::redirect_policy())
63            .dns_resolver(Arc::new(SsrfSafeResolver))
64            .no_proxy()
65            .build()
66            .map_err(|e| FetchError::Transport(TransportError::new(e)))?;
67
68        Ok(Self {
69            client,
70            user_agent: format!(
71                "feedparser-rs/{} (+https://github.com/bug-ops/feedparser-rs)",
72                env!("CARGO_PKG_VERSION")
73            ),
74            timeout: DEFAULT_TIMEOUT,
75            max_body_size: ParserLimits::default().max_feed_size_bytes,
76        })
77    }
78
79    /// Decides whether a redirect hop should be followed.
80    ///
81    /// Extracted from [`Self::redirect_policy`] so the decision can be unit
82    /// tested directly: `reqwest::redirect::Attempt` has no public
83    /// constructor, so the policy closure itself cannot be exercised without
84    /// a live HTTP round trip.
85    ///
86    /// # Errors
87    ///
88    /// Returns [`FetchError::TooManyRedirects`] if the hop count exceeds
89    /// `MAX_REDIRECTS`, or the SSRF rejection if `next_url` fails validation.
90    fn should_follow_redirect(
91        next_url: &str,
92        previous_hops: usize,
93    ) -> std::result::Result<(), FetchError> {
94        if previous_hops > MAX_REDIRECTS {
95            return Err(FetchError::TooManyRedirects);
96        }
97
98        validate_url(next_url)?;
99        Ok(())
100    }
101
102    /// Builds a redirect policy that re-validates every hop against the SSRF
103    /// checks in [`validate_url`], not just the initial request URL.
104    ///
105    /// `reqwest`'s built-in `Policy::limited` only counts hops — it never
106    /// re-runs SSRF validation on the `Location` header, so a malicious
107    /// server could pass the initial check and then redirect to an internal
108    /// address (e.g. cloud metadata endpoints) and have it followed
109    /// silently. A custom policy also does not enforce a hop limit on its
110    /// own, so [`Self::should_follow_redirect`] replicates `Policy::limited`'s
111    /// bound explicitly.
112    fn redirect_policy() -> reqwest::redirect::Policy {
113        reqwest::redirect::Policy::custom(|attempt| {
114            match Self::should_follow_redirect(attempt.url().as_str(), attempt.previous().len()) {
115                Ok(()) => attempt.follow(),
116                Err(e) => attempt.error(e),
117            }
118        })
119    }
120
121    /// Sets a custom User-Agent header
122    ///
123    /// # Security
124    ///
125    /// User-Agent is truncated to 512 bytes to prevent header injection attacks.
126    #[must_use]
127    pub fn with_user_agent(mut self, mut agent: String) -> Self {
128        // Truncate to 512 bytes to prevent header injection
129        const MAX_USER_AGENT_LEN: usize = 512;
130        agent.truncate(agent.floor_char_boundary(MAX_USER_AGENT_LEN));
131        self.user_agent = agent;
132        self
133    }
134
135    /// Sets the per-request timeout applied to every [`Self::get`] call.
136    ///
137    /// The value is a total deadline covering connection, all redirect hops,
138    /// and the full response body — not a per-hop timeout. `Duration::ZERO`
139    /// means "time out immediately", not "disable the timeout"; this API has
140    /// no way to disable it entirely. Values above one hour are clamped to
141    /// one hour: `reqwest`'s blocking wait computes its deadline as
142    /// `Instant::now() + timeout` without an overflow check, so passing
143    /// `Duration::MAX` (or another value near the `Instant` range limit)
144    /// would otherwise panic instead of erroring.
145    #[must_use]
146    pub const fn with_timeout(mut self, timeout: Duration) -> Self {
147        const MAX_TIMEOUT_SECS: u64 = 3600;
148        self.timeout = if timeout.as_secs() > MAX_TIMEOUT_SECS {
149            Duration::from_secs(MAX_TIMEOUT_SECS)
150        } else {
151            timeout
152        };
153        self
154    }
155
156    /// Caps the size of the response body read by [`Self::get`].
157    ///
158    /// The limit applies to the decompressed bytes, so a small compressed response
159    /// cannot expand without bound. At most `max_bytes + 1` bytes are read; a longer
160    /// body makes [`Self::get`] return [`FetchError::BodyTooLarge`], except for a 4xx or 5xx
161    /// response, whose body is truncated to the limit so that the status survives.
162    /// `usize::MAX` removes the bound.
163    ///
164    /// # Examples
165    ///
166    /// ```
167    /// use feedparser_rs::FeedHttpClient;
168    ///
169    /// let client = FeedHttpClient::new()?.with_max_body_size(1024 * 1024);
170    /// # Ok::<(), feedparser_rs::FeedError>(())
171    /// ```
172    #[must_use]
173    pub const fn with_max_body_size(mut self, max_bytes: usize) -> Self {
174        self.max_body_size = max_bytes;
175        self
176    }
177
178    #[cfg(test)]
179    pub(crate) const fn max_body_size(&self) -> usize {
180        self.max_body_size
181    }
182
183    /// Insert header with consistent error handling
184    ///
185    /// Helper method to reduce boilerplate in header insertion.
186    #[inline]
187    fn insert_header(
188        headers: &mut HeaderMap,
189        name: HeaderName,
190        value: &str,
191        field: HeaderField,
192    ) -> std::result::Result<(), FetchError> {
193        headers.insert(
194            name,
195            HeaderValue::from_str(value).map_err(|_| FetchError::InvalidHeader { name: field })?,
196        );
197        Ok(())
198    }
199
200    /// Fetches a feed from the given URL
201    ///
202    /// Supports conditional GET with `ETag` and `Last-Modified` headers.
203    ///
204    /// # Arguments
205    ///
206    /// * `url` - HTTP/HTTPS URL to fetch
207    /// * `etag` - Optional `ETag` from previous fetch
208    /// * `modified` - Optional `Last-Modified` from previous fetch
209    /// * `extra_headers` - Additional custom headers
210    ///
211    /// # Errors
212    ///
213    /// Returns `FeedError::Fetch` with [`FetchError::InvalidUrl`] or
214    /// [`FetchError::BlockedAddress`] for a rejected URL or redirect hop,
215    /// [`FetchError::TooManyRedirects`], [`FetchError::InvalidHeader`],
216    /// [`FetchError::BodyTooLarge`] for the body of a response below status 400
217    /// that exceeds the limit set by [`Self::with_max_body_size`], and
218    /// [`FetchError::Transport`] for any other failure. A 4xx or 5xx status is not
219    /// an error here: the response is returned with its status.
220    pub fn get(
221        &self,
222        url: &str,
223        etag: Option<&str>,
224        modified: Option<&str>,
225        extra_headers: Option<&HeaderMap>,
226    ) -> Result<FeedHttpResponse> {
227        // Validate URL to prevent SSRF attacks
228        let validated_url = validate_url(url)?;
229        let url_str = validated_url.as_str();
230
231        let mut headers = HeaderMap::new();
232
233        // Standard headers
234        Self::insert_header(
235            &mut headers,
236            USER_AGENT,
237            &self.user_agent,
238            HeaderField::UserAgent,
239        )?;
240
241        headers.insert(
242            ACCEPT,
243            HeaderValue::from_static(
244                "application/rss+xml, application/atom+xml, application/xml, text/xml, */*",
245            ),
246        );
247
248        headers.insert(
249            ACCEPT_ENCODING,
250            HeaderValue::from_static("gzip, deflate, br"),
251        );
252
253        // Conditional GET headers with length validation
254        if let Some(etag_val) = etag {
255            // Truncate ETag to 1KB to prevent oversized headers
256            const MAX_ETAG_LEN: usize = 1024;
257            let sanitized_etag = truncate_at_char_boundary(etag_val, MAX_ETAG_LEN);
258            Self::insert_header(
259                &mut headers,
260                IF_NONE_MATCH,
261                sanitized_etag,
262                HeaderField::IfNoneMatch,
263            )?;
264        }
265
266        if let Some(modified_val) = modified {
267            // Truncate Last-Modified to 64 bytes (RFC 822 dates are ~30 bytes)
268            const MAX_MODIFIED_LEN: usize = 64;
269            let sanitized_modified = truncate_at_char_boundary(modified_val, MAX_MODIFIED_LEN);
270            Self::insert_header(
271                &mut headers,
272                IF_MODIFIED_SINCE,
273                sanitized_modified,
274                HeaderField::IfModifiedSince,
275            )?;
276        }
277
278        // Merge extra headers
279        if let Some(extra) = extra_headers {
280            headers.extend(extra.clone());
281        }
282
283        let request = self.build_request(url_str, headers)?;
284
285        let response = self
286            .client
287            .execute(request)
288            .map_err(FetchError::from_request_error)?;
289
290        self.build_response(response)
291    }
292
293    /// Builds the GET request for `url_str` with `headers`, applying the
294    /// configured per-request timeout.
295    ///
296    /// Extracted from [`Self::get`] so the built [`reqwest::blocking::Request`]
297    /// can be inspected directly in tests (via [`reqwest::blocking::Request::timeout`])
298    /// without a network round trip.
299    ///
300    /// # Errors
301    ///
302    /// Returns [`FetchError::Transport`] if the request cannot be constructed.
303    fn build_request(
304        &self,
305        url_str: &str,
306        headers: HeaderMap,
307    ) -> std::result::Result<reqwest::blocking::Request, FetchError> {
308        self.client
309            .get(url_str)
310            .headers(headers)
311            .timeout(self.timeout)
312            .build()
313            .map_err(FetchError::from_request_error)
314    }
315
316    /// Converts `reqwest` Response to `FeedHttpResponse`
317    fn build_response(&self, response: Response) -> Result<FeedHttpResponse> {
318        let status = response.status().as_u16();
319        let url = response.url().to_string();
320
321        // Convert headers to HashMap with pre-allocated capacity
322        let mut headers_map = HashMap::with_capacity(response.headers().len());
323        for (name, value) in response.headers() {
324            if let Ok(val_str) = value.to_str() {
325                headers_map.insert(name.to_string(), val_str.to_string());
326            }
327        }
328
329        // Extract caching headers
330        let etag = headers_map.get("etag").cloned();
331        let last_modified = headers_map.get("last-modified").cloned();
332        let content_type = headers_map.get("content-type").cloned();
333
334        // Read body (handles gzip/deflate automatically)
335        let body = if status == 304 {
336            // Not Modified - no body
337            Vec::new()
338        } else {
339            self.read_body(status, response)?
340        };
341
342        Ok(FeedHttpResponse {
343            status,
344            url,
345            headers: headers_map,
346            body,
347            etag,
348            last_modified,
349            content_type,
350        })
351    }
352
353    /// Reads `body` up to one byte past the limit, enough to tell that it is too long.
354    fn read_body(&self, status: u16, body: impl Read) -> Result<Vec<u8>> {
355        let max = self.max_body_size;
356        let read_limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1);
357
358        let mut bytes = Vec::new();
359        body.take(read_limit)
360            .read_to_end(&mut bytes)
361            .map_err(|e| FetchError::Transport(TransportError::new(e)))?;
362
363        if status >= 400 {
364            bytes.truncate(max);
365        } else if bytes.len() > max {
366            return Err(FetchError::BodyTooLarge { limit: max }.into());
367        }
368        Ok(bytes)
369    }
370}
371
372/// Longest prefix of `s` that is at most `max` bytes and ends on a char boundary.
373fn truncate_at_char_boundary(s: &str, max: usize) -> &str {
374    s.get(..s.floor_char_boundary(max)).unwrap_or(s)
375}
376
377#[cfg(test)]
378mod tests {
379    use super::*;
380    use flate2::{Compression, write::GzEncoder};
381    use std::io::Write as _;
382
383    #[test]
384    fn test_truncate_at_char_boundary() {
385        assert_eq!(truncate_at_char_boundary("abc", 4), "abc");
386        assert_eq!(truncate_at_char_boundary("abc", 3), "abc");
387        assert_eq!(truncate_at_char_boundary("abcd", 3), "abc");
388        assert_eq!(truncate_at_char_boundary("aéé", 4), "aé");
389        assert_eq!(truncate_at_char_boundary("é", 1), "");
390    }
391
392    /// Serves `body` from a local server and reads it through `client`, bypassing
393    /// `get` whose SSRF checks reject loopback addresses.
394    #[expect(
395        clippy::significant_drop_tightening,
396        reason = "the mockito server must outlive the request under test"
397    )]
398    fn fetch_local(
399        client: &FeedHttpClient,
400        body: &[u8],
401        content_encoding: Option<&str>,
402    ) -> Result<FeedHttpResponse> {
403        let mut server = mockito::Server::new();
404        let mut mock = server.mock("GET", "/feed").with_body(body);
405        if let Some(encoding) = content_encoding {
406            mock = mock.with_header("content-encoding", encoding);
407        }
408        let _mock = mock.create();
409
410        let response = client
411            .client
412            .get(format!("{}/feed", server.url()))
413            .send()
414            .unwrap();
415        client.build_response(response)
416    }
417
418    fn assert_too_large(result: Result<FeedHttpResponse>, max: usize) {
419        let message = result.map(|response| response.body.len()).unwrap_err();
420        assert!(
421            message
422                .to_string()
423                .contains(&format!("Response body exceeds the limit of {max} bytes")),
424            "{message}"
425        );
426    }
427
428    #[test]
429    fn test_body_limit_applies_to_decompressed_bytes() {
430        let mut encoder = GzEncoder::new(Vec::new(), Compression::best());
431        encoder.write_all(&vec![b'a'; 1024 * 1024]).unwrap();
432        let bomb = encoder.finish().unwrap();
433        assert!(bomb.len() < 4096);
434
435        let client = FeedHttpClient::new().unwrap().with_max_body_size(4096);
436        assert_too_large(fetch_local(&client, &bomb, Some("gzip")), 4096);
437    }
438
439    #[test]
440    fn test_body_limit_boundaries() {
441        let client = |max| FeedHttpClient::new().unwrap().with_max_body_size(max);
442
443        let exact = fetch_local(&client(4), b"abcd", None).unwrap();
444        assert_eq!(exact.body, b"abcd");
445        assert_too_large(fetch_local(&client(3), b"abcd", None), 3);
446        assert_too_large(fetch_local(&client(0), b"a", None), 0);
447        assert!(fetch_local(&client(0), b"", None).is_ok());
448
449        let unbounded = fetch_local(&client(usize::MAX), b"abcd", None).unwrap();
450        assert_eq!(unbounded.body, b"abcd");
451    }
452
453    #[test]
454    fn test_body_limit_default_matches_parser_limits() {
455        let client = FeedHttpClient::new().unwrap();
456        assert_eq!(
457            client.max_body_size(),
458            ParserLimits::default().max_feed_size_bytes
459        );
460    }
461
462    #[test]
463    fn test_client_creation() {
464        let client = FeedHttpClient::new();
465        assert!(client.is_ok());
466    }
467
468    // === Redirect re-validation tests ===
469
470    #[test]
471    fn test_redirect_rejects_metadata_endpoint() {
472        let result =
473            FeedHttpClient::should_follow_redirect("http://169.254.169.254/latest/meta-data/", 1);
474        assert!(result.is_err());
475    }
476
477    #[test]
478    fn test_redirect_rejects_private_ip() {
479        let result = FeedHttpClient::should_follow_redirect("http://10.0.0.5/admin", 1);
480        assert!(result.is_err());
481    }
482
483    #[test]
484    fn test_redirect_allows_public_ip_within_hop_limit() {
485        let result = FeedHttpClient::should_follow_redirect("http://8.8.8.8/", 1);
486        assert!(result.is_ok());
487    }
488
489    #[test]
490    fn test_redirect_rejects_over_hop_limit_even_for_safe_url() {
491        let result = FeedHttpClient::should_follow_redirect("http://8.8.8.8/", MAX_REDIRECTS + 1);
492        assert!(result.is_err());
493    }
494
495    #[test]
496    fn test_redirect_allows_at_hop_limit() {
497        let result = FeedHttpClient::should_follow_redirect("http://8.8.8.8/", MAX_REDIRECTS);
498        assert!(result.is_ok());
499    }
500
501    #[expect(
502        clippy::significant_drop_tightening,
503        reason = "the mockito server must outlive the request under test"
504    )]
505    #[test]
506    fn test_redirect_to_metadata_endpoint_rejected_end_to_end() {
507        let mut server = mockito::Server::new();
508        let mock = server
509            .mock("GET", "/redirect")
510            .with_status(302)
511            .with_header("location", "http://169.254.169.254/latest/meta-data/")
512            .create();
513
514        // Bypasses the front-door `validate_url` (which would reject the
515        // mockito server's loopback address) to exercise only the redirect
516        // policy against a real HTTP redirect chain.
517        let client = Client::builder()
518            .redirect(FeedHttpClient::redirect_policy())
519            .build()
520            .unwrap();
521
522        let url = format!("{}/redirect", server.url());
523        let result = client.get(&url).send();
524
525        let err = result.expect_err("redirect to a metadata IP must be rejected");
526        // A broken policy would also error here (169.254.169.254 is
527        // unroutable from the test host), so assert on the actual SSRF
528        // rejection reason surviving through `describe_request_error`, not
529        // just on any error — proving the *redirect policy itself* is what
530        // rejected it, not a downstream connection failure.
531        let description = crate::http::error_chain(&err);
532        assert!(
533            description.contains("Link-local address not allowed"),
534            "expected the SSRF rejection reason in the error chain, got: {description}"
535        );
536        mock.assert();
537    }
538
539    #[expect(
540        clippy::significant_drop_tightening,
541        reason = "the mockito server must outlive the request under test"
542    )]
543    #[test]
544    fn test_redirect_follows_legitimate_multi_hop_chain() {
545        let mut server = mockito::Server::new();
546        let addr = server.socket_address();
547
548        let mock1 = server
549            .mock("GET", "/hop1")
550            .with_status(302)
551            .with_header("location", "http://public.test/hop2")
552            .create();
553        let mock2 = server
554            .mock("GET", "/hop2")
555            .with_status(302)
556            .with_header("location", "http://public.test/hop3")
557            .create();
558        let mock3 = server
559            .mock("GET", "/hop3")
560            .with_status(200)
561            .with_body("ok")
562            .create();
563
564        // `.resolve()` points the SSRF-passing domain "public.test" at the
565        // mock server's real (loopback) address, so the full policy +
566        // resolver stack can be driven end-to-end offline without the
567        // front door or `SsrfSafeResolver` rejecting the mock's actual
568        // loopback IP — proving legitimate multi-hop chains still work.
569        let client = Client::builder()
570            .redirect(FeedHttpClient::redirect_policy())
571            .dns_resolver(Arc::new(SsrfSafeResolver))
572            .resolve("public.test", addr)
573            .build()
574            .unwrap();
575
576        let url = format!("http://public.test:{}/hop1", addr.port());
577        let response = client.get(&url).send().unwrap();
578
579        assert_eq!(response.status().as_u16(), 200);
580        mock1.assert();
581        mock2.assert();
582        mock3.assert();
583    }
584
585    #[expect(
586        clippy::significant_drop_tightening,
587        reason = "the mockito server must outlive the request under test"
588    )]
589    #[test]
590    fn test_redirect_chain_rejects_metadata_after_legitimate_hops() {
591        let mut server = mockito::Server::new();
592        let addr = server.socket_address();
593
594        let mock1 = server
595            .mock("GET", "/hop1")
596            .with_status(302)
597            .with_header("location", "http://public.test/hop2")
598            .create();
599        let mock2 = server
600            .mock("GET", "/hop2")
601            .with_status(302)
602            .with_header("location", "http://169.254.169.254/latest/meta-data/")
603            .create();
604
605        let client = Client::builder()
606            .redirect(FeedHttpClient::redirect_policy())
607            .dns_resolver(Arc::new(SsrfSafeResolver))
608            .resolve("public.test", addr)
609            .build()
610            .unwrap();
611
612        // This is issue #436's actual attack shape: an initial URL and its
613        // first redirect both look legitimate, only the final hop targets
614        // a cloud metadata address.
615        let url = format!("http://public.test:{}/hop1", addr.port());
616        let err = client.get(&url).send().expect_err(
617            "a chain ending at a metadata IP must be rejected, even after legitimate hops",
618        );
619
620        let description = crate::http::error_chain(&err);
621        assert!(
622            description.contains("Link-local address not allowed"),
623            "expected the SSRF rejection reason to survive a multi-hop chain, got: {description}"
624        );
625        mock1.assert();
626        mock2.assert();
627    }
628
629    #[test]
630    fn test_dns_resolver_wired_into_client_rejects_loopback() {
631        let client = Client::builder()
632            .dns_resolver(Arc::new(SsrfSafeResolver))
633            .build()
634            .unwrap();
635
636        // Exercises the resolver as actually attached to a `Client` (not
637        // just `SsrfSafeResolver::resolve` in isolation): "localhost"
638        // resolves via the OS hosts file to 127.0.0.1/::1, both filtered
639        // out, so the connection must fail before any bytes are sent.
640        let result = client.get("http://localhost/").send();
641        assert!(result.is_err());
642    }
643
644    #[test]
645    fn test_custom_user_agent() {
646        let client = FeedHttpClient::new()
647            .unwrap()
648            .with_user_agent("CustomBot/1.0".to_string());
649        assert_eq!(client.user_agent, "CustomBot/1.0");
650    }
651
652    #[test]
653    fn test_user_agent_truncated_to_512_bytes_at_char_boundary() {
654        let client = FeedHttpClient::new()
655            .unwrap()
656            .with_user_agent("é".repeat(300));
657        assert_eq!(client.user_agent, "é".repeat(256));
658
659        let client = FeedHttpClient::new()
660            .unwrap()
661            .with_user_agent("a".repeat(511) + "é");
662        assert_eq!(client.user_agent, "a".repeat(511));
663
664        let exact = "b".repeat(512);
665        let client = FeedHttpClient::new()
666            .unwrap()
667            .with_user_agent(exact.clone());
668        assert_eq!(client.user_agent, exact);
669    }
670
671    #[test]
672    fn test_custom_timeout() {
673        let timeout = Duration::from_mins(1);
674        let client = FeedHttpClient::new().unwrap().with_timeout(timeout);
675        assert_eq!(client.timeout, timeout);
676    }
677
678    #[test]
679    fn test_with_timeout_clamps_absurd_duration() {
680        // `Duration::MAX` would overflow `Instant::now() + timeout` inside
681        // reqwest's blocking wait and panic; it must be clamped instead.
682        let client = FeedHttpClient::new().unwrap().with_timeout(Duration::MAX);
683        assert_eq!(client.timeout, Duration::from_hours(1));
684    }
685
686    #[test]
687    fn test_build_request_applies_configured_timeout() {
688        // Deterministic, network-free complement to the end-to-end tests
689        // below: asserts the timeout is actually wired onto the built
690        // request, not just stored on the struct.
691        let timeout = Duration::from_secs(7);
692        let client = FeedHttpClient::new().unwrap().with_timeout(timeout);
693        let request = client
694            .build_request("https://example.test/feed.xml", HeaderMap::new())
695            .unwrap();
696        assert_eq!(request.timeout(), Some(&timeout));
697    }
698
699    /// A client that reaches the local server at `addr` as `public.test`, so `get`
700    /// runs end to end, including `validate_url`, which rejects loopback addresses.
701    fn local_client(addr: std::net::SocketAddr, timeout: Duration) -> FeedHttpClient {
702        let client = Client::builder()
703            .dns_resolver(Arc::new(SsrfSafeResolver))
704            .resolve("public.test", addr)
705            .build()
706            .unwrap();
707
708        FeedHttpClient {
709            client,
710            user_agent: "test-agent".to_string(),
711            timeout,
712            max_body_size: usize::MAX,
713        }
714    }
715
716    #[expect(
717        clippy::significant_drop_tightening,
718        reason = "the mockito server must outlive the request under test"
719    )]
720    #[test]
721    fn test_url_parsing_bounds_download_by_feed_size_limit() {
722        let mut server = mockito::Server::new();
723        let addr = server.socket_address();
724        let mock = server
725            .mock("GET", "/big")
726            .with_body("a".repeat(100))
727            .create();
728        let options = crate::ParseOptions {
729            limits: ParserLimits {
730                max_feed_size_bytes: 10,
731                ..ParserLimits::default()
732            },
733            ..crate::ParseOptions::default()
734        };
735
736        // The client starts unbounded, so only the options can cap the download.
737        let client = local_client(addr, Duration::from_secs(5));
738        let url = format!("http://public.test:{}/big", addr.port());
739        let message = crate::fetch_and_parse(client, &url, None, None, None, &options)
740            .map(|feed| feed.version)
741            .unwrap_err()
742            .to_string();
743
744        assert!(
745            message.contains("Response body exceeds the limit of 10 bytes"),
746            "{message}"
747        );
748        mock.assert();
749    }
750
751    #[expect(
752        clippy::significant_drop_tightening,
753        reason = "the mockito server must outlive the request under test"
754    )]
755    #[test]
756    fn test_error_status_survives_oversized_body() {
757        let mut server = mockito::Server::new();
758        let addr = server.socket_address();
759        let mock = server
760            .mock("GET", "/missing")
761            .with_status(404)
762            .with_body("a".repeat(100))
763            .expect(2)
764            .create();
765        let url = format!("http://public.test:{}/missing", addr.port());
766        let client = || local_client(addr, Duration::from_secs(5));
767
768        let response = client()
769            .with_max_body_size(10)
770            .get(&url, None, None, None)
771            .unwrap();
772        assert_eq!(response.status, 404);
773        assert_eq!(response.body, b"aaaaaaaaaa");
774
775        let options = crate::ParseOptions {
776            limits: ParserLimits {
777                max_feed_size_bytes: 10,
778                ..ParserLimits::default()
779            },
780            ..crate::ParseOptions::default()
781        };
782        let message = crate::fetch_and_parse(client(), &url, None, None, None, &options)
783            .map(|feed| feed.version)
784            .unwrap_err()
785            .to_string();
786        assert!(message.contains("HTTP 404"), "{message}");
787        mock.assert();
788    }
789
790    // === Timeout enforcement tests (regression for #451) ===
791
792    #[expect(
793        clippy::significant_drop_tightening,
794        reason = "the mockito server must outlive the request under test"
795    )]
796    #[test]
797    fn test_with_timeout_enforced_on_slow_response() {
798        let mut server = mockito::Server::new();
799        let addr = server.socket_address();
800
801        let mock = server
802            .mock("GET", "/slow")
803            .with_chunked_body(|w| {
804                std::thread::sleep(Duration::from_millis(500));
805                w.write_all(b"too slow")
806            })
807            .create();
808
809        let client = local_client(addr, Duration::from_millis(100));
810
811        let url = format!("http://public.test:{}/slow", addr.port());
812        let started = std::time::Instant::now();
813        client
814            .get(&url, None, None, None)
815            .expect_err("a response slower than the configured 100ms timeout must fail");
816        let elapsed = started.elapsed();
817
818        // The mock sleeps 500ms before writing its body. Without the fix,
819        // `self.timeout` is never passed to the request builder, so this
820        // request would block for the full 500ms and succeed. Failing well
821        // before that proves `with_timeout` is actually enforced on `get`.
822        assert!(
823            elapsed < Duration::from_millis(400),
824            "request did not fail until {elapsed:?}; timeout was not enforced"
825        );
826        mock.assert();
827    }
828
829    #[test]
830    #[expect(
831        clippy::significant_drop_tightening,
832        reason = "the mockito server must outlive the request under test"
833    )]
834    fn test_with_timeout_allows_fast_response() {
835        let mut server = mockito::Server::new();
836        let addr = server.socket_address();
837
838        let mock = server
839            .mock("GET", "/fast")
840            .with_status(200)
841            .with_body("ok")
842            .create();
843
844        let client = local_client(addr, Duration::from_secs(5));
845
846        let url = format!("http://public.test:{}/fast", addr.port());
847        let response = client
848            .get(&url, None, None, None)
849            .expect("a response faster than the configured timeout must succeed");
850
851        assert_eq!(response.status, 200);
852        mock.assert();
853    }
854
855    // SSRF protection tests
856    #[test]
857    fn test_reject_localhost_url() {
858        let client = FeedHttpClient::new().unwrap();
859        let result = client.get("http://localhost/feed.xml", None, None, None);
860        assert!(result.is_err());
861        let err_msg = result.err().unwrap().to_string();
862        assert!(err_msg.contains("Localhost domain not allowed"));
863    }
864
865    #[test]
866    fn test_reject_private_ip() {
867        let client = FeedHttpClient::new().unwrap();
868        let result = client.get("http://192.168.1.1/feed.xml", None, None, None);
869        assert!(result.is_err());
870        let err_msg = result.err().unwrap().to_string();
871        assert!(err_msg.contains("Private IP address not allowed"));
872    }
873
874    #[test]
875    fn test_reject_metadata_endpoint() {
876        let client = FeedHttpClient::new().unwrap();
877        let result = client.get("http://169.254.169.254/latest/meta-data/", None, None, None);
878        assert!(result.is_err());
879        let err_msg = result.err().unwrap().to_string();
880        // Should be rejected as AWS metadata endpoint or link-local
881        assert!(err_msg.contains("metadata") || err_msg.contains("Link-local"));
882    }
883
884    #[test]
885    fn test_reject_file_scheme() {
886        let client = FeedHttpClient::new().unwrap();
887        let result = client.get("file:///etc/passwd", None, None, None);
888        assert!(result.is_err());
889        let err_msg = result.err().unwrap().to_string();
890        assert!(err_msg.contains("Unsupported URL scheme"));
891    }
892
893    #[test]
894    fn test_reject_internal_domain() {
895        let client = FeedHttpClient::new().unwrap();
896        let result = client.get("http://server.local/feed.xml", None, None, None);
897        assert!(result.is_err());
898        let err_msg = result.err().unwrap().to_string();
899        assert!(err_msg.contains("Internal domain TLD not allowed"));
900    }
901
902    #[test]
903    fn test_insert_header_valid() {
904        let mut headers = HeaderMap::new();
905        let result = FeedHttpClient::insert_header(
906            &mut headers,
907            USER_AGENT,
908            "TestBot/1.0",
909            HeaderField::UserAgent,
910        );
911        assert!(result.is_ok());
912        assert_eq!(headers.get(USER_AGENT).unwrap(), "TestBot/1.0");
913    }
914
915    #[test]
916    fn test_insert_header_invalid_value() {
917        let mut headers = HeaderMap::new();
918        // Invalid header value with control characters
919        let result = FeedHttpClient::insert_header(
920            &mut headers,
921            USER_AGENT,
922            "Invalid\nHeader",
923            HeaderField::UserAgent,
924        );
925        assert!(matches!(
926            result,
927            Err(FetchError::InvalidHeader {
928                name: HeaderField::UserAgent
929            })
930        ));
931        assert_eq!(
932            result.unwrap_err().to_string(),
933            "Invalid User-Agent header value"
934        );
935    }
936
937    #[test]
938    fn test_insert_header_multiple_headers() {
939        let mut headers = HeaderMap::new();
940
941        FeedHttpClient::insert_header(
942            &mut headers,
943            USER_AGENT,
944            "TestBot/1.0",
945            HeaderField::UserAgent,
946        )
947        .unwrap();
948
949        FeedHttpClient::insert_header(
950            &mut headers,
951            IF_NONE_MATCH,
952            "\"abc\"",
953            HeaderField::IfNoneMatch,
954        )
955        .unwrap();
956
957        assert_eq!(headers.len(), 2);
958        assert_eq!(headers.get(USER_AGENT).unwrap(), "TestBot/1.0");
959        assert_eq!(headers.get(IF_NONE_MATCH).unwrap(), "\"abc\"");
960    }
961}