use http::{
HeaderMap, Method, StatusCode, Uri, Version,
header::{
AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, COOKIE, HOST, LOCATION, PROXY_AUTHORIZATION,
TRANSFER_ENCODING,
},
};
use url::Url;
use crate::{Body, Error, Request, Response, Result, body::Replayable};
const SAME_ORIGIN_REDIRECT_LIMIT: usize = 10;
const REDIRECT_LIMIT: usize = 10;
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum Policy {
#[default]
NoFollow,
SameOrigin,
Follow,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum Decision {
Follow,
Return,
Error,
}
pub(crate) fn decide(
policy: Policy,
https_only: bool,
previous: &Url,
next: &Url,
previous_requests: usize,
) -> Decision {
match policy {
Policy::NoFollow => Decision::Return,
Policy::SameOrigin => {
if https_only && next.scheme() != "https" {
return Decision::Error;
}
if previous.origin() != next.origin() {
return Decision::Return;
}
if previous_requests > SAME_ORIGIN_REDIRECT_LIMIT {
return Decision::Error;
}
Decision::Follow
}
Policy::Follow => {
let violates_https_only = https_only && next.scheme() != "https";
let downgrades_https = previous.scheme() == "https" && next.scheme() == "http";
if violates_https_only || downgrades_https {
return Decision::Error;
}
if previous_requests > REDIRECT_LIMIT {
return Decision::Error;
}
Decision::Follow
}
}
}
pub(crate) struct RequestChain {
method: Method,
uri: Uri,
version: Version,
headers: HeaderMap,
extensions: http::Extensions,
body: ChainBody,
}
pub(crate) struct Redirect {
pub(crate) previous: Url,
pub(crate) next: Url,
uri: Uri,
}
enum ChainBody {
Replayable(Replayable),
Streaming(Option<Body>),
}
impl RequestChain {
pub(crate) fn new(request: Request) -> Self {
let (parts, body) = request.into_parts();
let body = match body.into_replayable() {
Ok(body) => ChainBody::Replayable(body),
Err(body) => ChainBody::Streaming(Some(body)),
};
Self {
method: parts.method,
uri: parts.uri,
version: parts.version,
headers: parts.headers,
extensions: parts.extensions,
body,
}
}
pub(crate) fn request(&mut self) -> Option<Request> {
let body = match &mut self.body {
ChainBody::Replayable(body) => body.body(),
ChainBody::Streaming(body) => body.take()?,
};
let mut request = Request::new(body);
*request.method_mut() = self.method.clone();
*request.uri_mut() = self.uri.clone();
*request.version_mut() = self.version;
*request.headers_mut() = self.headers.clone();
*request.extensions_mut() = self.extensions.clone();
Some(request)
}
pub(crate) fn redirect(&self, response: &Response) -> Result<Option<Redirect>> {
if !is_followable(response.status()) || !self.can_replay(response.status()) {
return Ok(None);
}
let Some(location) = response.headers().get(LOCATION) else {
return Ok(None);
};
let location = location.to_str().map_err(|_| Error::redirect())?;
let previous = Url::parse(&self.uri.to_string()).map_err(|_| Error::redirect())?;
let next = previous.join(location).map_err(|_| Error::redirect())?;
let uri = next.as_str().parse().map_err(|_| Error::redirect())?;
Ok(Some(Redirect {
previous,
next,
uri,
}))
}
pub(crate) fn follow(&mut self, response: &Response, redirect: Redirect) {
if redirect.previous.origin() != redirect.next.origin() {
for name in [AUTHORIZATION, COOKIE, PROXY_AUTHORIZATION, HOST] {
self.headers.remove(name);
}
let sensitive = self
.headers
.keys()
.filter(|name| {
self.headers
.get_all(*name)
.iter()
.any(http::HeaderValue::is_sensitive)
})
.cloned()
.collect::<Vec<_>>();
for name in sensitive {
self.headers.remove(name);
}
}
match response.status() {
StatusCode::SEE_OTHER => self.rewrite_to_get(),
StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND if self.method == Method::POST => {
self.rewrite_to_get();
}
_ => {}
}
self.uri = redirect.uri;
}
fn can_replay(&self, status: StatusCode) -> bool {
!matches!(self.body, ChainBody::Streaming(_))
|| status == StatusCode::SEE_OTHER
|| matches!(status, StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND)
&& self.method == Method::POST
}
fn rewrite_to_get(&mut self) {
if self.method != Method::HEAD {
self.method = Method::GET;
}
self.body = ChainBody::Replayable(Replayable::Empty);
self.headers.remove(CONTENT_LENGTH);
self.headers.remove(CONTENT_TYPE);
self.headers.remove(TRANSFER_ENCODING);
}
}
const fn is_followable(status: StatusCode) -> bool {
matches!(
status,
StatusCode::MOVED_PERMANENTLY
| StatusCode::FOUND
| StatusCode::SEE_OTHER
| StatusCode::TEMPORARY_REDIRECT
| StatusCode::PERMANENT_REDIRECT
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn origins_include_scheme_host_and_effective_port() {
let url = |value| Url::parse(value).unwrap();
assert_eq!(
url("http://example.com/path").origin(),
url("http://example.com:80/elsewhere").origin(),
);
assert_eq!(
url("https://example.com/path").origin(),
url("https://example.com:443/elsewhere").origin(),
);
assert_ne!(
url("http://example.com").origin(),
url("https://example.com").origin(),
);
assert_ne!(
url("https://example.com").origin(),
url("https://api.example.com").origin(),
);
assert_ne!(
url("https://example.com:443").origin(),
url("https://example.com:8443").origin(),
);
}
#[test]
fn crossing_origins_removes_authority_bound_headers() {
let mut request = Request::new(Body::empty());
*request.uri_mut() = "https://one.example/start".parse().unwrap();
request
.headers_mut()
.insert(AUTHORIZATION, "secret".parse().unwrap());
request
.headers_mut()
.insert(COOKIE, "session=secret".parse().unwrap());
request
.headers_mut()
.insert(PROXY_AUTHORIZATION, "secret".parse().unwrap());
request
.headers_mut()
.insert(HOST, "one.example".parse().unwrap());
let mut secret = http::HeaderValue::from_static("secret");
secret.set_sensitive(true);
request.headers_mut().insert("x-api-key", secret);
let mut chain = RequestChain::new(request);
let mut response = http::Response::new(Body::empty());
*response.status_mut() = StatusCode::FOUND;
response
.headers_mut()
.insert(LOCATION, "https://two.example/next".parse().unwrap());
let (parts, body) = response.into_parts();
let response = Response::new(
parts,
body,
"https://one.example/start".parse().unwrap(),
None,
crate::Limits::default().response_body(1024),
);
let redirect = chain.redirect(&response).unwrap().unwrap();
chain.follow(&response, redirect);
let redirected = chain.request().unwrap();
for name in [
AUTHORIZATION,
COOKIE,
PROXY_AUTHORIZATION,
HOST,
http::HeaderName::from_static("x-api-key"),
] {
assert!(!redirected.headers().contains_key(name));
}
}
#[test]
fn only_redirect_statuses_can_create_follow_up_requests() {
let mut request = Request::new(Body::empty());
*request.uri_mut() = "https://example.com/start".parse().unwrap();
let chain = RequestChain::new(request);
let mut response = http::Response::new(Body::empty());
*response.status_mut() = StatusCode::MULTIPLE_CHOICES;
response
.headers_mut()
.insert(LOCATION, "https://example.com/next".parse().unwrap());
let (parts, body) = response.into_parts();
let response = Response::new(
parts,
body,
"https://example.com/start".parse().unwrap(),
None,
crate::Limits::default().response_body(1024),
);
assert!(chain.redirect(&response).unwrap().is_none());
}
}