rama_http/layer/remove_header/
request.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
//! Remove headers from a request.
//!
//! # Example
//!
//! ```
//! use rama_http::layer::remove_header::RemoveRequestHeaderLayer;
//! use rama_http::{Body, Request, Response, header::{self, HeaderValue}};
//! use rama_core::service::service_fn;
//! use rama_core::{Context, Service, Layer};
//! use rama_core::error::BoxError;
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), BoxError> {
//! # let http_client = service_fn(|_: Request| async move {
//! #     Ok::<_, std::convert::Infallible>(Response::new(Body::empty()))
//! # });
//! #
//! let mut svc = (
//!     // Layer that removes all request headers with the prefix `x-foo`.`ac
//!     RemoveRequestHeaderLayer::prefix("x-foo"),
//! ).layer(http_client);
//!
//! let request = Request::new(Body::empty());
//!
//! let response = svc.serve(Context::default(), request).await?;
//! #
//! # Ok(())
//! # }
//! ```

use crate::{HeaderName, Request, Response};
use rama_core::{Context, Layer, Service};
use rama_utils::macros::define_inner_service_accessors;
use std::{borrow::Cow, fmt, future::Future};

#[derive(Debug, Clone)]
/// Layer that applies [`RemoveRequestHeader`] which removes request headers.
///
/// See [`RemoveRequestHeader`] for more details.
pub struct RemoveRequestHeaderLayer {
    mode: RemoveRequestHeaderMode,
}

#[derive(Debug, Clone)]
enum RemoveRequestHeaderMode {
    Prefix(Cow<'static, str>),
    Exact(HeaderName),
    Hop,
}

impl RemoveRequestHeaderLayer {
    /// Create a new [`RemoveRequestHeaderLayer`].
    ///
    /// Removes request headers by prefix.
    pub fn prefix(prefix: impl Into<Cow<'static, str>>) -> Self {
        Self {
            mode: RemoveRequestHeaderMode::Prefix(prefix.into()),
        }
    }

    /// Create a new [`RemoveRequestHeaderLayer`].
    ///
    /// Removes the request header with the exact name.
    pub fn exact(header: HeaderName) -> Self {
        Self {
            mode: RemoveRequestHeaderMode::Exact(header),
        }
    }

    /// Create a new [`RemoveRequestHeaderLayer`].
    ///
    /// Removes all hop-by-hop request headers as specified in [RFC 2616](https://datatracker.ietf.org/doc/html/rfc2616#section-13.5.1).
    /// This does not support other hop-by-hop headers defined in [section-14.10](https://datatracker.ietf.org/doc/html/rfc2616#section-14.10).
    pub fn hop_by_hop() -> Self {
        Self {
            mode: RemoveRequestHeaderMode::Hop,
        }
    }
}

impl<S> Layer<S> for RemoveRequestHeaderLayer {
    type Service = RemoveRequestHeader<S>;

    fn layer(&self, inner: S) -> Self::Service {
        RemoveRequestHeader {
            inner,
            mode: self.mode.clone(),
        }
    }
}

/// Middleware that removes headers from a request.
pub struct RemoveRequestHeader<S> {
    inner: S,
    mode: RemoveRequestHeaderMode,
}

impl<S> RemoveRequestHeader<S> {
    /// Create a new [`RemoveRequestHeader`].
    ///
    /// Removes headers by prefix.
    pub fn prefix(prefix: impl Into<Cow<'static, str>>, inner: S) -> Self {
        RemoveRequestHeaderLayer::prefix(prefix.into()).layer(inner)
    }

    /// Create a new [`RemoveRequestHeader`].
    ///
    /// Removes the header with the exact name.
    pub fn exact(header: HeaderName, inner: S) -> Self {
        RemoveRequestHeaderLayer::exact(header).layer(inner)
    }

    /// Create a new [`RemoveRequestHeader`].
    ///
    /// Removes all hop-by-hop headers as specified in [RFC 2616](https://datatracker.ietf.org/doc/html/rfc2616#section-13.5.1).
    /// This does not support other hop-by-hop headers defined in [section-14.10](https://datatracker.ietf.org/doc/html/rfc2616#section-14.10).
    pub fn hop_by_hop(inner: S) -> Self {
        RemoveRequestHeaderLayer::hop_by_hop().layer(inner)
    }

    define_inner_service_accessors!();
}

impl<S: fmt::Debug> fmt::Debug for RemoveRequestHeader<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RemoveRequestHeader")
            .field("inner", &self.inner)
            .field("mode", &self.mode)
            .finish()
    }
}

