Skip to main content

scion_http3/
error.rs

1// Copyright 2026 Anapaya Systems
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//   http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The error taxonomy of the HTTP/3 client.
16//!
17//! All request-path operations ([`Client::request`](crate::Client::request)
18//! and friends, and body collection on [`Response`](crate::Response)) share
19//! one failure domain and therefore one error type, [`Error`]: whatever the
20//! operation, the caller's decisions are the same, i.e., retry, fix the request,
21//! or give up, and [`Error::is_retryable`] answers the first one directly.
22//! Constructing a [`Request`](crate::Request) is the exception. It fails with
23//! the more specific [`BuildRequestError`] before any I/O happens.
24
25use std::{borrow::Cow, error::Error as StdError, fmt, time::Duration};
26
27use scion_quic::{
28    h3::client::{
29        CollectError, CollectToStringError, EstablishError, RequestError as H3RequestError,
30    },
31    reexport::squiche,
32};
33use scion_stack::{resolver::ResolveError, stack::ScionSocketBindError};
34
35/// The phase of a request during which a timeout fired.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37#[non_exhaustive]
38pub enum TimeoutPhase {
39    /// Establishing a connection to the origin (bounded by
40    /// [`Config::with_connect_timeout`](crate::Config::with_connect_timeout)).
41    Connect,
42    /// Waiting for the response head (bounded by
43    /// [`Config::with_request_timeout`](crate::Config::with_request_timeout)
44    /// or the per-request override).
45    Request,
46    /// Collecting the response body (bounded by the remainder of the request
47    /// timeout).
48    ///
49    /// That remainder shrinks while the caller holds the
50    /// [`Response`](crate::Response), so this can also mean "the response was
51    /// held too long before being collected" rather than "the body was slow".
52    Body,
53}
54
55impl fmt::Display for TimeoutPhase {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        match self {
58            TimeoutPhase::Connect => write!(f, "connect"),
59            TimeoutPhase::Request => write!(f, "request"),
60            TimeoutPhase::Body => write!(f, "response body collection"),
61        }
62    }
63}
64
65/// Any failure on the request path.
66///
67/// The variants follow the phases of a request: building connectivity,
68/// resolving the origin, connecting to it, and exchanging the request and
69/// response. [`is_retryable`](Self::is_retryable) classifies each error once,
70/// so callers branch on that instead of re-deriving the answer from the
71/// variant.
72#[derive(Debug, thiserror::Error)]
73#[non_exhaustive]
74pub enum Error {
75    /// Building SCION connectivity (the stack or the resolver) failed.
76    #[error("failed to build SCION connectivity")]
77    StackBuild {
78        /// Whether retrying may succeed (all underlying failures were
79        /// transient).
80        retryable: bool,
81        /// The underlying cause.
82        #[source]
83        source: Box<dyn StdError + Send + Sync>,
84    },
85    /// SCION name resolution for the origin's host failed: the DNS lookup
86    /// itself failed, or the host has no valid TSAR TXT records.
87    #[error("SCION name resolution failed for {host}")]
88    Resolution {
89        /// The host that failed to resolve.
90        host: String,
91        /// Whether retrying may succeed (the lookup failed, as opposed to the
92        /// host having no valid records).
93        retryable: bool,
94        /// The underlying resolver error.
95        #[source]
96        source: ResolveError,
97    },
98    /// No connection to the origin could be established: every candidate
99    /// address failed with a socket, QUIC, or handshake error.
100    #[error("could not connect to {host}:{port}")]
101    Connect {
102        /// The origin's host.
103        host: String,
104        /// The origin's port.
105        port: u16,
106        /// The underlying cause(s).
107        #[source]
108        source: Box<dyn StdError + Send + Sync>,
109    },
110    /// The TLS layer rejected the origin: every candidate negotiated an ALPN
111    /// other than HTTP/3.
112    ///
113    /// A certificate that fails to validate does *not* land here: the transport
114    /// reports it as a failed handshake, indistinguishable from an unreachable
115    /// peer, so it surfaces as [`Connect`](Self::Connect).
116    #[error("TLS failure connecting to {host}")]
117    Tls {
118        /// The origin's host (the certificate-validation identity).
119        host: String,
120        /// The underlying cause.
121        #[source]
122        source: Box<dyn StdError + Send + Sync>,
123    },
124    /// The peer reset the request stream.
125    #[error("stream reset by peer (code {code})")]
126    StreamReset {
127        /// The HTTP/3 application error code carried by the reset.
128        code: u64,
129    },
130    /// An HTTP/3 protocol violation occurred on an established connection.
131    #[error("HTTP/3 protocol error")]
132    Protocol {
133        /// The underlying cause.
134        #[source]
135        source: Box<dyn StdError + Send + Sync>,
136    },
137    /// The peer's concurrent-stream limit is exhausted; the request was never
138    /// sent.
139    #[error("peer's concurrent stream limit reached")]
140    ConnectionLimit,
141    /// The response body exceeded the size limit passed to
142    /// [`Response::bytes`](crate::Response::bytes) or
143    /// [`Response::text`](crate::Response::text).
144    #[error("response body exceeded {limit} bytes")]
145    BodyTooLarge {
146        /// The limit that was exceeded.
147        limit: usize,
148    },
149    /// A deadline expired.
150    #[error("{phase} timed out after {timeout:?}")]
151    Timeout {
152        /// The phase of the request that timed out.
153        phase: TimeoutPhase,
154        /// The deadline that expired.
155        timeout: Duration,
156    },
157    /// The response body is not valid UTF-8 (only from
158    /// [`Response::text`](crate::Response::text)).
159    #[error("response body is not valid UTF-8")]
160    InvalidBody {
161        /// The underlying UTF-8 error.
162        #[source]
163        source: std::string::FromUtf8Error,
164    },
165    /// The request is invalid (malformed URL, unsupported scheme, missing
166    /// host, or an invalid header).
167    #[error("invalid request: {reason}")]
168    InvalidRequest {
169        /// What is wrong with the request.
170        reason: Cow<'static, str>,
171    },
172    /// The client has been closed with [`Client::close`](crate::Client::close).
173    #[error("client is closed")]
174    Closed,
175}
176
177impl Error {
178    /// Whether retrying the request may succeed.
179    ///
180    /// Transient conditions (connectivity, timeouts, stream resets, stream
181    /// limits) are retryable. Deterministic ones (TLS rejection, protocol
182    /// violations, invalid requests, oversized bodies, a closed client) are
183    /// not. For [`StackBuild`](Self::StackBuild) and
184    /// [`Resolution`](Self::Resolution) the answer is decided when the error
185    /// is constructed, from the transience of the underlying failures.
186    ///
187    /// A retryable error never implies the request did not reach the server:
188    /// only the caller knows whether its request is idempotent.
189    #[must_use]
190    pub fn is_retryable(&self) -> bool {
191        match self {
192            Error::StackBuild { retryable, .. } | Error::Resolution { retryable, .. } => *retryable,
193            Error::Connect { .. }
194            | Error::StreamReset { .. }
195            | Error::ConnectionLimit
196            | Error::Timeout { .. } => true,
197            Error::Tls { .. }
198            | Error::Protocol { .. }
199            | Error::BodyTooLarge { .. }
200            | Error::InvalidBody { .. }
201            | Error::InvalidRequest { .. }
202            | Error::Closed => false,
203        }
204    }
205
206    /// Maps a transport-level request error to the taxonomy, attributing
207    /// connection-level failures to `host:port`.
208    pub(crate) fn from_h3_request_error(host: &str, port: u16, err: H3RequestError) -> Error {
209        match err {
210            H3RequestError::Establish(e) => {
211                Error::from_attempt_errors(host, port, vec![AttemptError::Establish(e)])
212            }
213            H3RequestError::Reset(code) => Error::StreamReset { code },
214            // Both shapes mean the same thing to the caller: the peer's
215            // concurrent-stream limit has no room for this request.
216            H3RequestError::StreamBlocked
217            | H3RequestError::H3(squiche::h3::Error::TransportError(squiche::Error::StreamLimit)) => {
218                Error::ConnectionLimit
219            }
220            H3RequestError::H3(_) => {
221                Error::Protocol {
222                    source: Box::new(err),
223                }
224            }
225            H3RequestError::ConnectionClosed | H3RequestError::LocallyClosed => {
226                Error::Connect {
227                    host: host.to_string(),
228                    port,
229                    source: Box::new(err),
230                }
231            }
232        }
233    }
234
235    /// Maps the failures of an attempt sequence to the taxonomy: TLS-level
236    /// rejections become [`Error::Tls`], everything else [`Error::Connect`].
237    ///
238    /// The classification is deliberately unanimous rather than "any": one
239    /// candidate rejecting the ALPN says nothing about the others, which may
240    /// have failed for transient reasons and may well work on a retry. Only
241    /// when *every* candidate rejected us is the failure deterministic, and
242    /// therefore not worth retrying.
243    pub(crate) fn from_attempt_errors(host: &str, port: u16, errors: Vec<AttemptError>) -> Error {
244        // XXX(shitz): A chain that fails against the trust anchors should be an
245        // `Error::Tls` too, but cannot be recognized here: scion-quic's
246        // handshake loop discards the cause and reports
247        // `EstablishError::Handshake`, which is what an unreachable peer also
248        // produces. Such failures are therefore reported as retryable
249        // `Error::Connect`. A chain that a caller-supplied verifier refuses is
250        // recognized, because that path keeps its cause.
251        let all_tls = !errors.is_empty()
252            && errors.iter().all(|e| {
253                matches!(
254                    e,
255                    AttemptError::Establish(
256                        EstablishError::AlpnMismatch | EstablishError::CertificateRejected(_)
257                    )
258                )
259            });
260        let source = Box::new(AllAttemptsFailed { errors });
261        if all_tls {
262            Error::Tls {
263                host: host.to_string(),
264                source,
265            }
266        } else {
267            Error::Connect {
268                host: host.to_string(),
269                port,
270                source,
271            }
272        }
273    }
274
275    /// Maps a resolver error to [`Error::Resolution`], taking retryability from
276    /// the resolver's own classification: a failed lookup may succeed later, a
277    /// host without valid TSAR records will not.
278    pub(crate) fn from_resolve_error(host: &str, err: ResolveError) -> Error {
279        let retryable = err.is_transient();
280        Error::Resolution {
281            host: host.to_string(),
282            retryable,
283            source: err,
284        }
285    }
286
287    /// Maps a body-collection error to the taxonomy.
288    pub(crate) fn from_collect_error(err: CollectError, limit: Option<usize>) -> Error {
289        match err {
290            CollectError::TooLarge => {
291                Error::BodyTooLarge {
292                    limit: limit.unwrap_or(usize::MAX),
293                }
294            }
295            _ => {
296                Error::Protocol {
297                    source: Box::new(err),
298                }
299            }
300        }
301    }
302
303    /// Maps a body-to-string collection error to the taxonomy.
304    pub(crate) fn from_collect_to_string_error(
305        err: CollectToStringError,
306        limit: Option<usize>,
307    ) -> Error {
308        match err {
309            CollectToStringError::TooLarge => {
310                Error::BodyTooLarge {
311                    limit: limit.unwrap_or(usize::MAX),
312                }
313            }
314            CollectToStringError::Utf8(source) => Error::InvalidBody { source },
315            CollectToStringError::H3(_) => {
316                Error::Protocol {
317                    source: Box::new(err),
318                }
319            }
320        }
321    }
322}
323
324impl From<BuildRequestError> for Error {
325    /// An invalid request is an [`Error::InvalidRequest`], so the convenience
326    /// entry points ([`Client::get`](crate::Client::get),
327    /// [`Client::post`](crate::Client::post)) report builder failures through
328    /// the same taxonomy as the rest of the request path.
329    fn from(error: BuildRequestError) -> Self {
330        Error::InvalidRequest {
331            reason: error.to_string().into(),
332        }
333    }
334}
335
336/// One failed connection attempt: binding the socket, or establishing the
337/// connection over it.
338#[derive(Debug, thiserror::Error)]
339pub(crate) enum AttemptError {
340    /// Binding a fresh socket for the attempt failed.
341    #[error("binding a socket failed")]
342    Bind(#[source] ScionSocketBindError),
343    /// Establishing the connection failed.
344    #[error("establishing the connection failed")]
345    Establish(#[source] EstablishError),
346}
347
348/// Aggregate of the failures of one attempt sequence, in completion order.
349/// The [`Error::Connect`] / [`Error::Tls`] source when every candidate
350/// failed.
351#[derive(Debug)]
352struct AllAttemptsFailed {
353    errors: Vec<AttemptError>,
354}
355
356impl fmt::Display for AllAttemptsFailed {
357    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
358        write!(
359            f,
360            "all {} connection attempt(s) failed: ",
361            self.errors.len()
362        )?;
363        for (i, err) in self.errors.iter().enumerate() {
364            if i > 0 {
365                write!(f, "; ")?;
366            }
367            write!(f, "{err}")?;
368        }
369        Ok(())
370    }
371}
372
373impl StdError for AllAttemptsFailed {
374    fn source(&self) -> Option<&(dyn StdError + 'static)> {
375        self.errors.first().map(|e| e as &(dyn StdError + 'static))
376    }
377}
378
379/// A [`Request`](crate::Request) could not be built.
380#[derive(Debug, thiserror::Error)]
381#[non_exhaustive]
382pub enum BuildRequestError {
383    /// No URL was provided to the builder.
384    #[error("no URL was provided")]
385    MissingUrl,
386    /// The URL could not be parsed.
387    #[error("invalid URL")]
388    InvalidUrl {
389        /// The underlying parse error.
390        #[source]
391        source: Box<dyn StdError + Send + Sync>,
392    },
393    /// The URL's scheme is not `https`. This is an HTTP/3-only client;
394    /// requests are never sent over cleartext or fall back to TCP.
395    #[error("unsupported URL scheme `{scheme}`, only `https` is supported")]
396    UnsupportedScheme {
397        /// The offending scheme.
398        scheme: String,
399    },
400    /// The URL has no host.
401    #[error("URL has no host")]
402    MissingHost,
403    /// The URL contains userinfo (`user:password@host`). HTTP/3 forbids
404    /// userinfo in `:authority` (RFC 9114 ยง4.3.1), and sending it would leak
405    /// the credentials on the wire; pass credentials in an `authorization`
406    /// header instead.
407    #[error("URL must not contain userinfo (credentials)")]
408    UserinfoNotAllowed,
409    /// A header name or value is invalid.
410    #[error("invalid header")]
411    InvalidHeader {
412        /// The underlying cause.
413        #[source]
414        source: Box<dyn StdError + Send + Sync>,
415    },
416    /// An empty target list was provided. Targets assert "resolution returned
417    /// exactly this", and an empty resolution result is an error, not a
418    /// wildcard.
419    #[error("target list must not be empty")]
420    EmptyTargets,
421}
422
423#[cfg(test)]
424mod tests {
425    use scion_quic::quic::cert_verifier::CertRejected;
426
427    use super::*;
428
429    #[test]
430    fn retryable_classification() {
431        let retryable = [
432            Error::StackBuild {
433                retryable: true,
434                source: "boom".into(),
435            },
436            Error::Connect {
437                host: "example.org".into(),
438                port: 443,
439                source: "boom".into(),
440            },
441            Error::StreamReset { code: 0x10c },
442            Error::ConnectionLimit,
443            Error::Timeout {
444                phase: TimeoutPhase::Request,
445                timeout: Duration::from_secs(1),
446            },
447        ];
448        for err in retryable {
449            assert!(err.is_retryable(), "{err}");
450        }
451
452        let not_retryable = [
453            Error::StackBuild {
454                retryable: false,
455                source: "boom".into(),
456            },
457            Error::Tls {
458                host: "example.org".into(),
459                source: "boom".into(),
460            },
461            Error::Protocol {
462                source: "boom".into(),
463            },
464            Error::BodyTooLarge { limit: 16 },
465            Error::InvalidRequest {
466                reason: "bad".into(),
467            },
468            Error::Closed,
469        ];
470        for err in not_retryable {
471            assert!(!err.is_retryable(), "{err}");
472        }
473    }
474
475    #[test]
476    fn resolution_retryability_follows_failure_kind() {
477        let lookup = Error::from_resolve_error(
478            "example.org",
479            ResolveError::DnsLookup("timed out".to_string()),
480        );
481        assert!(lookup.is_retryable());
482
483        let no_entries = Error::from_resolve_error(
484            "example.org",
485            ResolveError::NoValidEntries {
486                domain: "example.org".to_string(),
487                invalid_entries: vec![],
488            },
489        );
490        assert!(!no_entries.is_retryable());
491    }
492
493    #[test]
494    fn establish_errors_map_to_tls_only_when_uniform() {
495        let tls = Error::from_attempt_errors(
496            "example.org",
497            443,
498            vec![
499                AttemptError::Establish(EstablishError::AlpnMismatch),
500                AttemptError::Establish(EstablishError::AlpnMismatch),
501            ],
502        );
503        assert!(matches!(tls, Error::Tls { .. }));
504
505        let mixed = Error::from_attempt_errors(
506            "example.org",
507            443,
508            vec![
509                AttemptError::Establish(EstablishError::AlpnMismatch),
510                AttemptError::Establish(EstablishError::Handshake),
511            ],
512        );
513        assert!(matches!(mixed, Error::Connect { .. }));
514    }
515
516    #[test]
517    fn a_rejected_certificate_is_a_tls_error() {
518        // A verifier that refuses the chain refuses it again on a retry, so the
519        // failure is deterministic rather than a connect failure to retry.
520        let rejected = Error::from_attempt_errors(
521            "example.org",
522            443,
523            vec![AttemptError::Establish(
524                EstablishError::CertificateRejected(CertRejected::new("not the pinned server")),
525            )],
526        );
527        assert!(matches!(rejected, Error::Tls { .. }));
528        assert!(!rejected.is_retryable());
529        assert!(rejected.to_string().contains("example.org"));
530    }
531
532    #[test]
533    fn stream_level_request_errors_do_not_become_connect() {
534        let reset = Error::from_h3_request_error("example.org", 443, H3RequestError::Reset(7));
535        assert!(matches!(reset, Error::StreamReset { code: 7 }));
536
537        let blocked =
538            Error::from_h3_request_error("example.org", 443, H3RequestError::StreamBlocked);
539        assert!(matches!(blocked, Error::ConnectionLimit));
540    }
541}