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's version index offers no API version this crate speaks.
98    #[error(
99        "the endpoint offers API versions {offered:?}, none of which this crate speaks ({supported:?})"
100    )]
101    NoCommonApiVersion {
102        /// What `GET {base}` answered.
103        offered: Vec<String>,
104        /// What this crate speaks.
105        supported: &'static [&'static str],
106    },
107    /// The endpoint answered with more bytes than any S2 Connect body can legitimately be.
108    #[error("{operation} answered with more than {max} bytes")]
109    ResponseTooLarge {
110        /// Which operation.
111        operation: &'static str,
112        /// The cap that was exceeded.
113        max: usize,
114    },
115}
116
117impl Error {
118    /// Whether retrying after a back-off could plausibly work.
119    ///
120    /// A `503` is the specification's own "try again soon"; a transport failure may be a
121    /// cable. Everything else is a decision, and repeating it will produce the same
122    /// decision.
123    #[must_use]
124    pub fn is_transient(&self) -> bool {
125        match self {
126            // A cable, a DNS blip, a server still starting up.
127            Error::Transport { .. } | Error::Protocol(ConnectError::RateLimited) => true,
128            // `503` is the specification's own "try again soon"; every other code is a
129            // decision, and repeating the request reproduces the decision.
130            Error::Http { status, .. } => status.is_busy(),
131            _ => false,
132        }
133    }
134}
135
136/// The most of an endpoint's answer that will be read into memory.
137///
138/// The symmetric half of [`MAX_BODY_BYTES`](crate::connect::server::MAX_BODY_BYTES), and
139/// it matters for a reason that is easy to miss: during a LAN pairing the server is
140/// deliberately **not** authenticated — that is the whole meaning of
141/// [`TlsPolicy::LanPairingOnly`] — so the four pairing requests are answered by whatever
142/// is on the other end of the socket, which on a LAN is anything that got there first.
143/// Without a cap, a `reqwest` `text()` reads the lot.
144///
145/// Every S2 Connect body is a handful of identifiers, descriptions and Base64 challenges.
146/// `GET /v1/nodes` is the largest, and it is a list of node descriptions. A quarter of a
147/// mebibyte is four times what the server side accepts, so a long node list fits and a
148/// hostile endpoint still cannot make a constrained Resource Manager hold a gigabyte.
149pub const MAX_RESPONSE_BYTES: usize = 256 * 1024;
150
151/// The S2 Connect API versions this crate speaks, most preferred first.
152pub const API_VERSIONS: &[&str] = &["v1"];
153
154/// An HTTPS connection to one S2 Connect endpoint.
155#[derive(Debug, Clone)]
156pub(crate) struct Http {
157    client: reqwest::Client,
158    /// The base URL as given: the endpoint's **unversioned** URL, whose index lists the
159    /// versions it serves.
160    base: url::Url,
161    /// The versioned base every operation is joined onto, once the index has been read.
162    versioned: tokio::sync::OnceCell<url::Url>,
163    tls: TlsClient,
164}
165
166impl Http {
167    /// Open a connection to `base`: the endpoint's unversioned URL, as a DNS-SD
168    /// `pairingUrl` or an `initiateSessionUrl` carries it.
169    ///
170    /// `S2C §Selecting the version`: "the client **must** always first determine which
171    /// version of the API it will use" — so the first request is `GET {base}`, which a
172    /// conforming server answers with its versions (`["v1"]`). A base that already ends
173    /// in a version segment (`…/v1/`) is used as given, without the probe, for peers that
174    /// hand out versioned URLs.
175    pub(crate) fn new(
176        base: &str,
177        policy: &TlsPolicy,
178        timeout: core::time::Duration,
179    ) -> Result<Self, Error> {
180        let tls = TlsClient::new(policy)?;
181        let base = normalize(base)?;
182        let client = reqwest::Client::builder()
183            .use_preconfigured_tls(Arc::unwrap_or_clone(tls.config()))
184            .timeout(timeout)
185            // S2 Connect is HTTPS only; a redirect to plain HTTP would silently drop the
186            // binding the whole protocol rests on.
187            .https_only(true)
188            .redirect(reqwest::redirect::Policy::none())
189            .user_agent(concat!("s2-kit/", env!("CARGO_PKG_VERSION")))
190            .build()
191            .map_err(|e| Error::Transport {
192                operation: "building the HTTPS client",
193                source: Box::new(e),
194            })?;
195        let versioned = tokio::sync::OnceCell::new();
196        if base
197            .path_segments()
198            .and_then(|mut segments| segments.rfind(|s| !s.is_empty()))
199            .is_some_and(is_version_segment)
200        {
201            let _ = versioned.set(base.clone());
202        }
203        Ok(Self {
204            client,
205            base,
206            versioned,
207            tls,
208        })
209    }
210
211    /// The versioned base, reading the endpoint's version index the first time.
212    async fn versioned(&self) -> Result<&url::Url, Error> {
213        self.versioned
214            .get_or_try_init(|| async {
215                const OPERATION: &str = "the API version index";
216                let response = self
217                    .client
218                    .get(self.base.clone())
219                    .send()
220                    .await
221                    .map_err(|e| Error::Transport {
222                        operation: OPERATION,
223                        source: Box::new(e),
224                    })?;
225                let text = self.read(OPERATION, response).await?;
226                let offered: Vec<String> =
227                    serde_json::from_str(&text).map_err(|source| Error::Body {
228                        operation: OPERATION,
229                        source,
230                    })?;
231                let chosen = API_VERSIONS
232                    .iter()
233                    .find(|ours| offered.iter().any(|theirs| theirs == *ours))
234                    .ok_or_else(|| Error::NoCommonApiVersion {
235                        offered: offered.clone(),
236                        supported: API_VERSIONS,
237                    })?;
238                self.base
239                    .join(&alloc::format!("{chosen}/"))
240                    .map_err(|_| Error::Url(alloc::format!("{}{chosen}/", self.base)))
241            })
242            .await
243    }
244
245    pub(crate) fn tls(&self) -> &TlsClient {
246        &self.tls
247    }
248
249    pub(crate) fn base(&self) -> &url::Url {
250        &self.base
251    }
252
253    /// `POST {base}{path}`, with an optional bearer, expecting a body back.
254    pub(crate) async fn post<B: Serialize, R: DeserializeOwned>(
255        &self,
256        operation: &'static str,
257        path: &str,
258        bearer: Option<&str>,
259        body: &B,
260    ) -> Result<R, Error> {
261        let text = self.post_raw(operation, path, bearer, Some(body)).await?;
262        serde_json::from_str(&text).map_err(|source| Error::Body { operation, source })
263    }
264
265    /// `POST {base}{path}` with **no request body at all**, expecting one back.
266    ///
267    /// `confirmAccessToken` is the one operation `S2C-OAS session-init` defines with no
268    /// `requestBody`: the bearer *is* the message. Posting `null` with a JSON content type
269    /// — which is what serialising `()` produces — is a body the specification does not
270    /// define, and a peer entitled to validate against the OpenAPI is entitled to refuse
271    /// it.
272    pub(crate) async fn post_bodyless<R: DeserializeOwned>(
273        &self,
274        operation: &'static str,
275        path: &str,
276        bearer: Option<&str>,
277    ) -> Result<R, Error> {
278        let url = self.join(path).await?;
279        let mut request = self.client.post(url);
280        if let Some(token) = bearer {
281            request = request.bearer_auth(token);
282        }
283        let response = request.send().await.map_err(|e| Error::Transport {
284            operation,
285            source: Box::new(e),
286        })?;
287        let text = self.read(operation, response).await?;
288        serde_json::from_str(&text).map_err(|source| Error::Body { operation, source })
289    }
290
291    /// `POST {base}{path}` where `204 No Content` is a legitimate answer meaning "nothing".
292    ///
293    /// `waitForPairing`'s: `S2C-OAS` gives its `200` list `minItems: 1`, and a hold that
294    /// ran out is `204` — "No action for the client, try again."
295    pub(crate) async fn post_or_no_content<B: Serialize, R: DeserializeOwned>(
296        &self,
297        operation: &'static str,
298        path: &str,
299        bearer: Option<&str>,
300        body: &B,
301    ) -> Result<Option<R>, Error> {
302        let url = self.join(path).await?;
303        let mut request = self.client.post(url).json(body);
304        if let Some(token) = bearer {
305            request = request.bearer_auth(token);
306        }
307        let response = request.send().await.map_err(|e| Error::Transport {
308            operation,
309            source: Box::new(e),
310        })?;
311        if response.status() == reqwest::StatusCode::NO_CONTENT {
312            return Ok(None);
313        }
314        let text = self.read(operation, response).await?;
315        serde_json::from_str(&text)
316            .map(Some)
317            .map_err(|source| Error::Body { operation, source })
318    }
319
320    /// `POST {base}{path}` where the answer has no body worth reading.
321    pub(crate) async fn post_empty<B: Serialize>(
322        &self,
323        operation: &'static str,
324        path: &str,
325        bearer: Option<&str>,
326        body: Option<&B>,
327    ) -> Result<(), Error> {
328        self.post_raw(operation, path, bearer, body).await.map(drop)
329    }
330
331    /// `GET {base}{path}`.
332    pub(crate) async fn get<R: DeserializeOwned>(
333        &self,
334        operation: &'static str,
335        path: &str,
336    ) -> Result<R, Error> {
337        let url = self.join(path).await?;
338        let response = self
339            .client
340            .get(url)
341            .send()
342            .await
343            .map_err(|e| Error::Transport {
344                operation,
345                source: Box::new(e),
346            })?;
347        let text = self.read(operation, response).await?;
348        serde_json::from_str(&text).map_err(|source| Error::Body { operation, source })
349    }
350
351    async fn post_raw<B: Serialize>(
352        &self,
353        operation: &'static str,
354        path: &str,
355        bearer: Option<&str>,
356        body: Option<&B>,
357    ) -> Result<String, Error> {
358        let url = self.join(path).await?;
359        let mut request = self.client.post(url);
360        if let Some(token) = bearer {
361            request = request.bearer_auth(token);
362        }
363        if let Some(body) = body {
364            request = request.json(body);
365        }
366        let response = request.send().await.map_err(|e| Error::Transport {
367            operation,
368            source: Box::new(e),
369        })?;
370        self.read(operation, response).await
371    }
372
373    async fn read(
374        &self,
375        operation: &'static str,
376        response: reqwest::Response,
377    ) -> Result<String, Error> {
378        let status = Status(response.status().as_u16());
379        let text = read_bounded(operation, response).await?;
380        if status.is_success() {
381            return Ok(text);
382        }
383        Err(Error::Http {
384            operation,
385            status,
386            detail: (!text.is_empty()).then_some(text),
387        })
388    }
389
390    async fn join(&self, path: &str) -> Result<url::Url, Error> {
391        let base = self.versioned().await?;
392        base.join(path.trim_start_matches('/'))
393            .map_err(|_| Error::Url(alloc::format!("{base}{path}")))
394    }
395}
396
397/// `v` followed by digits: a path segment that names an API version.
398fn is_version_segment(segment: &str) -> bool {
399    segment
400        .strip_prefix('v')
401        .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit()))
402}
403
404/// Read a response body, refusing anything past [`MAX_RESPONSE_BYTES`].
405///
406/// Chunk by chunk rather than `Response::text()`, because `text()` has already allocated
407/// the whole body by the time it returns a value anyone could measure. `Content-Length` is
408/// checked first where the server sent one — it is a hint and not a promise, so the
409/// running total is what actually enforces the cap.
410async fn read_bounded(
411    operation: &'static str,
412    mut response: reqwest::Response,
413) -> Result<String, Error> {
414    let too_large = || Error::ResponseTooLarge {
415        operation,
416        max: MAX_RESPONSE_BYTES,
417    };
418    if response
419        .content_length()
420        .is_some_and(|len| len > MAX_RESPONSE_BYTES as u64)
421    {
422        return Err(too_large());
423    }
424
425    let mut body: Vec<u8> = Vec::new();
426    loop {
427        let chunk = response.chunk().await.map_err(|e| Error::Transport {
428            operation,
429            source: Box::new(e),
430        })?;
431        let Some(chunk) = chunk else { break };
432        if body.len().saturating_add(chunk.len()) > MAX_RESPONSE_BYTES {
433            return Err(too_large());
434        }
435        body.extend_from_slice(&chunk);
436    }
437    // Not `from_utf8_lossy`: a body that is not UTF-8 is not an S2 Connect body, and
438    // replacing the bad bytes would hand the JSON parser a plausible-looking lie.
439    String::from_utf8(body).map_err(|e| Error::Transport {
440        operation,
441        source: Box::new(e),
442    })
443}
444
445/// Make a base URL joinable: HTTPS, and ending in a slash.
446///
447/// `url::Url::join` replaces the last path segment when the base does not end in one, so
448/// `https://host/v1` + `requestPairing` gives `https://host/requestPairing` — an endpoint
449/// that exists on no server and a bug that is very hard to see.
450fn normalize(base: &str) -> Result<url::Url, Error> {
451    let mut url = url::Url::parse(base).map_err(|_| Error::Url(base.to_string()))?;
452    if url.scheme() != "https" {
453        return Err(Error::Url(alloc::format!(
454            "{base} is not HTTPS, and S2 Connect is HTTPS only"
455        )));
456    }
457    if !url.path().ends_with('/') {
458        let path = alloc::format!("{}/", url.path());
459        url.set_path(&path);
460    }
461    Ok(url)
462}
463
464#[cfg(test)]
465mod tests {
466    use super::*;
467
468    #[test]
469    fn a_base_url_without_a_trailing_slash_still_joins_correctly() {
470        // Without this, `https://host/v1` + `requestPairing` resolves to
471        // `https://host/requestPairing` — an endpoint that exists nowhere.
472        let url = normalize("https://evse.local/v1").unwrap();
473        assert_eq!(url.as_str(), "https://evse.local/v1/");
474        assert_eq!(
475            url.join("requestPairing").unwrap().as_str(),
476            "https://evse.local/v1/requestPairing"
477        );
478        // And one that already has the slash is left alone.
479        assert_eq!(
480            normalize("https://evse.local/v1/").unwrap().as_str(),
481            "https://evse.local/v1/"
482        );
483    }
484
485    #[test]
486    fn a_versioned_base_is_recognised_and_an_unversioned_one_is_not() {
487        assert!(is_version_segment("v1"));
488        assert!(is_version_segment("v12"));
489        assert!(!is_version_segment("v"));
490        assert!(!is_version_segment("pairing"));
491        assert!(!is_version_segment("v1beta"));
492    }
493
494    #[test]
495    fn plain_http_is_refused_rather_than_upgraded() {
496        // Silently upgrading would be worse: the caller would believe it had a binding.
497        assert!(matches!(
498            normalize("http://evse.local/v1/"),
499            Err(Error::Url(_))
500        ));
501        assert!(matches!(normalize("ws://evse.local/"), Err(Error::Url(_))));
502        assert!(matches!(normalize("not a url"), Err(Error::Url(_))));
503    }
504
505    #[test]
506    fn the_statuses_the_specification_distinguishes_are_distinguished() {
507        assert!(Status(200).is_success());
508        assert!(Status(204).is_success());
509        assert!(!Status(400).is_success());
510        // "Provided pairingAttemptId not accepted. The client may restart the pairing
511        // process" — recoverable.
512        assert!(Status(401).is_unauthorized());
513        // "The PairingAttempt has failed and cannot proceed" — not.
514        assert!(Status(403).is_forbidden());
515        // "The server is temporarily not able to process the pairing request, try again
516        // soon."
517        assert!(Status(503).is_busy());
518    }
519
520    #[test]
521    fn only_the_errors_worth_retrying_say_they_are() {
522        let busy = Error::Http {
523            operation: "requestPairing",
524            status: Status(503),
525            detail: None,
526        };
527        assert!(busy.is_transient());
528        let refused = Error::Http {
529            operation: "requestPairing",
530            status: Status(400),
531            detail: None,
532        };
533        assert!(!refused.is_transient());
534        assert!(!Error::IdentityChanged.is_transient());
535        assert!(Error::Protocol(ConnectError::RateLimited).is_transient());
536        assert!(!Error::Protocol(ConnectError::ChallengeFailed).is_transient());
537    }
538}