Skip to main content

passalong_https/
client.rs

1//! The HTTP client: TLS as [`crate::tls`] sets it up, the API key as a
2//! bearer token, an `X-Request-Id` on every request, and the retries of
3//! [`crate::error`].
4
5use std::time::Duration;
6
7use passalong_core::api_key::ApiKey;
8use passalong_core::config::HttpsConfig;
9use passalong_core::random::{RandomSource, StdRandom};
10use reqwest::header::RETRY_AFTER;
11use serde::de::DeserializeOwned;
12
13use crate::api::{Viewer, Workspace};
14use crate::error::{self, HttpsError, Next, Problem};
15use crate::tls;
16
17/// How long a connection, TLS included, may take to open.
18pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
19/// How long the server may stay silent in the middle of an answer.
20pub const READ_TIMEOUT: Duration = Duration::from_secs(60);
21
22/// A client of one server, with one API key.
23pub struct Client {
24    http: reqwest::Client,
25    base: String,
26    key: ApiKey,
27}
28
29impl std::fmt::Debug for Client {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        f.debug_struct("Client")
32            .field("base", &self.base)
33            .field("key", &self.key)
34            .finish_non_exhaustive()
35    }
36}
37
38impl Client {
39    /// A client for the server `config` names, authenticating with `key`.
40    ///
41    /// # Errors
42    ///
43    /// [`HttpsError::Transport`] when TLS cannot be set up.
44    pub fn new(config: &HttpsConfig, key: ApiKey) -> Result<Self, HttpsError> {
45        let setup = |reason: String| HttpsError::Transport {
46            url: config.url.clone(),
47            reason,
48            retryable: false,
49        };
50        let tls = tls::client_config(config.tls_pin)
51            .map_err(|err| setup(format!("setting up TLS: {err}")))?;
52        let http = reqwest::Client::builder()
53            .tls_backend_preconfigured(tls)
54            .https_only(true)
55            .connect_timeout(CONNECT_TIMEOUT)
56            .read_timeout(READ_TIMEOUT)
57            .user_agent(format!("passalong/{}", passalong_core::VERSION))
58            .build()
59            .map_err(|err| setup(chain(&err)))?;
60        Ok(Self {
61            http,
62            base: config.url.clone(),
63            key,
64        })
65    }
66
67    /// The API key in use.
68    pub fn key(&self) -> &ApiKey {
69        &self.key
70    }
71
72    /// The URL of the API route `path`, such as `/items`.
73    pub fn url(&self, path: &str) -> String {
74        format!("{}/v1{path}", self.base)
75    }
76
77    /// Sends the request `build` makes, with the API key, repeating it as
78    /// [`error::next`] says; `build` is called for every attempt. Returns
79    /// the answer when it is a success.
80    ///
81    /// # Errors
82    ///
83    /// The last attempt's [`HttpsError`].
84    pub async fn send<F>(&self, what: &str, build: F) -> Result<reqwest::Response, HttpsError>
85    where
86        F: Fn(&reqwest::Client) -> reqwest::RequestBuilder,
87    {
88        let mut attempts = 0;
89        loop {
90            attempts += 1;
91            let request_id = format!("{:016x}", StdRandom::new().next_u64());
92            tracing::debug!(request = %request_id, what, attempt = attempts, "sending");
93            let result = build(&self.http)
94                .bearer_auth(self.key.expose())
95                .header("X-Request-Id", &request_id)
96                .send()
97                .await;
98            let err = match result {
99                Ok(response) if response.status().is_success() => return Ok(response),
100                Ok(response) => refused(response).await,
101                Err(err) => transport(&self.base, &err),
102            };
103            match error::next(&err, attempts) {
104                Next::Stop => return Err(err),
105                Next::RetryAfter(wait) => {
106                    tracing::info!(request = %request_id, what, error = %err, wait_ms = wait.as_millis(), "retrying");
107                    tokio::time::sleep(wait).await;
108                }
109            }
110        }
111    }
112
113    /// `GET` of a JSON document.
114    ///
115    /// # Errors
116    ///
117    /// As [`Client::send`], and [`HttpsError::Protocol`] for a document
118    /// that does not read.
119    pub async fn get_json<T: DeserializeOwned>(&self, path: &str) -> Result<T, HttpsError> {
120        let url = self.url(path);
121        let response = self.send(path, |http| http.get(&url)).await?;
122        json(response).await
123    }
124
125    /// `getViewer`: the key in use and the server.
126    ///
127    /// # Errors
128    ///
129    /// As [`Client::get_json`].
130    pub async fn viewer(&self) -> Result<Viewer, HttpsError> {
131        self.get_json("/viewer").await
132    }
133
134    /// `getWorkspace`: the workspace the key opens.
135    ///
136    /// # Errors
137    ///
138    /// As [`Client::get_json`].
139    pub async fn workspace(&self) -> Result<Workspace, HttpsError> {
140        self.get_json("/workspace").await
141    }
142}
143
144/// Reads a JSON answer.
145///
146/// # Errors
147///
148/// [`HttpsError::Protocol`] when it does not read as `T`, and
149/// [`HttpsError::Transport`] when the answer breaks off.
150pub async fn json<T: DeserializeOwned>(response: reqwest::Response) -> Result<T, HttpsError> {
151    let url = response.url().to_string();
152    let body = response
153        .bytes()
154        .await
155        .map_err(|err| transport(&url, &err))?;
156    serde_json::from_slice(&body).map_err(|err| HttpsError::Protocol(format!("{url}: {err}")))
157}
158
159/// The error for a refusal: the problem the server sent.
160async fn refused(response: reqwest::Response) -> HttpsError {
161    let status = response.status();
162    let retry_after = response
163        .headers()
164        .get(RETRY_AFTER)
165        .and_then(|value| value.to_str().ok())
166        .and_then(|value| value.trim().parse::<u64>().ok())
167        .map(Duration::from_secs);
168    let url = response.url().to_string();
169    match response.bytes().await {
170        Ok(body) => match serde_json::from_slice::<Problem>(&body) {
171            Ok(problem) => HttpsError::Refused {
172                problem,
173                retry_after,
174            },
175            Err(_) => HttpsError::Protocol(format!("{url}: HTTP {status} without a problem")),
176        },
177        Err(err) => transport(&url, &err),
178    }
179}
180
181/// The error for a request that got no answer. A refused certificate is
182/// not retried: it would be refused again.
183fn transport(url: &str, err: &reqwest::Error) -> HttpsError {
184    let certificate = sources(err).any(refuses_certificate);
185    HttpsError::Transport {
186        url: url.to_owned(),
187        reason: chain(err),
188        retryable: !certificate
189            && (err.is_connect() || err.is_timeout() || err.is_request() || err.is_body()),
190    }
191}
192
193/// Whether `err` is rustls refusing the server's certificate. hyper-rustls
194/// wraps that in `io::Error`s, whose `source()` skips what they wrap, so
195/// they are unwrapped here.
196fn refuses_certificate(err: &(dyn std::error::Error + 'static)) -> bool {
197    let mut current = Some(err);
198    while let Some(error) = current {
199        if error
200            .downcast_ref::<rustls::Error>()
201            .is_some_and(|tls| matches!(tls, rustls::Error::InvalidCertificate(_)))
202        {
203            return true;
204        }
205        current = error
206            .downcast_ref::<std::io::Error>()
207            .and_then(std::io::Error::get_ref)
208            .map(|inner| inner as &(dyn std::error::Error + 'static));
209    }
210    false
211}
212
213/// `err` and the errors it wraps.
214fn sources<'a>(
215    err: &'a (dyn std::error::Error + 'static),
216) -> impl Iterator<Item = &'a (dyn std::error::Error + 'static)> {
217    std::iter::successors(Some(err), |err| err.source())
218}
219
220/// `err` and every error it wraps, in one line, so a TLS reason such as a
221/// pin mismatch is shown.
222pub(crate) fn chain(err: &(dyn std::error::Error + 'static)) -> String {
223    let mut text = String::new();
224    for source in sources(err) {
225        let part = source.to_string();
226        if !text.contains(&part) {
227            if !text.is_empty() {
228                text.push_str(": ");
229            }
230            text.push_str(&part);
231        }
232    }
233    text
234}