Skip to main content

feedparser_rs/http/
error.rs

1//! Typed failures of the HTTP fetch path.
2
3use crate::error::UrlParseError;
4use crate::util::ssrf::{SsrfRejection, UrlRejection};
5use std::error::Error;
6use std::fmt;
7use std::io;
8use std::sync::Arc;
9use thiserror::Error;
10
11/// A failure status code: always in `400..=999`.
12///
13/// # Examples
14///
15/// ```
16/// use feedparser_rs::http::HttpStatus;
17///
18/// assert_eq!(HttpStatus::new(404).map(HttpStatus::as_u16), Some(404));
19/// assert!(HttpStatus::new(200).is_none());
20/// ```
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22pub struct HttpStatus(u16);
23
24impl HttpStatus {
25    /// Returns `Some` exactly when `code` is in `400..=999`.
26    #[must_use]
27    pub const fn new(code: u16) -> Option<Self> {
28        match code {
29            400..=999 => Some(Self(code)),
30            _ => None,
31        }
32    }
33
34    /// The numeric status code.
35    #[must_use]
36    pub const fn as_u16(self) -> u16 {
37        self.0
38    }
39}
40
41impl fmt::Display for HttpStatus {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        write!(f, "{}", self.0)
44    }
45}
46
47/// Request header whose value was rejected.
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49#[non_exhaustive]
50pub enum HeaderField {
51    /// `User-Agent`
52    UserAgent,
53    /// `If-None-Match`
54    IfNoneMatch,
55    /// `If-Modified-Since`
56    IfModifiedSince,
57}
58
59impl fmt::Display for HeaderField {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        f.write_str(match self {
62            Self::UserAgent => "User-Agent",
63            Self::IfNoneMatch => "If-None-Match",
64            Self::IfModifiedSince => "If-Modified-Since",
65        })
66    }
67}
68
69/// Formats `error` followed by every error in its `source()` chain, joined by `": "`.
70///
71/// A fetch error's own message can be generic ("HTTP request failed"); the detail sits
72/// further down the chain. The bindings use this to build one complete message.
73///
74/// # Examples
75///
76/// ```
77/// use feedparser_rs::http::{error_chain, validate_url};
78///
79/// let err = validate_url("not a url").unwrap_err();
80/// assert!(error_chain(&err).starts_with("Invalid URL"));
81/// ```
82pub fn error_chain(error: &(dyn Error + 'static)) -> String {
83    use std::fmt::Write as _;
84
85    let mut message = error.to_string();
86    let mut source = error.source();
87    while let Some(err) = source {
88        let _ = write!(message, ": {err}");
89        source = err.source();
90    }
91    message
92}
93
94/// Whether `error` is a timeout, directly or through the error it wraps.
95///
96/// A body read through `reqwest` surfaces as an `io::Error` of kind `Other` wrapping the
97/// `reqwest::Error`, and `io::Error::source` skips that wrapped error.
98fn io_error_is_timeout(error: &io::Error) -> bool {
99    error.kind() == io::ErrorKind::TimedOut
100        || error
101            .get_ref()
102            .and_then(|inner| inner.downcast_ref::<reqwest::Error>())
103            .is_some_and(reqwest::Error::is_timeout)
104}
105
106/// Opaque transport-level failure (connect, TLS, timeout, I/O).
107#[derive(Debug, Clone)]
108pub struct TransportError {
109    source: Arc<dyn Error + Send + Sync>,
110}
111
112impl TransportError {
113    pub(crate) fn new(source: impl Error + Send + Sync + 'static) -> Self {
114        Self {
115            source: Arc::new(source),
116        }
117    }
118
119    /// Whether the failure was a timeout: a `reqwest` timeout or an `io::ErrorKind::TimedOut`
120    /// anywhere in the source chain, including one wrapped by a body read.
121    ///
122    /// # Examples
123    ///
124    /// ```
125    /// use feedparser_rs::http::{FetchError, validate_url};
126    ///
127    /// // A rejected URL never reaches the network, so it is not a transport timeout.
128    /// let err = validate_url("http://127.0.0.1/").unwrap_err();
129    /// let timed_out = match err {
130    ///     FetchError::Transport(transport) => transport.is_timeout(),
131    ///     _ => false,
132    /// };
133    /// assert!(!timed_out);
134    /// ```
135    #[must_use]
136    pub fn is_timeout(&self) -> bool {
137        let root: &(dyn Error + 'static) = &*self.source;
138        std::iter::successors(Some(root), |err| (*err).source()).any(|err| {
139            err.downcast_ref::<reqwest::Error>()
140                .is_some_and(reqwest::Error::is_timeout)
141                || err
142                    .downcast_ref::<io::Error>()
143                    .is_some_and(io_error_is_timeout)
144        })
145    }
146}
147
148impl fmt::Display for TransportError {
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        self.source.fmt(f)
151    }
152}
153
154/// `Display` prints the wrapped error's own message, so `source` continues with that
155/// error's source: a chain reporter then prints each message once.
156impl Error for TransportError {
157    fn source(&self) -> Option<&(dyn Error + 'static)> {
158        self.source.source()
159    }
160}
161
162/// Failure while fetching a feed over HTTP.
163///
164/// Match on the variant to react to a specific failure; the enum is `#[non_exhaustive]`.
165///
166/// # Examples
167///
168/// ```
169/// use feedparser_rs::http::{FetchError, validate_url};
170///
171/// let err = validate_url("http://127.0.0.1/feed.xml").unwrap_err();
172/// assert!(matches!(err, FetchError::BlockedAddress { .. }));
173/// ```
174#[derive(Debug, Clone, Error)]
175#[non_exhaustive]
176pub enum FetchError {
177    /// The server answered with a failure status.
178    #[error("HTTP {status} for URL: {url}")]
179    Status {
180        /// The failure status.
181        status: HttpStatus,
182        /// Final URL after redirects.
183        url: String,
184    },
185    /// The URL, a redirect hop or a resolved address was rejected by SSRF protection.
186    #[error("{reason}")]
187    BlockedAddress {
188        /// Why the target was rejected.
189        reason: SsrfRejection,
190    },
191    /// More redirects than allowed.
192    #[error("Too many redirects")]
193    TooManyRedirects,
194    /// The body exceeded the configured size limit.
195    #[error("Response body exceeds the limit of {limit} bytes")]
196    BodyTooLarge {
197        /// The configured limit in bytes.
198        limit: usize,
199    },
200    /// A request header value was invalid.
201    #[error("Invalid {name} header value")]
202    InvalidHeader {
203        /// The offending header.
204        name: HeaderField,
205    },
206    /// The URL could not be parsed.
207    #[error("Invalid URL: {0}")]
208    InvalidUrl(UrlParseError),
209    /// Any other transport failure.
210    #[error("HTTP request failed")]
211    Transport(#[source] TransportError),
212}
213
214impl From<UrlRejection> for FetchError {
215    fn from(rejection: UrlRejection) -> Self {
216        match rejection {
217            UrlRejection::Invalid(e) => Self::InvalidUrl(UrlParseError::new(e)),
218            UrlRejection::Blocked(reason) => Self::BlockedAddress { reason },
219        }
220    }
221}
222
223impl FetchError {
224    /// Classifies a `reqwest` failure.
225    ///
226    /// The redirect policy and the DNS resolver attach a typed [`FetchError`] to the
227    /// error chain; the first one found is returned. Anything else is a transport
228    /// failure.
229    pub(crate) fn from_request_error(error: reqwest::Error) -> Self {
230        let root: &(dyn Error + 'static) = &error;
231        let typed = std::iter::successors(Some(root), |err| (*err).source())
232            .find_map(|err| err.downcast_ref::<Self>().cloned());
233        typed.unwrap_or_else(|| Self::Transport(TransportError::new(error)))
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240
241    #[test]
242    fn http_status_accepts_only_400_to_999() {
243        assert!(HttpStatus::new(399).is_none());
244        assert_eq!(HttpStatus::new(400).map(HttpStatus::as_u16), Some(400));
245        assert_eq!(HttpStatus::new(999).map(HttpStatus::as_u16), Some(999));
246        assert!(HttpStatus::new(1000).is_none());
247    }
248
249    #[test]
250    fn transport_timeout_is_detected_through_the_source_chain() {
251        let timed_out = TransportError::new(io::Error::new(io::ErrorKind::TimedOut, "slow"));
252        assert!(timed_out.is_timeout());
253        let refused = TransportError::new(io::Error::new(io::ErrorKind::ConnectionRefused, "no"));
254        assert!(!refused.is_timeout());
255    }
256
257    #[expect(
258        clippy::significant_drop_tightening,
259        reason = "the mockito server must outlive the request under test"
260    )]
261    #[test]
262    fn typed_error_in_the_chain_is_recovered_without_wrapping() {
263        let client = reqwest::blocking::Client::builder()
264            .redirect(reqwest::redirect::Policy::custom(|attempt| {
265                attempt.error(FetchError::TooManyRedirects)
266            }))
267            .build()
268            .expect("client");
269        let mut server = mockito::Server::new();
270        let _mock = server
271            .mock("GET", "/r")
272            .with_status(302)
273            .with_header("location", "/r2")
274            .create();
275        let err = client
276            .get(format!("{}/r", server.url()))
277            .send()
278            .expect_err("redirect is rejected");
279        assert!(matches!(
280            FetchError::from_request_error(err),
281            FetchError::TooManyRedirects
282        ));
283    }
284
285    #[expect(
286        clippy::significant_drop_tightening,
287        reason = "the mockito server must outlive the request under test"
288    )]
289    #[test]
290    fn body_read_timeout_is_detected() {
291        use std::io::Read as _;
292        use std::time::Duration;
293
294        let mut server = mockito::Server::new();
295        let _mock = server
296            .mock("GET", "/slow-body")
297            .with_chunked_body(|w| {
298                w.write_all(b"<rss>")?;
299                w.flush()?;
300                std::thread::sleep(Duration::from_millis(600));
301                w.write_all(b"</rss>")
302            })
303            .create();
304        let client = reqwest::blocking::Client::builder()
305            .timeout(Duration::from_millis(200))
306            .build()
307            .expect("client");
308        let response = client
309            .get(format!("{}/slow-body", server.url()))
310            .send()
311            .expect("headers arrive before the timeout");
312        let mut bytes = Vec::new();
313        let err = response
314            .take(1 << 20)
315            .read_to_end(&mut bytes)
316            .expect_err("the body read times out");
317
318        assert!(TransportError::new(err).is_timeout());
319    }
320
321    #[test]
322    fn untyped_request_error_is_a_transport_failure() {
323        let client = reqwest::blocking::Client::new();
324        let err = client
325            .get("http://127.0.0.1:1/")
326            .send()
327            .expect_err("nothing listens on port 1");
328        assert!(matches!(
329            FetchError::from_request_error(err),
330            FetchError::Transport(_)
331        ));
332    }
333}