Skip to main content

owlauth_client/
transport.rs

1use std::{fmt, time::Duration};
2
3use async_trait::async_trait;
4use url::Url;
5
6use crate::OwlAuthError;
7
8pub(crate) const MAX_BODY: usize = 1024 * 1024;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum HttpMethod {
12    Get,
13    Post,
14}
15
16pub struct HttpRequest {
17    pub method: HttpMethod,
18    pub url: Url,
19    pub bearer: Option<String>,
20    pub body: Option<Vec<u8>>,
21    pub timeout: Duration,
22}
23
24impl fmt::Debug for HttpRequest {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        f.debug_struct("HttpRequest")
27            .field("method", &self.method)
28            .field("timeout", &self.timeout)
29            .finish_non_exhaustive()
30    }
31}
32
33pub struct HttpResponse {
34    pub status: u16,
35    pub body: Vec<u8>,
36}
37
38impl fmt::Debug for HttpResponse {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        f.debug_struct("HttpResponse")
41            .field("status", &self.status)
42            .finish_non_exhaustive()
43    }
44}
45
46/// One bounded, cookie-free HTTP request without redirects or automatic retries.
47#[async_trait]
48pub trait Transport: Send + Sync {
49    /// Send the request and return the response without following redirects.
50    ///
51    /// # Errors
52    /// Returns the classified transport failure.
53    async fn send(&self, request: HttpRequest) -> Result<HttpResponse, OwlAuthError>;
54}
55
56pub(crate) struct DefaultTransport(reqwest::Client);
57
58impl DefaultTransport {
59    pub(crate) fn new() -> Result<Self, OwlAuthError> {
60        reqwest::Client::builder()
61            .redirect(reqwest::redirect::Policy::none())
62            .retry(reqwest::retry::never())
63            .no_proxy()
64            .build()
65            .map(Self)
66            .map_err(|_| {
67                OwlAuthError::new(
68                    "invalid_configuration",
69                    "Could not create Runtime HTTP transport",
70                    None,
71                )
72            })
73    }
74}
75
76#[async_trait]
77impl Transport for DefaultTransport {
78    async fn send(&self, request: HttpRequest) -> Result<HttpResponse, OwlAuthError> {
79        let mut outgoing = match request.method {
80            HttpMethod::Get => self.0.get(request.url),
81            HttpMethod::Post => self.0.post(request.url),
82        }
83        .header(reqwest::header::ACCEPT, "application/json")
84        .timeout(request.timeout);
85        if let Some(token) = request.bearer {
86            outgoing = outgoing.bearer_auth(token);
87        }
88        if let Some(body) = request.body {
89            outgoing = outgoing
90                .header(reqwest::header::CONTENT_TYPE, "application/json")
91                .body(body);
92        }
93        let mut reply = outgoing.send().await.map_err(|e| transport_error(&e))?;
94        let status = reply.status().as_u16();
95        let mut body = Vec::new();
96        if !(300..400).contains(&status) && status != 204 {
97            while let Some(chunk) = reply.chunk().await.map_err(|e| transport_error(&e))? {
98                if chunk.len() > MAX_BODY - body.len() {
99                    return Err(too_large(status));
100                }
101                body.extend_from_slice(&chunk);
102            }
103        }
104        Ok(HttpResponse { status, body })
105    }
106}
107
108fn transport_error(error: &reqwest::Error) -> OwlAuthError {
109    if error.is_timeout() {
110        timeout()
111    } else {
112        OwlAuthError::new(
113            "network_error",
114            "Runtime request failed to reach the service",
115            None,
116        )
117    }
118}
119
120pub(crate) fn timeout() -> OwlAuthError {
121    OwlAuthError::new("timeout", "Runtime request timed out", None)
122}
123
124pub(crate) fn too_large(status: u16) -> OwlAuthError {
125    OwlAuthError::new(
126        "response_too_large",
127        "Runtime response is too large",
128        Some(status),
129    )
130}