tez 0.0.3

A lightweight, ergonomic, and fast high-level HTTP client for Rust
Documentation
use std::{convert::TryFrom, future::Future, pin::Pin};

use base64::{Engine as _, engine::general_purpose::STANDARD};
use http::{HeaderName, HeaderValue, header::AUTHORIZATION};
use secrecy::{ExposeSecret as _, SecretString};

use crate::{Error, Request, Result};

/// Authenticates a request before it is sent.
///
/// Implementations own their complete authentication behavior: they may
/// refresh credentials asynchronously, inspect the request, and replace the
/// headers they control. Tez invokes authentication once per
/// [`crate::Client::send`] call, before the first network attempt. Mark custom
/// credential header values sensitive so cross-origin redirects remove them.
pub trait Authentication: Send + Sync {
    /// Applies authentication to the request.
    ///
    /// Implementations should map credential-provider failures to
    /// [`Error::authentication`] so their details are not exposed.
    fn authenticate<'request>(
        &'request self,
        request: &'request mut Request,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'request>>;
}

/// API-key authentication carried in a request header.
#[derive(Clone, Debug)]
pub struct ApiKeyAuth {
    name: HeaderName,
    value: SecretString,
}

impl ApiKeyAuth {
    /// Creates header-based API-key authentication.
    ///
    /// # Errors
    ///
    /// Returns an error when the header name or API key is not a valid HTTP
    /// header.
    pub fn new<K>(name: K, value: impl Into<SecretString>) -> Result<Self>
    where
        HeaderName: TryFrom<K>,
    {
        let name = HeaderName::try_from(name)
            .map_err(|_| Error::request("API key header name is invalid"))?;
        let value = value.into();
        api_key(value.expose_secret())?;
        Ok(Self { name, value })
    }
}

impl Authentication for ApiKeyAuth {
    fn authenticate<'request>(
        &'request self,
        request: &'request mut Request,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'request>> {
        let name = self.name.clone();
        let value = api_key(self.value.expose_secret());
        Box::pin(async move {
            let value = value?;
            request.headers_mut().insert(name, value);
            Ok(())
        })
    }
}

/// HTTP Basic authentication.
#[derive(Clone, Debug)]
pub struct BasicAuth {
    username: String,
    password: SecretString,
}

impl BasicAuth {
    /// Creates HTTP Basic authentication.
    ///
    /// # Errors
    ///
    /// Returns an error when the username contains `:` or either credential
    /// contains an ASCII control character.
    pub fn new(username: impl AsRef<str>, password: impl Into<SecretString>) -> Result<Self> {
        let username = username.as_ref().to_owned();
        let password = password.into();
        basic(&username, password.expose_secret())
            .ok_or_else(|| Error::request("Basic authentication is invalid"))?;
        Ok(Self { username, password })
    }
}

impl Authentication for BasicAuth {
    fn authenticate<'request>(
        &'request self,
        request: &'request mut Request,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'request>> {
        let authorization = basic(&self.username, self.password.expose_secret())
            .ok_or_else(|| Error::request("Basic authentication is invalid"));
        Box::pin(async move {
            let authorization = authorization?;
            request.headers_mut().insert(AUTHORIZATION, authorization);
            Ok(())
        })
    }
}

/// HTTP Bearer authentication.
#[derive(Clone, Debug)]
pub struct BearerAuth {
    token: SecretString,
}

impl BearerAuth {
    /// Creates HTTP Bearer authentication.
    ///
    /// # Errors
    ///
    /// Returns an error when `token` is not a nonempty RFC 6750 bearer token.
    pub fn new(token: impl Into<SecretString>) -> Result<Self> {
        let token = token.into();
        bearer(token.expose_secret())
            .ok_or_else(|| Error::request("Bearer authentication is invalid"))?;
        Ok(Self { token })
    }
}

impl Authentication for BearerAuth {
    fn authenticate<'request>(
        &'request self,
        request: &'request mut Request,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'request>> {
        let authorization = bearer(self.token.expose_secret())
            .ok_or_else(|| Error::request("Bearer authentication is invalid"));
        Box::pin(async move {
            let authorization = authorization?;
            request.headers_mut().insert(AUTHORIZATION, authorization);
            Ok(())
        })
    }
}

fn basic(username: &str, password: &str) -> Option<HeaderValue> {
    if username.contains(':') || contains_control(username) || contains_control(password) {
        return None;
    }

    let mut credentials = String::with_capacity(username.len() + password.len() + 1);
    credentials.push_str(username);
    credentials.push(':');
    credentials.push_str(password);
    authorization("Basic", &STANDARD.encode(credentials))
}

fn bearer(token: &str) -> Option<HeaderValue> {
    if !valid_bearer_token(token) {
        return None;
    }
    authorization("Bearer", token)
}

fn api_key(value: &str) -> Result<HeaderValue> {
    let mut value =
        HeaderValue::try_from(value).map_err(|_| Error::request("API key is invalid"))?;
    value.set_sensitive(true);
    Ok(value)
}

fn authorization(scheme: &str, credentials: &str) -> Option<HeaderValue> {
    let mut header = String::with_capacity(scheme.len() + credentials.len() + 1);
    header.push_str(scheme);
    header.push(' ');
    header.push_str(credentials);

    let mut value = HeaderValue::from_bytes(header.as_bytes()).ok()?;
    value.set_sensitive(true);
    Some(value)
}

fn contains_control(value: &str) -> bool {
    value.bytes().any(|byte| byte.is_ascii_control())
}

fn valid_bearer_token(token: &str) -> bool {
    let mut has_credentials = false;
    let mut padding_started = false;

    for byte in token.bytes() {
        if byte == b'=' {
            if !has_credentials {
                return false;
            }
            padding_started = true;
        } else if padding_started
            || !matches!(
                byte,
                b'A'..=b'Z'
                    | b'a'..=b'z'
                    | b'0'..=b'9'
                    | b'-'
                    | b'.'
                    | b'_'
                    | b'~'
                    | b'+'
                    | b'/'
            )
        {
            return false;
        } else {
            has_credentials = true;
        }
    }

    has_credentials
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bearer_tokens_follow_rfc_6750_syntax() {
        for token in ["token", "header.payload.signature", "abc-._~+/=="] {
            assert!(valid_bearer_token(token));
        }
        for token in ["", "token with space", "token=middle", "=padding", "tøken"] {
            assert!(!valid_bearer_token(token));
        }
    }

    #[test]
    fn generated_values_are_sensitive() {
        assert!(basic("user", "password").unwrap().is_sensitive());
        assert!(bearer("token").unwrap().is_sensitive());
        assert!(api_key("secret").unwrap().is_sensitive());
    }

    #[test]
    fn api_key_debug_is_redacted() {
        let auth = ApiKeyAuth::new("x-api-key", "secret").unwrap();
        let debug = format!("{auth:?}");

        assert!(debug.contains("x-api-key"));
        assert!(!debug.contains("secret"));
    }

    #[test]
    fn authentication_redacts_its_credentials() {
        let api_key = ApiKeyAuth::new("x-api-key", "secret").unwrap();
        let basic = BasicAuth::new("user", "secret").unwrap();
        let bearer = BearerAuth::new("bearer-credential").unwrap();

        assert!(!format!("{api_key:?}").contains("secret"));
        assert!(!format!("{basic:?}").contains("secret"));
        assert!(!format!("{bearer:?}").contains("bearer-credential"));
    }
}