owlauth-client 0.7.0

Rust Project Auth client for OwlAuth
Documentation
use std::{fmt, time::Duration};

use async_trait::async_trait;
use url::Url;

use crate::OwlAuthError;

pub(crate) const MAX_BODY: usize = 1024 * 1024;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HttpMethod {
    Get,
    Post,
}

pub struct HttpRequest {
    pub method: HttpMethod,
    pub url: Url,
    pub bearer: Option<String>,
    pub body: Option<Vec<u8>>,
    pub timeout: Duration,
}

impl fmt::Debug for HttpRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HttpRequest")
            .field("method", &self.method)
            .field("timeout", &self.timeout)
            .finish_non_exhaustive()
    }
}

pub struct HttpResponse {
    pub status: u16,
    pub body: Vec<u8>,
}

impl fmt::Debug for HttpResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HttpResponse")
            .field("status", &self.status)
            .finish_non_exhaustive()
    }
}

/// One bounded, cookie-free HTTP request without redirects or automatic retries.
#[async_trait]
pub trait Transport: Send + Sync {
    /// Send the request and return the response without following redirects.
    ///
    /// # Errors
    /// Returns the classified transport failure.
    async fn send(&self, request: HttpRequest) -> Result<HttpResponse, OwlAuthError>;
}

pub(crate) struct DefaultTransport(reqwest::Client);

impl DefaultTransport {
    pub(crate) fn new() -> Result<Self, OwlAuthError> {
        reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .retry(reqwest::retry::never())
            .no_proxy()
            .build()
            .map(Self)
            .map_err(|_| {
                OwlAuthError::new(
                    "invalid_configuration",
                    "Could not create Runtime HTTP transport",
                    None,
                )
            })
    }
}

#[async_trait]
impl Transport for DefaultTransport {
    async fn send(&self, request: HttpRequest) -> Result<HttpResponse, OwlAuthError> {
        let mut outgoing = match request.method {
            HttpMethod::Get => self.0.get(request.url),
            HttpMethod::Post => self.0.post(request.url),
        }
        .header(reqwest::header::ACCEPT, "application/json")
        .timeout(request.timeout);
        if let Some(token) = request.bearer {
            outgoing = outgoing.bearer_auth(token);
        }
        if let Some(body) = request.body {
            outgoing = outgoing
                .header(reqwest::header::CONTENT_TYPE, "application/json")
                .body(body);
        }
        let mut reply = outgoing.send().await.map_err(|e| transport_error(&e))?;
        let status = reply.status().as_u16();
        let mut body = Vec::new();
        if !(300..400).contains(&status) && status != 204 {
            while let Some(chunk) = reply.chunk().await.map_err(|e| transport_error(&e))? {
                if chunk.len() > MAX_BODY - body.len() {
                    return Err(too_large(status));
                }
                body.extend_from_slice(&chunk);
            }
        }
        Ok(HttpResponse { status, body })
    }
}

fn transport_error(error: &reqwest::Error) -> OwlAuthError {
    if error.is_timeout() {
        timeout()
    } else {
        OwlAuthError::new(
            "network_error",
            "Runtime request failed to reach the service",
            None,
        )
    }
}

pub(crate) fn timeout() -> OwlAuthError {
    OwlAuthError::new("timeout", "Runtime request timed out", None)
}

pub(crate) fn too_large(status: u16) -> OwlAuthError {
    OwlAuthError::new(
        "response_too_large",
        "Runtime response is too large",
        Some(status),
    )
}