impl<S: Clone> Clone for RemoveRequestHeader<S> {
    fn clone(&self) -> Self {
        RemoveRequestHeader {
            inner: self.inner.clone(),
            mode: self.mode.clone(),
        }
    }
}

impl<ReqBody, ResBody, State, S> Service<State, Request<ReqBody>> for RemoveRequestHeader<S>
where
    ReqBody: Send + 'static,
    ResBody: Send + 'static,
    State: Clone + Send + Sync + 'static,
    S: Service<State, Request<ReqBody>, Response = Response<ResBody>>,
{
    type Response = S::Response;
    type Error = S::Error;

    fn serve(
        &self,
        ctx: Context<State>,
        mut req: Request<ReqBody>,
    ) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send + '_ {
        match &self.mode {
            RemoveRequestHeaderMode::Hop => {
                super::remove_hop_by_hop_request_headers(req.headers_mut())
            }
            RemoveRequestHeaderMode::Prefix(prefix) => {
                super::remove_headers_by_prefix(req.headers_mut(), prefix)
            }
            RemoveRequestHeaderMode::Exact(header) => {
                super::remove_headers_by_exact_name(req.headers_mut(), header)
            }
        }
        self.inner.serve(ctx, req)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::{Body, Response};
    use rama_core::{service::service_fn, Layer, Service};
    use std::convert::Infallible;

    #[tokio::test]
    async fn remove_request_header_prefix() {
        let svc = RemoveRequestHeaderLayer::prefix("x-foo").layer(service_fn(
            |_ctx: Context<()>, req: Request| async move {
                assert!(req.headers().get("x-foo-bar").is_none());
                assert_eq!(
                    req.headers().get("foo").map(|v| v.to_str().unwrap()),
                    Some("bar")
                );
                Ok::<_, Infallible>(Response::new(Body::empty()))
            },
        ));
        let req = Request::builder()
            .header("x-foo-bar", "baz")
            .header("foo", "bar")
            .body(Body::empty())
            .unwrap();
        let _ = svc.serve(Context::default(), req).await.unwrap();
    }

    #[tokio::test]
    async fn remove_request_header_exact() {
        let svc = RemoveRequestHeaderLayer::exact(HeaderName::from_static("x-foo")).layer(
            service_fn(|_ctx: Context<()>, req: Request| async move {
                assert!(req.headers().get("x-foo").is_none());
                assert_eq!(
                    req.headers().get("x-foo-bar").map(|v| v.to_str().unwrap()),
                    Some("baz")
                );
                Ok::<_, Infallible>(Response::new(Body::empty()))
            }),
        );
        let req = Request::builder()
            .header("x-foo", "baz")
            .header("x-foo-bar", "baz")
            .body(Body::empty())
            .unwrap();
        let _ = svc.serve(Context::default(), req).await.unwrap();
    }

    #[tokio::test]
    async fn remove_request_header_hop_by_hop() {
        let svc = RemoveRequestHeaderLayer::hop_by_hop().layer(service_fn(
            |_ctx: Context<()>, req: Request| async move {
                assert!(req.headers().get("connection").is_none());
                assert_eq!(
                    req.headers().get("foo").map(|v| v.to_str().unwrap()),
                    Some("bar")
                );
                Ok::<_, Infallible>(Response::new(Body::empty()))
            },
        ));
        let req = Request::builder()
            .header("connection", "close")
            .header("foo", "bar")
            .body(Body::empty())
            .unwrap();
        let _ = svc.serve(Context::default(), req).await.unwrap();
    }
}