Skip to main content

crypto_service_sdk/
transport.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2//! The HTTP exchange under every call, replaceable for tests.
3
4use std::fmt;
5use std::future::Future;
6use std::pin::Pin;
7
8use http::{HeaderMap, Method};
9
10use crate::error::TransportError;
11
12/// Largest response body read, in bytes.
13pub(crate) const BODY_LIMIT: usize = 64 * 1024 * 1024;
14
15/// A boxed, sendable future, as [`Transport::send`] returns.
16pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
17
18/// Sends one HTTP request and reads the whole answer.
19///
20/// The default is [`ReqwestTransport`]. A custom one (a recording
21/// wrapper, an in-process fake) goes in with
22/// [`ClientBuilder::transport`](crate::ClientBuilder::transport). The
23/// client applies the per-attempt timeout, the deadline, retries and
24/// error mapping around it; a transport only moves bytes, and answers
25/// every status, 2xx or not, as an `Ok`.
26pub trait Transport: Send + Sync + fmt::Debug {
27    /// Sends `request` and returns the answer, or a [`TransportError`]
28    /// when none arrived.
29    fn send(&self, request: HttpRequest) -> BoxFuture<'_, Result<HttpResponse, TransportError>>;
30}
31
32/// One request, as the client hands it to a [`Transport`].
33///
34/// `Debug` shows the method, URL and header names only: the values carry
35/// credentials and the body carries keys and plaintexts.
36#[derive(Clone)]
37pub struct HttpRequest {
38    /// The method.
39    pub method: Method,
40    /// The absolute URL.
41    pub url: String,
42    /// Every header the client sets, credentials included.
43    pub headers: HeaderMap,
44    /// The JSON body, when there is one.
45    pub body: Option<Vec<u8>>,
46}
47
48/// One answer, of any status.
49///
50/// `Debug` shows the status, header names and body length only.
51#[derive(Clone)]
52pub struct HttpResponse {
53    /// The status code.
54    pub status: u16,
55    /// The response headers.
56    pub headers: HeaderMap,
57    /// The whole body.
58    pub body: Vec<u8>,
59}
60
61impl HttpResponse {
62    /// The `Content-Type` without parameters, for example
63    /// `application/problem+json`; empty when absent.
64    #[must_use]
65    pub fn media_type(&self) -> &str {
66        self.headers
67            .get(http::header::CONTENT_TYPE)
68            .and_then(|value| value.to_str().ok())
69            .and_then(|value| value.split(';').next())
70            .map_or("", str::trim)
71    }
72
73    /// A header's value, when present and visible ASCII.
74    #[must_use]
75    pub fn header(&self, name: &str) -> Option<&str> {
76        self.headers.get(name).and_then(|value| value.to_str().ok())
77    }
78}
79
80impl fmt::Debug for HttpRequest {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        f.debug_struct("HttpRequest")
83            .field("method", &self.method)
84            .field("url", &self.url)
85            .field("headers", &self.headers.keys().collect::<Vec<_>>())
86            .field("body", &self.body.as_ref().map(Vec::len))
87            .finish()
88    }
89}
90
91impl fmt::Debug for HttpResponse {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        f.debug_struct("HttpResponse")
94            .field("status", &self.status)
95            .field("headers", &self.headers.keys().collect::<Vec<_>>())
96            .field("body", &self.body.len())
97            .finish()
98    }
99}
100
101/// The default [`Transport`]: one pooled `reqwest` client per SDK client
102/// and its clones, with rustls (the platform's trust store, verification
103/// always on), HTTP/2 by ALPN, gzip, keep-alive, and redirects refused.
104/// Responses are read up to 64 MiB.
105#[derive(Debug, Clone)]
106pub struct ReqwestTransport {
107    client: reqwest::Client,
108    limit: usize,
109}
110
111impl ReqwestTransport {
112    /// A transport with the SDK's settings.
113    ///
114    /// # Errors
115    ///
116    /// [`Error::Config`](crate::Error::Config) when the TLS stack cannot
117    /// be initialised.
118    pub fn new() -> Result<Self, crate::Error> {
119        Self::with_limit(BODY_LIMIT)
120    }
121
122    /// [`ReqwestTransport::new`] reading bodies up to `limit` bytes.
123    pub(crate) fn with_limit(limit: usize) -> Result<Self, crate::Error> {
124        reqwest::Client::builder()
125            // A redirect would carry the credentials to whatever origin
126            // the Location names; an API never needs one.
127            .redirect(reqwest::redirect::Policy::none())
128            .build()
129            .map(|client| ReqwestTransport { client, limit })
130            .map_err(build_failed)
131    }
132
133    async fn exchange(&self, request: HttpRequest) -> Result<HttpResponse, TransportError> {
134        let mut builder = self
135            .client
136            .request(request.method, request.url)
137            .headers(request.headers);
138        if let Some(body) = request.body {
139            builder = builder.body(body);
140        }
141        let mut response = builder.send().await.map_err(failure)?;
142        let status = response.status().as_u16();
143        let headers = std::mem::take(response.headers_mut());
144        let mut body = Vec::new();
145        while let Some(chunk) = response.chunk().await.map_err(failure)? {
146            if body.len() + chunk.len() > self.limit {
147                return Err(TransportError::new(
148                    "response body over the size limit",
149                    false,
150                ));
151            }
152            body.extend_from_slice(&chunk);
153        }
154        Ok(HttpResponse {
155            status,
156            headers,
157            body,
158        })
159    }
160}
161
162impl Transport for ReqwestTransport {
163    fn send(&self, request: HttpRequest) -> BoxFuture<'_, Result<HttpResponse, TransportError>> {
164        Box::pin(self.exchange(request))
165    }
166}
167
168/// The error for a `reqwest` client that could not be built.
169pub(crate) fn build_failed(_: reqwest::Error) -> crate::Error {
170    crate::Error::Config("the HTTP client could not be built")
171}
172
173/// A reqwest error as a [`TransportError`], without the URL.
174fn failure(error: reqwest::Error) -> TransportError {
175    let timed_out = error.is_timeout();
176    TransportError::new(error.without_url(), timed_out)
177}