rama_http/layer/forwarded/get_forwarded.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
use crate::headers::{
ForwardHeader, HeaderMapExt, Via, XForwardedFor, XForwardedHost, XForwardedProto,
};
use crate::Request;
use rama_core::{Context, Layer, Service};
use rama_net::forwarded::Forwarded;
use rama_net::forwarded::ForwardedElement;
use rama_utils::macros::all_the_tuples_no_last_special_case;
use std::fmt;
use std::future::Future;
use std::marker::PhantomData;
/// Layer to extract [`Forwarded`] information from the specified `T` headers.
///
/// This layer can be used to extract the [`Forwarded`] information from any specified header `T`,
/// as long as the header implements the [`ForwardHeader`] trait. Multiple headers can be specified
/// as a tuple, and the layer will extract information from them all, and combine the information.
///
/// Please take into consideration the following when combining headers:
///
/// - The last header in the tuple will take precedence over the previous headers,
/// if the same information is present in multiple headers.
/// - Headers that can contain multiple elements, (e.g. X-Forwarded-For, Via)
/// will combine their elements in the order as specified. That does however mean that in
/// case one header has less elements then the other, that the combination down the line
/// will not be accurate.
///
/// The following headers are supported by default:
///
/// - [`GetForwardedHeadersLayer::forwarded`]: The standard [`Forwarded`] header [`RFC 7239`](https://tools.ietf.org/html/rfc7239).
/// - [`GetForwardedHeadersLayer::via`]: The canonical [`Via`] header [`RFC 7230`](https://tools.ietf.org/html/rfc7230#section-5.7.1).
/// - [`GetForwardedHeadersLayer::x_forwarded_for`]: The canonical [`X-Forwarded-For`] header [`RFC 7239`](https://tools.ietf.org/html/rfc7239#section-5.2).
/// - [`GetForwardedHeadersLayer::x_forwarded_host`]: The canonical [`X-Forwarded-Host`] header [`RFC 7239`](https://tools.ietf.org/html/rfc7239#section-5.4).
/// - [`GetForwardedHeadersLayer::x_forwarded_proto`]: The canonical [`X-Forwarded-Proto`] header [`RFC 7239`](https://tools.ietf.org/html/rfc7239#section-5.3).
///
/// Rama also has the following headers already implemented for you to use:
///
/// > [`X-Real-Ip`], [`X-Client-Ip`], [`Client-Ip`], [`Cf-Connecting-Ip`] and [`True-Client-Ip`].
///
/// There are no [`GetForwardedHeadersLayer`] constructors for these headers,
/// but you can use the [`GetForwardedHeadersLayer::new`] constructor and pass the header type as a type parameter,
/// alone or in a tuple with other headers.
///
/// [`X-Real-Ip`]: crate::headers::XRealIp
/// [`X-Client-Ip`]: crate::headers::XClientIp
/// [`Client-Ip`]: crate::headers::ClientIp
/// [`CF-Connecting-Ip`]: crate::headers::CFConnectingIp
/// [`True-Client-Ip`]: crate::headers::TrueClientIp
///
/// ## Example
///
/// This example shows you can extract the client IP from the `X-Forwarded-For`
/// header in case your application is behind a proxy which sets this header.
///
/// ```rust
/// use rama_core::{
/// service::service_fn,
/// Context, Service, Layer,
/// };
/// use rama_http::{headers::Forwarded, layer::forwarded::GetForwardedHeadersLayer, Request};
/// use std::{convert::Infallible, net::IpAddr};
///
/// #[tokio::main]
/// async fn main() {
/// let service = GetForwardedHeadersLayer::x_forwarded_for()
/// .layer(service_fn(|ctx: Context<()>, _| async move {
/// let forwarded = ctx.get::<Forwarded>().unwrap();
/// assert_eq!(forwarded.client_ip(), Some(IpAddr::from([12, 23, 34, 45])));
/// assert!(forwarded.client_proto().is_none());
///
/// // ...
///
/// Ok::<_, Infallible>(())
/// }));
///
/// let req = Request::builder()
/// .header("X-Forwarded-For", "12.23.34.45")
/// .body(())
/// .unwrap();
///
/// service.serve(Context::default(), req).await.unwrap();
/// }
/// ```
pub struct GetForwardedHeadersLayer<T = Forwarded> {
_headers: PhantomData<fn() -> T>,
}
impl<T: fmt::Debug> fmt::Debug for GetForwardedHeadersLayer<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("GetForwardedHeadersLayer")
.field(
"_headers",
&format_args!("{}", std::any::type_name::<fn() -> T>()),
)
.finish()
}
}
impl<T: Clone> Clone for GetForwardedHeadersLayer<T> {
fn clone(&self) -> Self {
Self {
_headers: PhantomData,
}
}
}
impl Default for GetForwardedHeadersLayer {
fn default() -> Self {
Self::forwarded()
}
}
impl<T> GetForwardedHeadersLayer<T> {
/// Create a new `GetForwardedHeadersLayer` for the specified headers `T`.
pub const fn new() -> Self {
Self {
_headers: PhantomData,
}
}
}
impl GetForwardedHeadersLayer {
#[inline]
/// Create a new `GetForwardedHeadersLayer` for the standard [`Forwarded`] header.
pub fn forwarded() -> Self {
Self::new()
}
}
impl GetForwardedHeadersLayer<Via> {
#[inline]
/// Create a new `GetForwardedHeadersLayer` for the canonical [`Via`] header.
pub fn via() -> Self {
Self::new()
}
}
impl GetForwardedHeadersLayer<XForwardedFor> {
#[inline]
/// Create a new `GetForwardedHeadersLayer` for the canonical [`X-Forwarded-For`] header.
pub fn x_forwarded_for() -> Self {
Self::new()
}
}
impl GetForwardedHeadersLayer<XForwardedHost> {
#[inline]
/// Create a new `GetForwardedHeadersLayer` for the canonical [`X-Forwarded-Host`] header.
pub fn x_forwarded_host() -> Self {
Self::new()
}
}
impl GetForwardedHeadersLayer<XForwardedProto> {
#[inline]
/// Create a new `GetForwardedHeadersLayer` for the canonical [`X-Forwarded-Proto`] header.
pub fn x_forwarded_proto() -> Self {
Self::new()
}
}
impl<H, S> Layer<S> for GetForwardedHeadersLayer<H> {
type Service = GetForwardedHeadersService<S, H>;
fn layer(&self, inner: S) -> Self::Service {
Self::Service {
inner,
_headers: PhantomData,
}
}
}
/// Middleware service to extract [`Forwarded`] information from the specified `T` headers.
///
/// See [`GetForwardedHeadersLayer`] for more information.
pub struct GetForwardedHeadersService<S, T = Forwarded> {
inner: S,
_headers: PhantomData<fn() -> T>,
}
impl<S: fmt::Debug, T> fmt::Debug for GetForwardedHeadersService<S, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GetForwardedHeadersService")
.field("inner", &self.inner)
.field("_headers", &format_args!("{}", std::any::type_name::<T>()))
.finish()
}
}
impl<S: Clone, T> Clone for GetForwardedHeadersService<S, T> {
fn clone(&self) -> Self {
GetForwardedHeadersService {
inner: self.inner.clone(),
_headers: PhantomData,
}
}
}
impl<S, T> GetForwardedHeadersService<S, T> {
/// Create a new `GetForwardedHeadersService` for the specified headers `T`.
pub const fn new(inner: S) -> Self {
Self {
inner,
_headers: PhantomData,
}
}
}
impl<S> GetForwardedHeadersService<S> {
#[inline]
/// Create a new `GetForwardedHeadersService` for the standard [`Forwarded`] header.
pub fn forwarded(inner: S) -> Self {
Self::new(inner)
}
}
impl<S> GetForwardedHeadersService<S, Via> {
#[inline]
/// Create a new `GetForwardedHeadersService` for the canonical [`Via`] header.
pub fn via(inner: S) -> Self {
Self::new(inner)
}
}
impl<S> GetForwardedHeadersService<S, XForwardedFor> {
#[inline]
/// Create a new `GetForwardedHeadersService` for the canonical [`X-Forwarded-For`] header.
pub fn x_forwarded_for(inner: S) -> Self {
Self::new(inner)
}
}
impl<S> GetForwardedHeadersService<S, XForwardedHost> {
#[inline]
/// Create a new `GetForwardedHeadersService` for the canonical [`X-Forwarded-Host`] header.
pub fn x_forwarded_host(inner: S) -> Self {
Self::new(inner)
}
}
impl<S> GetForwardedHeadersService<S, XForwardedProto> {
#[inline]
/// Create a new `GetForwardedHeadersService` for the canonical [`X-Forwarded-Proto`] header.
pub fn x_forwarded_proto(inner: S) -> Self {
Self::new(inner)
}
}
macro_rules! get_forwarded_service_for_tuple {
( $($ty:ident),* $(,)? ) => {
#[allow(non_snake_case)]
impl<$($ty,)* S, State, Body> Service<State, Request<Body>> for GetForwardedHeadersService<S, ($($ty,)*)>
where
$( $ty: ForwardHeader + Send + Sync + 'static, )*
S: Service<State, Request<Body>>,
Body: Send + 'static,
State: Clone + Send + Sync + 'static,
{
type Response = S::Response;
type Error = S::Error;
fn serve(
&self,
mut ctx: Context<State>,
req: Request<Body>,
) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send + '_ {
let mut forwarded_elements: Vec<ForwardedElement> = Vec::with_capacity(1);
$(
if let Some($ty) = req.headers().typed_get::<$ty>() {
let mut iter = $ty.into_iter();
for element in forwarded_elements.iter_mut() {
let other = iter.next();
match other {
Some(other) => {
element.merge(other);
}
None => break,
}
}
for other in iter {
forwarded_elements.push(other);
}
}
)*
if !forwarded_elements.is_empty() {
match ctx.get_mut::<Forwarded>() {
Some(ref mut f) => {
f.extend(forwarded_elements);
}
None => {
let mut it = forwarded_elements.into_iter();
let mut forwarded = Forwarded::new(it.next().unwrap());
forwarded.extend(it);
ctx.insert(forwarded);
}
}
}
self.inner.serve(ctx, req)
}
}
}
}
impl<H, S, State, Body> Service<State, Request<Body>> for GetForwardedHeadersService<S, H>
where
H: ForwardHeader + Send + Sync + 'static,
S: Service<State, Request<Body>>,
Body: Send + 'static,
State: Clone + Send + Sync + 'static,
{
type Response = S::Response;
type Error = S::Error;
fn serve(
&self,
mut ctx: Context<State>,
req: Request<Body>,
) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send + '_ {
let mut forwarded_elements: Vec<ForwardedElement> = Vec::with_capacity(1);
if let Some(header) = req.headers().typed_get::<H>() {
forwarded_elements.extend(header);
}
if !forwarded_elements.is_empty() {
match ctx.get_mut::<Forwarded>() {
Some(ref mut f) => {
f.extend(forwarded_elements);
}
None => {
let mut it = forwarded_elements.into_iter();
let mut forwarded = Forwarded::new(it.next().unwrap());
forwarded.extend(it);
ctx.insert(forwarded);
}
}
}
self.inner.serve(ctx, req)
}
}
all_the_tuples_no_last_special_case!(get_forwarded_service_for_tuple);
#[cfg(test)]
mod tests {
use super::*;
use crate::{
headers::{ClientIp, TrueClientIp, XClientIp, XRealIp},
IntoResponse, Response, StatusCode,
};
use rama_core::{error::OpaqueError, service::service_fn, Layer};
use rama_net::forwarded::{ForwardedProtocol, ForwardedVersion};
use std::{convert::Infallible, net::IpAddr};
fn assert_is_service<T: Service<(), Request<()>>>(_: T) {}
async fn dummy_service_fn() -> Result<Response, OpaqueError> {
Ok(StatusCode::OK.into_response())
}
#[test]
fn test_get_forwarded_service_is_service() {
assert_is_service(GetForwardedHeadersService::forwarded(service_fn(
dummy_service_fn,
)));
assert_is_service(GetForwardedHeadersService::via(service_fn(
dummy_service_fn,
)));
assert_is_service(GetForwardedHeadersService::x_forwarded_for(service_fn(
dummy_service_fn,
)));
assert_is_service(GetForwardedHeadersService::x_forwarded_proto(service_fn(
dummy_service_fn,
)));
assert_is_service(GetForwardedHeadersService::x_forwarded_host(service_fn(
dummy_service_fn,
)));
assert_is_service(GetForwardedHeadersService::<_, TrueClientIp>::new(
service_fn(dummy_service_fn),
));
assert_is_service(GetForwardedHeadersService::<_, (TrueClientIp,)>::new(
service_fn(dummy_service_fn),
));
assert_is_service(
GetForwardedHeadersService::<_, (TrueClientIp, XClientIp)>::new(service_fn(
dummy_service_fn,
)),
);
assert_is_service(
GetForwardedHeadersLayer::forwarded().layer(service_fn(dummy_service_fn)),
);
assert_is_service(GetForwardedHeadersLayer::via().layer(service_fn(dummy_service_fn)));
assert_is_service(
GetForwardedHeadersLayer::<XRealIp>::new().layer(service_fn(dummy_service_fn)),
);
assert_is_service(
GetForwardedHeadersLayer::<(ClientIp, TrueClientIp)>::new()
.layer(service_fn(dummy_service_fn)),
);
}
#[tokio::test]
async fn test_get_forwarded_header_forwarded() {
let service = GetForwardedHeadersLayer::forwarded().layer(service_fn(
|ctx: Context<()>, _| async move {
let forwarded = ctx.get::<Forwarded>().unwrap();
assert_eq!(forwarded.client_ip(), Some(IpAddr::from([12, 23, 34, 45])));
assert_eq!(forwarded.client_proto(), Some(ForwardedProtocol::HTTP));
Ok::<_, Infallible>(())
},
));
let req = Request::builder()
.header("Forwarded", "for=\"12.23.34.45:5000\";proto=http")
.body(())
.unwrap();
service.serve(Context::default(), req).await.unwrap();
}
#[tokio::test]
async fn test_get_forwarded_header_via() {
let service =
GetForwardedHeadersLayer::via().layer(service_fn(|ctx: Context<()>, _| async move {
let forwarded = ctx.get::<Forwarded>().unwrap();
assert!(forwarded.client_ip().is_none());
assert_eq!(
forwarded.iter().next().unwrap().ref_forwarded_by(),
Some(&(IpAddr::from([12, 23, 34, 45]), 5000).into())
);
assert!(forwarded.client_proto().is_none());
assert_eq!(forwarded.client_version(), Some(ForwardedVersion::HTTP_11));
Ok::<_, Infallible>(())
}));
let req = Request::builder()
.header("Via", "1.1 12.23.34.45:5000")
.body(())
.unwrap();
service.serve(Context::default(), req).await.unwrap();
}
#[tokio::test]
async fn test_get_forwarded_header_x_forwarded_for() {
let service = GetForwardedHeadersLayer::x_forwarded_for().layer(service_fn(
|ctx: Context<()>, _| async move {
let forwarded = ctx.get::<Forwarded>().unwrap();
assert_eq!(forwarded.client_ip(), Some(IpAddr::from([12, 23, 34, 45])));
assert!(forwarded.client_proto().is_none());
Ok::<_, Infallible>(())
},
));
let req = Request::builder()
.header("X-Forwarded-For", "12.23.34.45, 127.0.0.1")
.body(())
.unwrap();
service.serve(Context::default(), req).await.unwrap();
}
}