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;
6use alloc::vec::Vec;
7
8use serde::Serialize;
9use serde::de::DeserializeOwned;
10
11use crate::connect::proto::ConnectError;
12use crate::connect::tls::{TlsClient, TlsPolicy};
13
14/// What an S2 Connect endpoint answered.
15///
16/// The specification assigns meanings to particular codes on particular operations, and
17/// they are not interchangeable — a `401` on `requestConnectionDetails` means "restart the
18/// pairing", a `403` on the same operation means "this attempt is dead". Keeping the code
19/// rather than collapsing everything into one error is what lets a driver tell them apart.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub struct Status(pub u16);
22
23impl Status {
24    /// Whether the request succeeded.
25    #[must_use]
26    pub const fn is_success(self) -> bool {
27        self.0 >= 200 && self.0 < 300
28    }
29
30    /// `401` — the bearer was not accepted.
31    #[must_use]
32    pub const fn is_unauthorized(self) -> bool {
33        self.0 == 401
34    }
35
36    /// `403` — the challenge response was wrong; the attempt cannot proceed.
37    #[must_use]
38    pub const fn is_forbidden(self) -> bool {
39        self.0 == 403
40    }
41
42    /// `503` — the server is rate-limiting; `S2C` says "try again soon".
43    #[must_use]
44    pub const fn is_busy(self) -> bool {
45        self.0 == 503
46    }
47}
48
49impl core::fmt::Display for Status {
50    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
51        write!(f, "{}", self.0)
52    }
53}
54
55/// Anything that can go wrong talking to an S2 Connect endpoint.
56#[derive(Debug, thiserror::Error)]
57#[non_exhaustive]
58pub enum Error {
59    /// The protocol refused to advance. Everything that is a *rule* surfaces here.
60    #[error(transparent)]
61    Protocol(#[from] ConnectError),
62    /// TLS could not be set up, or the certificate could not be read.
63    #[error(transparent)]
64    Tls(#[from] crate::connect::tls::Error),
65    /// The request never completed.
66    #[error("{operation} failed: {source}")]
67    Transport {
68        /// Which operation.
69        operation: &'static str,
70        /// Why.
71        source: Box<dyn core::error::Error + Send + Sync>,
72    },
73    /// The endpoint answered, but not with success.
74    #[error("{operation} answered {status}{}", match .detail { Some(d) => alloc::format!(": {d}"), None => String::new() })]
75    Http {
76        /// Which operation.
77        operation: &'static str,
78        /// What it answered.
79        status: Status,
80        /// The body, when there was one worth keeping.
81        detail: Option<String>,
82    },
83    /// The endpoint answered with success and a body we could not read.
84    #[error("{operation} answered with a body that is not what the schema defines: {source}")]
85    Body {
86        /// Which operation.
87        operation: &'static str,
88        /// Why.
89        source: serde_json::Error,
90    },
91    /// The URL is not one we can dial.
92    #[error("{0} is not a usable URL")]
93    Url(String),
94    /// The certificate presented changed between two requests of one pairing attempt.
95    #[error("the server's certificate changed during the pairing attempt")]
96    IdentityChanged,
97    /// The endpoint answered with more bytes than any S2 Connect body can legitimately be.
98    #[error("{operation} answered with more than {max} bytes")]
99    ResponseTooLarge {
100        /// Which operation.
101        operation: &'static str,
102        /// The cap that was exceeded.
103        max: usize,
104    },
105}
106
107impl Error {
108    /// Whether retrying after a back-off could plausibly work.
109    ///
110    /// A `503` is the specification's own "try again soon"; a transport failure may be a
111    /// cable. Everything else is a decision, and repeating it will produce the same
112    /// decision.
113    #[must_use]
114    pub fn is_transient(&self) -> bool {
115        match self {
116            // A cable, a DNS blip, a server still starting up.
117            Error::Transport { .. } | Error::Protocol(ConnectError::RateLimited) => true,
118            // `503` is the specification's own "try again soon"; every other code is a
119            // decision, and repeating the request reproduces the decision.
120            Error::Http { status, .. } => status.is_busy(),
121            _ => false,
122        }
123    }
124}
125
126/// The most of an endpoint's answer that will be read into memory.
127///
128/// The symmetric half of [`MAX_BODY_BYTES`](crate::connect::server::MAX_BODY_BYTES), and
129/// it matters for a reason that is easy to miss: during a LAN pairing the server is
130/// deliberately **not** authenticated — that is the whole meaning of
131/// [`TlsPolicy::LanPairingOnly`] — so the four pairing requests are answered by whatever
132/// is on the other end of the socket, which on a LAN is anything that got there first.
133/// Without a cap, a `reqwest` `text()` reads the lot.
134///
135/// Every S2 Connect body is a handful of identifiers, descriptions and Base64 challenges.
136/// `GET /v1/nodes` is the largest, and it is a list of node descriptions. A quarter of a
137/// mebibyte is four times what the server side accepts, so a long node list fits and a
138/// hostile endpoint still cannot make a constrained Resource Manager hold a gigabyte.
139pub const MAX_RESPONSE_BYTES: usize = 256 * 1024;
140
141/// An HTTPS connection to one S2 Connect endpoint.
142#[derive(Debug, Clone)]
143pub(crate) struct Http {
144    client: reqwest::Client,
145    base: url::Url,
146    tls: TlsClient,
147}
148
149impl Http {
150    /// Open a connection to `base`, which must be the endpoint's versioned base URL.
151    pub(crate) fn new(
152        base: &str,
153        policy: &TlsPolicy,
154        timeout: core::time::Duration,
155    ) -> Result<Self, Error> {
156        let tls = TlsClient::new(policy)?;
157        let base = normalize(base)?;
158        let client = reqwest::Client::builder()
159            .use_preconfigured_tls(Arc::unwrap_or_clone(tls.config()))
160            .timeout(timeout)
161            // S2 Connect is HTTPS only; a redirect to plain HTTP would silently drop the
162            // binding the whole protocol rests on.
163            .https_only(true)
164            .redirect(reqwest::redirect::Policy::none())
165            .user_agent(concat!("s2-kit/", env!("CARGO_PKG_VERSION")))
166            .build()
167            .map_err(|e| Error::Transport {
168                operation: "building the HTTPS client",
169                source: Box::new(e),
170            })?;
171        Ok(Self { client, base, tls })
172    }
173
174    pub(crate) fn tls(&self) -> &TlsClient {
175        &self.tls
176    }
177
178    pub(crate) fn base(&self) -> &url::Url {
179        &self.base
180    }
181
182    /// `POST {base}{path}`, with an optional bearer, expecting a body back.
183    pub(crate) async fn post<B: Serialize, R: DeserializeOwned>(
184        &self,
185        operation: &'static str,
186        path: &str,
187        bearer: Option<&str>,
188        body: &B,
189    ) -> Result<R, Error> {
190        let text = self.post_raw(operation, path, bearer, Some(body)).await?;
191        serde_json::from_str(&text).map_err(|source| Error::Body { operation, source })
192    }
193
194    /// `POST {base}{path}` with **no request body at all**, expecting one back.
195    ///
196    /// `confirmAccessToken` is the one operation `S2C-OAS session-init` defines with no
197    /// `requestBody`: the bearer *is* the message. Posting `null` with a JSON content type
198    /// — which is what serialising `()` produces — is a body the specification does not
199    /// define, and a peer entitled to validate against the OpenAPI is entitled to refuse
200    /// it.
201    pub(crate) async fn post_bodyless<R: DeserializeOwned>(
202        &self,
203        operation: &'static str,
204        path: &str,
205        bearer: Option<&str>,
206    ) -> Result<R, Error> {
207        let url = self.join(path)?;
208        let mut request = self.client.post(url);
209        if let Some(token) = bearer {
210            request = request.bearer_auth(token);
211        }
212        let response = request.send().await.map_err(|e| Error::Transport {
213            operation,
214            source: Box::new(e),
215        })?;
216        let text = self.read(operation, response).await?;
217        serde_json::from_str(&text).map_err(|source| Error::Body { operation, source })
218    }
219
220    /// `POST {base}{path}` where the answer has no body worth reading.
221    pub(crate) async fn post_empty<B: Serialize>(
222        &self,
223        operation: &'static str,
224        path: &str,
225        bearer: Option<&str>,
226        body: Option<&B>,
227    ) -> Result<(), Error> {
228        self.post_raw(operation, path, bearer, body).await.map(drop)
229    }
230
231    /// `GET {base}{path}`.
232    pub(crate) async fn get<R: DeserializeOwned>(
233        &self,
234        operation: &'static str,
235        path: &str,
236    ) -> Result<R, Error> {
237        let url = self.join(path)?;
238        let response = self
239            .client
240            .get(url)
241            .send()
242            .await
243            .map_err(|e| Error::Transport {
244                operation,
245                source: Box::new(e),
246            })?;
247        let text = self.read(operation, response).await?;
248        serde_json::from_str(&text).map_err(|source| Error::Body { operation, source })
249    }
250
251    async fn post_raw<B: Serialize>(
252        &self,
253        operation: &'static str,
254        path: &str,
255        bearer: Option<&str>,
256        body: Option<&B>,
257    ) -> Result<String, Error> {
258        let url = self.join(path)?;
259        let mut request = self.client.post(url);
260        if let Some(token) = bearer {
261            request = request.bearer_auth(token);
262        }
263        if let Some(body) = body {
264            request = request.json(body);
265        }
266        let response = request.send().await.map_err(|e| Error::Transport {
267            operation,
268            source: Box::new(e),
269        })?;
270        self.read(operation, response).await
271    }
272
273    async fn read(
274        &self,
275        operation: &'static str,
276        response: reqwest::Response,
277    ) -> Result<String, Error> {
278        let status = Status(response.status().as_u16());
279        let text = read_bounded(operation, response).await?;
280        if status.is_success() {
281            return Ok(text);
282        }
283        Err(Error::Http {
284            operation,
285            status,
286            detail: (!text.is_empty()).then_some(text),
287        })
288    }
289
290    fn join(&self, path: &str) -> Result<url::Url, Error> {
291        self.base
292            .join(path.trim_start_matches('/'))
293            .map_err(|_| Error::Url(alloc::format!("{}{path}", self.base)))
294    }
295}
296
297/// Read a response body, refusing anything past [`MAX_RESPONSE_BYTES`].
298///
299/// Chunk by chunk rather than `Response::text()`, because `text()` has already allocated
300/// the whole body by the time it returns a value anyone could measure. `Content-Length` is
301/// checked first where the server sent one — it is a hint and not a promise, so the
302/// running total is what actually enforces the cap.
303async fn read_bounded(
304    operation: &'static str,
305    mut response: reqwest::Response,
306) -> Result<String, Error> {
307    let too_large = || Error::ResponseTooLarge {
308        operation,
309        max: MAX_RESPONSE_BYTES,
310    };
311    if response
312        .content_length()
313        .is_some_and(|len| len > MAX_RESPONSE_BYTES as u64)
314    {
315        return Err(too_large());
316    }
317
318    let mut body: Vec<u8> = Vec::new();
319    loop {
320        let chunk = response.chunk().await.map_err(|e| Error::Transport {
321            operation,
322            source: Box::new(e),
323        })?;
324        let Some(chunk) = chunk else { break };
325        if body.len().saturating_add(chunk.len()) > MAX_RESPONSE_BYTES {
326            return Err(too_large());
327        }
328        body.extend_from_slice(&chunk);
329    }
330    // Not `from_utf8_lossy`: a body that is not UTF-8 is not an S2 Connect body, and
331    // replacing the bad bytes would hand the JSON parser a plausible-looking lie.
332    String::from_utf8(body).map_err(|e| Error::Transport {
333        operation,
334        source: Box::new(e),
335    })
336}
337
338/// Make a base URL joinable: HTTPS, and ending in a slash.
339///
340/// `url::Url::join` replaces the last path segment when the base does not end in one, so
341/// `https://host/v1` + `requestPairing` gives `https://host/requestPairing` — an endpoint
342/// that exists on no server and a bug that is very hard to see.
343fn normalize(base: &str) -> Result<url::Url, Error> {
344    let mut url = url::Url::parse(base).map_err(|_| Error::Url(base.to_string()))?;
345    if url.scheme() != "https" {
346        return Err(Error::Url(alloc::format!(
347            "{base} is not HTTPS, and S2 Connect is HTTPS only"
348        )));
349    }
350    if !url.path().ends_with('/') {
351        let path = alloc::format!("{}/", url.path());
352        url.set_path(&path);
353    }
354    Ok(url)
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360
361    #[test]
362    fn a_base_url_without_a_trailing_slash_still_joins_correctly() {
363        // Without this, `https://host/v1` + `requestPairing` resolves to
364        // `https://host/requestPairing` — an endpoint that exists nowhere.
365        let url = normalize("https://evse.local/v1").unwrap();
366        assert_eq!(url.as_str(), "https://evse.local/v1/");
367        assert_eq!(
368            url.join("requestPairing").unwrap().as_str(),
369            "https://evse.local/v1/requestPairing"
370        );
371        // And one that already has the slash is left alone.
372        assert_eq!(
373            normalize("https://evse.local/v1/").unwrap().as_str(),
374            "https://evse.local/v1/"
375        );
376    }
377
378    #[test]
379    fn plain_http_is_refused_rather_than_upgraded() {
380        // Silently upgrading would be worse: the caller would believe it had a binding.
381        assert!(matches!(
382            normalize("http://evse.local/v1/"),
383            Err(Error::Url(_))
384        ));
385        assert!(matches!(normalize("ws://evse.local/"), Err(Error::Url(_))));
386        assert!(matches!(normalize("not a url"), Err(Error::Url(_))));
387    }
388
389    #[test]
390    fn the_statuses_the_specification_distinguishes_are_distinguished() {
391        assert!(Status(200).is_success());
392        assert!(Status(204).is_success());
393        assert!(!Status(400).is_success());
394        // "Provided pairingAttemptId not accepted. The client may restart the pairing
395        // process" — recoverable.
396        assert!(Status(401).is_unauthorized());
397        // "The PairingAttempt has failed and cannot proceed" — not.
398        assert!(Status(403).is_forbidden());
399        // "The server is temporarily not able to process the pairing request, try again
400        // soon."
401        assert!(Status(503).is_busy());
402    }
403
404    #[test]
405    fn only_the_errors_worth_retrying_say_they_are() {
406        let busy = Error::Http {
407            operation: "requestPairing",
408            status: Status(503),
409            detail: None,
410        };
411        assert!(busy.is_transient());
412        let refused = Error::Http {
413            operation: "requestPairing",
414            status: Status(400),
415            detail: None,
416        };
417        assert!(!refused.is_transient());
418        assert!(!Error::IdentityChanged.is_transient());
419        assert!(Error::Protocol(ConnectError::RateLimited).is_transient());
420        assert!(!Error::Protocol(ConnectError::ChallengeFailed).is_transient());
421    }
422}