use super::FromPartsStateRefPair;
use crate::utils::macros::define_http_rejection;
use rama_http_types::request::Parts;
use rama_net::address;
use rama_net::input_ext::AuthorityInputExt;
use rama_utils::macros::impl_deref;
#[derive(Debug, Clone)]
pub struct Authority(pub address::HostWithOptPort);
impl_deref!(Authority: address::HostWithOptPort);
define_http_rejection! {
#[status = BAD_REQUEST]
#[body = "Failed to detect the Http Authority"]
pub struct MissingAuthority;
}
impl<State> FromPartsStateRefPair<State> for Authority
where
State: Send + Sync,
{
type Rejection = MissingAuthority;
async fn from_parts_state_ref_pair(
parts: &Parts,
_state: &State,
) -> Result<Self, Self::Rejection> {
Ok(Self(parts.authority().ok_or(MissingAuthority)?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::StatusCode;
use crate::body::util::BodyExt;
use crate::header::X_FORWARDED_HOST;
use crate::layer::forwarded::GetForwardedHeaderService;
use crate::service::web::WebService;
use crate::{Body, HeaderName, Request};
use rama_core::Service;
async fn test_authority_from_request(
uri: &str,
authority: &str,
headers: Vec<(&HeaderName, &str)>,
) {
let svc = GetForwardedHeaderService::x_forwarded_host(
WebService::default().with_get("/", async |Authority(authority): Authority| {
authority.to_string()
}),
);
let mut builder = Request::builder().method("GET").uri(uri);
for (header, value) in headers {
builder = builder.header(header, value);
}
let req = builder.body(Body::empty()).unwrap();
let res = svc.serve(req).await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let body = res.into_body().collect().await.unwrap().to_bytes();
assert_eq!(body, authority);
}
#[tokio::test]
async fn host_header() {
test_authority_from_request(
"/",
"some-domain:123",
vec![(&rama_http_types::header::HOST, "some-domain:123")],
)
.await;
}
#[tokio::test]
async fn x_forwarded_host_header() {
test_authority_from_request(
"/",
"some-domain:456",
vec![(&X_FORWARDED_HOST, "some-domain:456")],
)
.await;
}
#[tokio::test]
async fn x_forwarded_host_precedence_over_host_header() {
test_authority_from_request(
"/",
"some-domain:456",
vec![
(&X_FORWARDED_HOST, "some-domain:456"),
(&rama_http_types::header::HOST, "some-domain:123"),
],
)
.await;
}
#[tokio::test]
async fn uri_host() {
test_authority_from_request("http://example.com", "example.com:80", vec![]).await;
}
}