Skip to main content

crypto_service_sdk/
error.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2//! The error every call returns: an RFC 9457 problem from the server, a
3//! request that got no answer, or an answer that did not decode.
4//!
5//! No message here carries a credential, a key, a plaintext or a body:
6//! an [`ApiError`] shows the problem's status, type and title (which the
7//! server writes for the client), a [`TransportError`] a fixed text, and a
8//! [`DecodeError`] the position of the fault, never the value found there.
9
10use std::fmt;
11
12use serde::{Deserialize, Serialize};
13use serde_json::{Map, Value};
14
15/// What went wrong with a call. Every variant wraps a type of its own, so
16/// a caller can match the kind and keep the details.
17#[derive(Debug, thiserror::Error)]
18#[non_exhaustive]
19pub enum Error {
20    /// The server answered with a status other than 2xx.
21    #[error(transparent)]
22    Api(Box<ApiError>),
23    /// No answer arrived: the connection failed, an attempt timed out, or
24    /// the overall deadline passed.
25    #[error(transparent)]
26    Transport(#[from] TransportError),
27    /// A 2xx answer did not have the documented shape.
28    #[error(transparent)]
29    Decode(#[from] DecodeError),
30    /// The client could not be built, or a request could not be formed
31    /// from its options (for example a base URL that is not a URL).
32    #[error("invalid client configuration: {0}")]
33    Config(&'static str),
34}
35
36impl From<ApiError> for Error {
37    fn from(error: ApiError) -> Self {
38        Error::Api(Box::new(error))
39    }
40}
41
42impl Error {
43    /// The HTTP status of an [`Error::Api`]; `None` for the other kinds.
44    #[must_use]
45    pub fn status(&self) -> Option<u16> {
46        match self {
47            Error::Api(api) => Some(api.status),
48            _ => None,
49        }
50    }
51
52    /// The problem of an [`Error::Api`]; `None` for the other kinds.
53    #[must_use]
54    pub fn problem(&self) -> Option<&Problem> {
55        match self {
56            Error::Api(api) => Some(&api.problem),
57            _ => None,
58        }
59    }
60
61    /// Whether this is a [`TransportError`] caused by a timeout or the
62    /// deadline.
63    #[must_use]
64    pub fn is_timeout(&self) -> bool {
65        matches!(self, Error::Transport(t) if t.timed_out)
66    }
67}
68
69/// A non-2xx answer, with its RFC 9457 problem.
70///
71/// A body that is not a problem (an HTML page from a proxy, an empty
72/// body) becomes an `about:blank` problem for the status, so
73/// [`ApiError::problem`] always has the problem shape.
74#[derive(Debug, Clone, PartialEq)]
75pub struct ApiError {
76    /// The HTTP status code.
77    pub status: u16,
78    /// The problem the server sent, or the `about:blank` stand-in.
79    pub problem: Problem,
80}
81
82impl ApiError {
83    /// The problem, as the server sent it.
84    #[must_use]
85    pub fn problem(&self) -> &Problem {
86        &self.problem
87    }
88
89    /// The problem's `code` (for example `KEY_NOT_FOUND`), when it has one.
90    #[must_use]
91    pub fn code(&self) -> Option<&str> {
92        self.problem.code.as_deref()
93    }
94}
95
96impl fmt::Display for ApiError {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        write!(
99            f,
100            "crypto-service API error: HTTP {} {} ({})",
101            self.status, self.problem.title, self.problem.kind
102        )
103    }
104}
105
106impl std::error::Error for ApiError {}
107
108/// RFC 9457 problem details (`application/problem+json`).
109#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
110#[serde(rename_all = "camelCase")]
111pub struct Problem {
112    /// Problem type: `urn:crypto-service:problem:<slug>`, or `about:blank`.
113    #[serde(rename = "type", default = "about_blank")]
114    pub kind: String,
115    /// Summary of the problem type.
116    #[serde(default)]
117    pub title: String,
118    /// HTTP status code.
119    #[serde(default)]
120    pub status: u16,
121    /// Explanation of this occurrence, written by the server for the
122    /// client.
123    pub detail: String,
124    /// Request path, without the query string.
125    #[serde(default, skip_serializing_if = "Option::is_none")]
126    pub instance: Option<String>,
127    /// Error code from crypto-lib, the key store or a KMS provider (for
128    /// example `INVALID_HEX`, `KEY_NOT_FOUND`).
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub code: Option<String>,
131    /// Each field that failed validation (`validation-failed`).
132    #[serde(default, skip_serializing_if = "Vec::is_empty")]
133    pub errors: Vec<ValidationError>,
134    /// Requests a tenant may make per minute (tenant quota).
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub limit: Option<u64>,
137    /// Seconds until the tenant quota resets.
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub reset_seconds: Option<u64>,
140    /// Any other extension member.
141    #[serde(flatten)]
142    pub extensions: Map<String, Value>,
143}
144
145/// One field that failed validation.
146#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
147pub struct ValidationError {
148    /// The field, as a JSON pointer or a body field name.
149    pub field: String,
150    /// Why it failed.
151    pub message: String,
152}
153
154fn about_blank() -> String {
155    String::from("about:blank")
156}
157
158impl Problem {
159    /// The problem a non-2xx `body` carries: the body itself when it is a
160    /// JSON object with a string `detail`, with any missing `type`, `title`
161    /// or `status` filled in; otherwise an `about:blank` problem for
162    /// `status`.
163    #[must_use]
164    pub fn from_body(status: u16, body: &[u8]) -> Self {
165        match serde_json::from_slice::<Problem>(body) {
166            Ok(mut problem) => {
167                if problem.title.is_empty() {
168                    problem.title = reason(status);
169                }
170                if problem.status == 0 {
171                    problem.status = status;
172                }
173                problem
174            }
175            Err(_) => Self::blank(status),
176        }
177    }
178
179    /// The `about:blank` problem for a status without a problem body.
180    #[must_use]
181    pub fn blank(status: u16) -> Self {
182        Problem {
183            kind: about_blank(),
184            title: reason(status),
185            status,
186            detail: format!("The server answered {status} without a problem body"),
187            instance: None,
188            code: None,
189            errors: Vec::new(),
190            limit: None,
191            reset_seconds: None,
192            extensions: Map::new(),
193        }
194    }
195}
196
197/// The canonical reason phrase of `status`, or `HTTP error`.
198fn reason(status: u16) -> String {
199    http::StatusCode::from_u16(status)
200        .ok()
201        .and_then(|code| code.canonical_reason())
202        .unwrap_or("HTTP error")
203        .to_owned()
204}
205
206/// No answer arrived.
207#[derive(Debug, thiserror::Error)]
208#[error("{message}")]
209pub struct TransportError {
210    /// Whether the attempt's timeout or the call's deadline ended it.
211    pub timed_out: bool,
212    message: &'static str,
213    #[source]
214    source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
215}
216
217impl TransportError {
218    /// A failure with `source` as its cause; `timed_out` says whether a
219    /// timeout ended it. For custom [`Transport`](crate::Transport)s.
220    pub fn new<E>(source: E, timed_out: bool) -> Self
221    where
222        E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
223    {
224        TransportError {
225            timed_out,
226            message: if timed_out {
227                "request timed out"
228            } else {
229                "network error"
230            },
231            source: Some(source.into()),
232        }
233    }
234
235    /// An attempt that ran past the per-attempt timeout.
236    pub(crate) fn attempt_timeout() -> Self {
237        TransportError {
238            timed_out: true,
239            message: "request timed out",
240            source: None,
241        }
242    }
243
244    /// A call that ran past its deadline.
245    pub(crate) fn deadline() -> Self {
246        TransportError {
247            timed_out: true,
248            message: "deadline exceeded",
249            source: None,
250        }
251    }
252}
253
254/// A 2xx body that did not decode. It names where the fault is, never the
255/// value found there, which could be a key or a plaintext.
256#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
257#[error("response body could not be decoded ({category} error at line {line}, column {column})")]
258pub struct DecodeError {
259    category: &'static str,
260    line: usize,
261    column: usize,
262}
263
264impl DecodeError {
265    /// The 1-based line of the fault, or 0 when it is not at a position.
266    #[must_use]
267    pub fn line(&self) -> usize {
268        self.line
269    }
270
271    /// The 1-based column of the fault, or 0 when it is not at a position.
272    #[must_use]
273    pub fn column(&self) -> usize {
274        self.column
275    }
276}
277
278impl From<serde_json::Error> for DecodeError {
279    fn from(error: serde_json::Error) -> Self {
280        use serde_json::error::Category;
281        DecodeError {
282            category: match error.classify() {
283                Category::Io => "io",
284                Category::Syntax => "syntax",
285                Category::Data => "data",
286                Category::Eof => "eof",
287            },
288            line: error.line(),
289            column: error.column(),
290        }
291    }
292}
293
294#[cfg(test)]
295mod tests;