tez 0.0.0

A lightweight, ergonomic, and fast high-level HTTP client for Rust
Documentation
use http::{Method, StatusCode, header::LOCATION};

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

/// Redirect handling policy.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum Redirect {
    /// Return redirect responses without following them.
    #[default]
    NoFollow,
    /// Follow at most this many eligible hops.
    ///
    /// Values are validated as `1..=10` when the client is built.
    Limit(u32),
    /// Follow eligible redirects up to tez's hard ceiling of ten hops.
    FollowAll,
}

impl Redirect {
    pub(crate) fn max_hops(self) -> Result<u32> {
        match self {
            Self::NoFollow => Ok(0),
            Self::Limit(limit @ 1..=10) => Ok(limit),
            Self::Limit(_) => Err(Error::invalid_request(
                "redirect limit must be between 1 and 10",
            )),
            Self::FollowAll => Ok(10),
        }
    }
}

pub(crate) fn redirect_request(
    response: &Response,
    sent: &Request,
    replay: Option<Request>,
) -> Result<Option<Request>> {
    if !matches!(
        response.status(),
        StatusCode::MOVED_PERMANENTLY
            | StatusCode::FOUND
            | StatusCode::SEE_OTHER
            | StatusCode::TEMPORARY_REDIRECT
            | StatusCode::PERMANENT_REDIRECT
    ) {
        return Ok(None);
    }

    let locations = response
        .headers()
        .get_all(LOCATION)
        .iter()
        .collect::<Vec<_>>();
    if locations.len() != 1 {
        return Ok(None);
    }
    let Some(location) = locations[0].to_str().ok() else {
        return Ok(None);
    };
    let Ok(mut target) = crate::client::resolve_url(Some(sent.url()), location) else {
        return Ok(None);
    };
    target.set_fragment(None);
    if !matches!(target.scheme(), "http" | "https")
        || target.host_str().is_none()
        || !target.username().is_empty()
        || target.password().is_some()
    {
        return Ok(None);
    }

    let status = response.status();
    let method = sent.method();
    let mut next = match status {
        StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND if method == Method::POST => {
            let mut request = sent.clone_without_body();
            request.set_method(Method::GET);
            request
        }
        StatusCode::SEE_OTHER => {
            let mut request = sent.clone_without_body();
            if method != Method::HEAD {
                request.set_method(Method::GET);
            }
            request
        }
        StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND
            if method != Method::GET && method != Method::HEAD =>
        {
            let Some(request) = replay else {
                return Ok(None);
            };
            request
        }
        StatusCode::TEMPORARY_REDIRECT | StatusCode::PERMANENT_REDIRECT => {
            let Some(request) = replay else {
                return Ok(None);
            };
            request
        }
        _ if sent.body_was_present() => {
            let Some(request) = replay else {
                return Ok(None);
            };
            request
        }
        _ => replay.unwrap_or_else(|| sent.clone_without_body()),
    };

    next.set_url(target);
    if matches!(
        status,
        StatusCode::SEE_OTHER | StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND
    ) && (method == Method::POST || status == StatusCode::SEE_OTHER)
    {
        next.remove_content_fields();
        next.replace_body(Body::default());
    }
    Ok(Some(next))
}

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

    #[test]
    fn it_redirect_limit_is_finite_and_validated() {
        assert_eq!(Redirect::NoFollow.max_hops().unwrap(), 0);
        assert_eq!(Redirect::Limit(1).max_hops().unwrap(), 1);
        assert_eq!(Redirect::Limit(10).max_hops().unwrap(), 10);
        assert_eq!(Redirect::FollowAll.max_hops().unwrap(), 10);
        assert!(Redirect::Limit(0).max_hops().is_err());
        assert!(Redirect::Limit(11).max_hops().is_err());
    }
}