tez 0.0.0

A lightweight, ergonomic, and fast high-level HTTP client for Rust
Documentation
use std::{fmt, sync::Arc};

use zeroize::Zeroizing;

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

/// Minimum accepted TLS protocol version.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum TlsVersion {
    /// Require TLS 1.2 or newer.
    #[default]
    Tls12,
    /// Require TLS 1.3.
    Tls13,
}

/// Owned custom trust anchor in PEM or DER form.
#[derive(Clone)]
pub struct Certificate {
    pub(crate) encoding: CertificateEncoding,
    pub(crate) bytes: Vec<u8>,
}

#[derive(Clone, Copy)]
pub(crate) enum CertificateEncoding {
    Pem,
    Der,
}

/// Owned PEM client certificate chain and private key.
#[derive(Clone)]
pub struct Identity {
    pub(crate) pem: Arc<Zeroizing<Vec<u8>>>,
}

/// Owned TLS configuration for a client.
#[derive(Clone, Debug)]
pub struct Tls {
    pub(crate) https_only: bool,
    pub(crate) minimum_version: TlsVersion,
    pub(crate) roots: Vec<Certificate>,
    pub(crate) identity: Option<Identity>,
}

impl Default for Tls {
    fn default() -> Self {
        Self {
            https_only: false,
            minimum_version: TlsVersion::Tls12,
            roots: Vec::new(),
            identity: None,
        }
    }
}

impl Tls {
    /// Creates TLS configuration using platform trust roots and TLS 1.2+.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Restricts the client to HTTPS URLs.
    #[must_use]
    pub fn https_only(mut self) -> Self {
        self.https_only = true;
        self
    }

    /// Sets the minimum accepted TLS protocol version.
    #[must_use]
    pub fn minimum_version(mut self, version: TlsVersion) -> Self {
        self.minimum_version = version;
        self
    }

    /// Adds a custom trust anchor in addition to platform roots.
    #[must_use]
    pub fn add_root(mut self, certificate: Certificate) -> Self {
        self.roots.push(certificate);
        self
    }

    /// Sets the PEM client identity used for mutual TLS.
    ///
    /// Building the client then requires an HTTPS base URL and no proxy. The
    /// identity is bound to that origin; it is never used for a cross-origin
    /// request or redirect.
    #[must_use]
    pub fn identity(mut self, identity: Identity) -> Self {
        self.identity = Some(identity);
        self
    }

    pub(crate) fn is_default(&self) -> bool {
        !self.https_only
            && self.minimum_version == TlsVersion::Tls12
            && self.roots.is_empty()
            && self.identity.is_none()
    }

    pub(crate) fn has_identity(&self) -> bool {
        self.identity.is_some()
    }
}

impl Certificate {
    /// Creates a custom trust anchor from PEM bytes.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is empty or lacks a PEM certificate
    /// marker. Full certificate parsing occurs when the client is built.
    pub fn from_pem(bytes: impl Into<Vec<u8>>) -> Result<Self> {
        let bytes = bytes.into();
        if bytes.is_empty()
            || !bytes
                .windows(b"-----BEGIN CERTIFICATE-----".len())
                .any(|window| window == b"-----BEGIN CERTIFICATE-----")
        {
            return Err(Error::new(
                ErrorKind::Tls,
                "TLS root must contain a PEM certificate",
            ));
        }
        Ok(Self {
            encoding: CertificateEncoding::Pem,
            bytes,
        })
    }

    /// Creates a custom trust anchor from DER bytes.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is empty.
    pub fn from_der(bytes: impl Into<Vec<u8>>) -> Result<Self> {
        let bytes = bytes.into();
        if bytes.is_empty() {
            return Err(Error::new(ErrorKind::Tls, "TLS DER root cannot be empty"));
        }
        Ok(Self {
            encoding: CertificateEncoding::Der,
            bytes,
        })
    }
}

impl Identity {
    /// Creates a mutual-TLS identity from a PEM certificate chain and key.
    ///
    /// # Errors
    ///
    /// Returns an error unless both certificate and private-key PEM blocks are
    /// present. The certificate chain must be leaf-first and the unencrypted
    /// key must be PKCS#8, PKCS#1 RSA, or SEC1 EC. Full cryptographic parsing
    /// occurs when the client is built.
    pub fn from_pem(pem: impl Into<Vec<u8>>) -> Result<Self> {
        let pem = pem.into();
        let certificate = pem
            .windows(b"-----BEGIN CERTIFICATE-----".len())
            .any(|window| window == b"-----BEGIN CERTIFICATE-----");
        let key = pem
            .windows(b"PRIVATE KEY-----".len())
            .any(|window| window == b"PRIVATE KEY-----");
        if !certificate || !key {
            return Err(Error::new(
                ErrorKind::Tls,
                "TLS identity must contain PEM certificate and private key blocks",
            ));
        }
        Ok(Self {
            pem: Arc::new(Zeroizing::new(pem)),
        })
    }
}

impl fmt::Debug for Certificate {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let encoding = match self.encoding {
            CertificateEncoding::Pem => "PEM",
            CertificateEncoding::Der => "DER",
        };
        formatter
            .debug_struct("Certificate")
            .field("encoding", &encoding)
            .field("length", &self.bytes.len())
            .finish()
    }
}

impl fmt::Debug for Identity {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Identity")
            .field("pem", &"[redacted]")
            .field("length", &self.pem.len())
            .finish()
    }
}

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

    #[test]
    fn it_tls_configuration_has_secure_defaults() {
        let tls = Tls::default();

        assert_eq!(tls.minimum_version, TlsVersion::Tls12);
        assert!(!tls.https_only);
        assert!(tls.roots.is_empty());
        assert!(tls.identity.is_none());
    }

    #[test]
    fn it_tls_identity_debug_never_prints_key_material() {
        let identity = Identity::from_pem(
            b"-----BEGIN CERTIFICATE-----\na\n-----END CERTIFICATE-----\n-----BEGIN PRIVATE KEY-----\nsecret-key\n-----END PRIVATE KEY-----",
        )
        .unwrap();

        assert!(!format!("{identity:?}").contains("secret-key"));
    }
}