Skip to main content

libtea_client/
error.rs

1//! Errors from TEA HTTP operations.
2//!
3//! Display text does not include access tokens, API key secrets, or
4//! `Authorization` header values.
5
6use libtea_core::{
7    escape_control_chars, IntegrityOutcome, IntegrityReport, ModelError, PolicyError,
8};
9use thiserror::Error;
10
11/// Failure of a consumer HTTP operation.
12#[derive(Debug, Error)]
13#[non_exhaustive]
14pub enum ClientError {
15    /// The URL was rejected by destination policy.
16    #[error(transparent)]
17    Policy(#[from] PolicyError),
18    /// A TEA document or identifier was not valid.
19    #[error(transparent)]
20    Model(#[from] ModelError),
21    /// JSON that could not be decoded.
22    #[error("JSON parse error: {0}")]
23    Json(String),
24    /// A connection or protocol failure.
25    #[error("transport error: {0}")]
26    Transport(String),
27    /// A response exceeded a configured limit.
28    #[error("response exceeded the configured size limit")]
29    TooLarge,
30    /// Redirects exceeded the configured limit.
31    #[error("too many redirects")]
32    TooManyRedirects,
33    /// A redirect had no usable `Location`.
34    #[error("redirect location is missing or invalid")]
35    BadRedirect,
36    /// The request timed out.
37    #[error("request timed out")]
38    Timeout,
39    /// The server required authentication and no credential was available for that origin.
40    #[error("authentication is required")]
41    AuthenticationRequired,
42    /// The server returned 403. This does not trigger token replacement or failover.
43    #[error("request is not authorized")]
44    Forbidden,
45    /// An HTTP status the operation did not accept.
46    #[error("TEA API status {status}{}", tea_suffix(tea_error))]
47    #[non_exhaustive]
48    Api {
49        /// HTTP status code.
50        status: u16,
51        /// TEA `error` value when the body was a TEA error response.
52        tea_error: Option<String>,
53        /// Optional human-readable message. Not a programmatic contract.
54        message: Option<String>,
55    },
56    /// `/discovery` returned a TEA 404. This is not evidence that no updates exist.
57    #[error("identifier was not resolved ({error})")]
58    #[non_exhaustive]
59    Unresolved {
60        /// TEA error code, preserved even when this client does not know it.
61        error: String,
62        /// Optional diagnostic message.
63        message: Option<String>,
64    },
65    /// Well-known or API discovery attempts were exhausted.
66    #[error("discovery failed during the {stage} stage after {attempts} attempts")]
67    #[non_exhaustive]
68    DiscoveryFailed {
69        /// `well-known` or `api`.
70        stage: &'static str,
71        /// Attempts counted toward the bound.
72        attempts: u32,
73    },
74    /// Declared checksums did not all match the decoded artifact bytes, or at
75    /// least one could not be computed.
76    #[error("artifact integrity was not verified ({outcome:?})")]
77    #[non_exhaustive]
78    Integrity {
79        /// Summary outcome.
80        outcome: IntegrityOutcome,
81        /// Per-algorithm detail.
82        report: IntegrityReport,
83    },
84    /// A local file operation of a streaming download failed (for example the
85    /// destination exists, is a symbolic link, or could not be written).
86    /// *Experimental.* The text names the operation and the I/O error kind.
87    #[error("file error: {0}")]
88    Io(String),
89    /// The server answered a `GET` with `429` or `503` and the retries (which
90    /// honor `Retry-After` up to [`crate::Limits::max_retry_after`]) ran out, or
91    /// the server asked for a longer wait than that limit allows.
92    #[error(
93        "the server asked the client to slow down (HTTP {status}{})",
94        retry_suffix(retry_after_secs)
95    )]
96    #[non_exhaustive]
97    Throttled {
98        /// `429` or `503`.
99        status: u16,
100        /// The wait the server asked for, in seconds, when it said.
101        retry_after_secs: Option<u64>,
102    },
103    /// Offline mode: the response is not in the cache (or is too old), or the
104    /// request cannot be served from a cache at all.
105    #[error("offline: the response is not in the cache")]
106    Offline,
107    /// The token endpoint rejected the credential exchange.
108    #[error("token request failed ({error})")]
109    #[non_exhaustive]
110    Token {
111        /// OAuth error code or HTTP status.
112        error: String,
113    },
114}
115
116fn retry_suffix(seconds: &Option<u64>) -> String {
117    match seconds {
118        Some(seconds) => format!(", retry after {seconds}s"),
119        None => String::new(),
120    }
121}
122
123fn tea_suffix(error: &Option<String>) -> String {
124    match error {
125        Some(code) => format!(" ({code})"),
126        None => String::new(),
127    }
128}
129
130impl From<serde_json::Error> for ClientError {
131    fn from(value: serde_json::Error) -> Self {
132        Self::Json(escape_control_chars(&value.to_string()))
133    }
134}
135
136impl ClientError {
137    pub(crate) fn transport(err: reqwest::Error) -> Self {
138        if err.is_timeout() {
139            return Self::Timeout;
140        }
141        // Prefer structured removal: reqwest's Display appends
142        // ` for url (https://...?secret=...)`. Drop that URL object first.
143        let message = err.without_url().to_string();
144        if message.to_ascii_lowercase().contains("authorization")
145            || message.to_ascii_lowercase().contains("bearer ")
146        {
147            return Self::Transport("request failed".into());
148        }
149        // Residual free-text URLs are rewritten only when the whole
150        // whitespace-bounded span can be parsed; otherwise use a generic
151        // message rather than risk leaving query-value fragments.
152        Self::Transport(escape_control_chars(
153            &crate::transport::sanitize_transport_text(&message),
154        ))
155    }
156}