Skip to main content

s2_kit/connect/client/
http.rs

1//! The thin layer between `reqwest` and the protocol: URLs, bearers, and what a status
2//! code means.
3
4use alloc::string::{String, ToString};
5use alloc::sync::Arc;
6
7use serde::Serialize;
8use serde::de::DeserializeOwned;
9
10use crate::connect::proto::ConnectError;
11use crate::connect::tls::{TlsClient, TlsPolicy};
12
13/// What an S2 Connect endpoint answered.
14///
15/// The specification assigns meanings to particular codes on particular operations, and
16/// they are not interchangeable — a `401` on `requestConnectionDetails` means "restart the
17/// pairing", a `403` on the same operation means "this attempt is dead". Keeping the code
18/// rather than collapsing everything into one error is what lets a driver tell them apart.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct Status(pub u16);
21
22impl Status {
23    /// Whether the request succeeded.
24    #[must_use]
25    pub const fn is_success(self) -> bool {
26        self.0 >= 200 && self.0 < 300
27    }
28
29    /// `401` — the bearer was not accepted.
30    #[must_use]
31    pub const fn is_unauthorized(self) -> bool {
32        self.0 == 401
33    }
34
35    /// `403` — the challenge response was wrong; the attempt cannot proceed.
36    #[must_use]
37    pub const fn is_forbidden(self) -> bool {
38        self.0 == 403
39    }
40
41    /// `503` — the server is rate-limiting; `S2C` says "try again soon".
42    #[must_use]
43    pub const fn is_busy(self) -> bool {
44        self.0 == 503
45    }
46}
47
48impl core::fmt::Display for Status {
49    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
50        write!(f, "{}", self.0)
51    }
52}
53
54/// Anything that can go wrong talking to an S2 Connect endpoint.
55#[derive(Debug, thiserror::Error)]
56#[non_exhaustive]
57pub enum Error {
58    /// The protocol refused to advance. Everything that is a *rule* surfaces here.
59    #[error(transparent)]
60    Protocol(#[from] ConnectError),
61    /// TLS could not be set up, or the certificate could not be read.
62    #[error(transparent)]
63    Tls(#[from] crate::connect::tls::Error),
64    /// The request never completed.
65    #[error("{operation} failed: {source}")]
66    Transport {
67        /// Which operation.
68        operation: &'static str,
69        /// Why.
70        source: Box<dyn core::error::Error + Send + Sync>,
71    },
72    /// The endpoint answered, but not with success.
73    #[error("{operation} answered {status}{}", match .detail { Some(d) => alloc::format!(": {d}"), None => String::new() })]
74    Http {
75        /// Which operation.
76        operation: &'static str,
77        /// What it answered.
78        status: Status,
79        /// The body, when there was one worth keeping.
80        detail: Option<String>,
81    },
82    /// The endpoint answered with success and a body we could not read.
83    #[error("{operation} answered with a body that is not what the schema defines: {source}")]
84    Body {
85        /// Which operation.
86        operation: &'static str,
87        /// Why.
88        source: serde_json::Error,
89    },
90    /// The URL is not one we can dial.
91    #[error("{0} is not a usable URL")]
92    Url(String),
93    /// The certificate presented changed between two requests of one pairing attempt.
94    #[error("the server's certificate changed during the pairing attempt")]
95    IdentityChanged,
96}
97
98impl Error {
99    /// Whether retrying after a back-off could plausibly work.
100    ///
101    /// A `503` is the specification's own "try again soon"; a transport failure may be a
102    /// cable. Everything else is a decision, and repeating it will produce the same
103    /// decision.
104    #[must_use]
105    pub fn is_transient(&self) -> bool {
106        match self {
107            // A cable, a DNS blip, a server still starting up.
108            Error::Transport { .. } | Error::Protocol(ConnectError::RateLimited) => true,
109            // `503` is the specification's own "try again soon"; every other code is a
110            // decision, and repeating the request reproduces the decision.
111            Error::Http { status, .. } => status.is_busy(),
112            _ => false,
113        }
114    }
115}
116
117/// An HTTPS connection to one S2 Connect endpoint.
118#[derive(Debug, Clone)]
119pub(crate) struct Http {
120    client: reqwest::Client,
121    base: url::Url,
122    tls: TlsClient,
123}
124
125impl Http {
126    /// Open a connection to `base`, which must be the endpoint's versioned base URL.
127    pub(crate) fn new(
128        base: &str,
129        policy: &TlsPolicy,
130        timeout: core::time::Duration,
131    ) -> Result<Self, Error> {
132        let tls = TlsClient::new(policy)?;
133        let base = normalize(base)?;
134        let client = reqwest::Client::builder()
135            .use_preconfigured_tls(Arc::unwrap_or_clone(tls.config()))
136            .timeout(timeout)
137            // S2 Connect is HTTPS only; a redirect to plain HTTP would silently drop the
138            // binding the whole protocol rests on.
139            .https_only(true)
140            .redirect(reqwest::redirect::Policy::none())
141            .user_agent(concat!("s2-kit/", env!("CARGO_PKG_VERSION")))
142            .build()
143            .map_err(|e| Error::Transport {
144                operation: "building the HTTPS client",
145                source: Box::new(e),
146            })?;
147        Ok(Self { client, base, tls })
148    }
149
150    pub(crate) fn tls(&self) -> &TlsClient {
151        &self.tls
152    }
153
154    pub(crate) fn base(&self) -> &url::Url {
155        &self.base
156    }
157
158    /// `POST {base}{path}`, with an optional bearer, expecting a body back.
159    pub(crate) async fn post<B: Serialize, R: DeserializeOwned>(
160        &self,
161        operation: &'static str,
162        path: &str,
163        bearer: Option<&str>,
164        body: &B,
165    ) -> Result<R, Error> {
166        let text = self.post_raw(operation, path, bearer, Some(body)).await?;
167        serde_json::from_str(&text).map_err(|source| Error::Body { operation, source })
168    }
169
170    /// `POST {base}{path}` where the answer has no body worth reading.
171    pub(crate) async fn post_empty<B: Serialize>(
172        &self,
173        operation: &'static str,
174        path: &str,
175        bearer: Option<&str>,
176        body: Option<&B>,
177    ) -> Result<(), Error> {
178        self.post_raw(operation, path, bearer, body).await.map(drop)
179    }
180
181    /// `GET {base}{path}`.
182    pub(crate) async fn get<R: DeserializeOwned>(
183        &self,
184        operation: &'static str,
185        path: &str,
186    ) -> Result<R, Error> {
187        let url = self.join(path)?;
188        let response = self
189            .client
190            .get(url)
191            .send()
192            .await
193            .map_err(|e| Error::Transport {
194                operation,
195                source: Box::new(e),
196            })?;
197        let text = self.read(operation, response).await?;
198        serde_json::from_str(&text).map_err(|source| Error::Body { operation, source })
199    }
200
201    async fn post_raw<B: Serialize>(
202        &self,
203        operation: &'static str,
204        path: &str,
205        bearer: Option<&str>,
206        body: Option<&B>,
207    ) -> Result<String, Error> {
208        let url = self.join(path)?;
209        let mut request = self.client.post(url);
210        if let Some(token) = bearer {
211            request = request.bearer_auth(token);
212        }
213        if let Some(body) = body {
214            request = request.json(body);
215        }
216        let response = request.send().await.map_err(|e| Error::Transport {
217            operation,
218            source: Box::new(e),
219        })?;
220        self.read(operation, response).await
221    }
222
223    async fn read(
224        &self,
225        operation: &'static str,
226        response: reqwest::Response,
227    ) -> Result<String, Error> {
228        let status = Status(response.status().as_u16());
229        let text = response.text().await.unwrap_or_default();
230        if status.is_success() {
231            return Ok(text);
232        }
233        Err(Error::Http {
234            operation,
235            status,
236            detail: (!text.is_empty()).then_some(text),
237        })
238    }
239
240    fn join(&self, path: &str) -> Result<url::Url, Error> {
241        self.base
242            .join(path.trim_start_matches('/'))
243            .map_err(|_| Error::Url(alloc::format!("{}{path}", self.base)))
244    }
245}
246
247/// Make a base URL joinable: HTTPS, and ending in a slash.
248///
249/// `url::Url::join` replaces the last path segment when the base does not end in one, so
250/// `https://host/v1` + `requestPairing` gives `https://host/requestPairing` — an endpoint
251/// that exists on no server and a bug that is very hard to see.
252fn normalize(base: &str) -> Result<url::Url, Error> {
253    let mut url = url::Url::parse(base).map_err(|_| Error::Url(base.to_string()))?;
254    if url.scheme() != "https" {
255        return Err(Error::Url(alloc::format!(
256            "{base} is not HTTPS, and S2 Connect is HTTPS only"
257        )));
258    }
259    if !url.path().ends_with('/') {
260        let path = alloc::format!("{}/", url.path());
261        url.set_path(&path);
262    }
263    Ok(url)
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    #[test]
271    fn a_base_url_without_a_trailing_slash_still_joins_correctly() {
272        // Without this, `https://host/v1` + `requestPairing` resolves to
273        // `https://host/requestPairing` — an endpoint that exists nowhere.
274        let url = normalize("https://evse.local/v1").unwrap();
275        assert_eq!(url.as_str(), "https://evse.local/v1/");
276        assert_eq!(
277            url.join("requestPairing").unwrap().as_str(),
278            "https://evse.local/v1/requestPairing"
279        );
280        // And one that already has the slash is left alone.
281        assert_eq!(
282            normalize("https://evse.local/v1/").unwrap().as_str(),
283            "https://evse.local/v1/"
284        );
285    }
286
287    #[test]
288    fn plain_http_is_refused_rather_than_upgraded() {
289        // Silently upgrading would be worse: the caller would believe it had a binding.
290        assert!(matches!(
291            normalize("http://evse.local/v1/"),
292            Err(Error::Url(_))
293        ));
294        assert!(matches!(normalize("ws://evse.local/"), Err(Error::Url(_))));
295        assert!(matches!(normalize("not a url"), Err(Error::Url(_))));
296    }
297
298    #[test]
299    fn the_statuses_the_specification_distinguishes_are_distinguished() {
300        assert!(Status(200).is_success());
301        assert!(Status(204).is_success());
302        assert!(!Status(400).is_success());
303        // "Provided pairingAttemptId not accepted. The client may restart the pairing
304        // process" — recoverable.
305        assert!(Status(401).is_unauthorized());
306        // "The PairingAttempt has failed and cannot proceed" — not.
307        assert!(Status(403).is_forbidden());
308        // "The server is temporarily not able to process the pairing request, try again
309        // soon."
310        assert!(Status(503).is_busy());
311    }
312
313    #[test]
314    fn only_the_errors_worth_retrying_say_they_are() {
315        let busy = Error::Http {
316            operation: "requestPairing",
317            status: Status(503),
318            detail: None,
319        };
320        assert!(busy.is_transient());
321        let refused = Error::Http {
322            operation: "requestPairing",
323            status: Status(400),
324            detail: None,
325        };
326        assert!(!refused.is_transient());
327        assert!(!Error::IdentityChanged.is_transient());
328        assert!(Error::Protocol(ConnectError::RateLimited).is_transient());
329        assert!(!Error::Protocol(ConnectError::ChallengeFailed).is_transient());
330    }
331}