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
//! X-Forwarded-Prefix header.
//!
//! See [`XForwardedPrefix`] docs.

use std::future::{ready, Ready};

use actix_http::{
    error::ParseError,
    header::{Header, HeaderName, HeaderValue, InvalidHeaderValue, TryIntoHeaderValue},
    HttpMessage,
};
use actix_web::FromRequest;
use derive_more::{Deref, DerefMut, Display};
use http::uri::PathAndQuery;

/// Conventional `X-Forwarded-Prefix` header.
///
/// See <https://github.com/dotnet/aspnetcore/issues/23263#issuecomment-776192575>.
#[allow(clippy::declare_interior_mutable_const)]
pub const X_FORWARDED_PREFIX: HeaderName = HeaderName::from_static("x-forwarded-prefix");

/// The `X-Forwarded-Prefix` header, defined in [RFC XXX §X.X].
///
/// The `X-Forwarded-Prefix` header field is used
///
/// Also see
///
/// # Example Values
///
/// - `/`
/// - `/foo`
///
/// # Examples
///
/// ```
/// use actix_web::HttpResponse;
/// use actix_web_lab::header::XForwardedPrefix;
///
/// let mut builder = HttpResponse::Ok();
/// builder.insert_header(XForwardedPrefix("/bar".parse().unwrap()));
/// ```
///
/// [RFC 7234 §5.2]: https://datatracker.ietf.org/doc/html/rfc7234#section-5.2
#[derive(Debug, Clone, PartialEq, Eq, Deref, DerefMut, Display)]
pub struct XForwardedPrefix(pub PathAndQuery);

impl TryIntoHeaderValue for XForwardedPrefix {
    type Error = InvalidHeaderValue;

    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
        HeaderValue::try_from(self.to_string())
    }
}

impl Header for XForwardedPrefix {
    fn name() -> HeaderName {
        X_FORWARDED_PREFIX
    }

    fn parse<M: HttpMessage>(msg: &M) -> Result<Self, ParseError> {
        let header = msg.headers().get(Self::name());

        header
            .and_then(|hdr| hdr.to_str().ok())
            .map(|hdr| hdr.trim())
            .filter(|hdr| !hdr.is_empty())
            .and_then(|hdr| hdr.parse::<actix_web::http::uri::PathAndQuery>().ok())
            .filter(|path| path.query().is_none())
            .map(XForwardedPrefix)
            .ok_or(ParseError::Header)
    }
}

#[cfg(test)]
mod header_tests {
    use actix_web::test::{self};

    use super::*;

    #[test]
    fn deref() {
        let mut fwd_prefix = XForwardedPrefix(PathAndQuery::from_static("/"));
        let _: &PathAndQuery = &fwd_prefix;
        let _: &mut PathAndQuery = &mut fwd_prefix;
    }

    #[test]
    fn no_headers() {
        let req = test::TestRequest::default().to_http_request();
        assert_eq!(XForwardedPrefix::parse(&req).ok(), None);
    }

    #[test]
    fn empty_header() {
        let req = test::TestRequest::default()
            .insert_header((X_FORWARDED_PREFIX, ""))
            .to_http_request();

        assert_eq!(XForwardedPrefix::parse(&req).ok(), None);
    }

    #[test]
    fn single_header() {
        let req = test::TestRequest::default()
            .insert_header((X_FORWARDED_PREFIX, "/foo"))
            .to_http_request();

        assert_eq!(
            XForwardedPrefix::parse(&req).ok().unwrap(),
            XForwardedPrefix(PathAndQuery::from_static("/foo")),
        );
    }

    #[test]
    fn multiple_headers() {
        let req = test::TestRequest::default()
            .append_header((X_FORWARDED_PREFIX, "/foo"))
            .append_header((X_FORWARDED_PREFIX, "/bar"))
            .to_http_request();

        assert_eq!(
            XForwardedPrefix::parse(&req).ok().unwrap(),
            XForwardedPrefix(PathAndQuery::from_static("/foo")),
        );
    }
}

/// Reconstructed path using x-forwarded-prefix header.
///
/// ```
/// # use actix_web::{FromRequest as _, test::TestRequest};
/// # actix_web::rt::System::new().block_on(async {
/// use actix_web_lab::extract::ReconstructedPath;
///
/// let req = TestRequest::with_uri("/bar")
///     .insert_header(("x-forwarded-prefix", "/foo"))
///     .to_http_request();
///
/// let path = ReconstructedPath::extract(&req).await.unwrap();
/// assert_eq!(format!("{path}"), "/foo/bar");
/// # })
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Display)]
pub struct ReconstructedPath(pub PathAndQuery);

impl FromRequest for ReconstructedPath {
    type Error = actix_web::Error;
    type Future = Ready<Result<Self, Self::Error>>;

    fn from_request(
        req: &actix_web::HttpRequest,
        _payload: &mut actix_http::Payload,
    ) -> Self::Future {
        let parts = req.head().uri.clone().into_parts();
        let path_and_query = parts
            .path_and_query
            .unwrap_or(PathAndQuery::from_static("/"));

        let prefix = XForwardedPrefix::parse(req).unwrap();

        let reconstructed = [prefix.as_str(), path_and_query.as_str()].concat();

        ready(Ok(ReconstructedPath(
            PathAndQuery::from_maybe_shared(reconstructed).unwrap(),
        )))
    }
}

#[cfg(test)]
mod extractor_tests {
    use actix_web::test::{self};

    use super::*;

    #[actix_web::test]
    async fn basic() {
        let req = test::TestRequest::with_uri("/bar")
            .insert_header((X_FORWARDED_PREFIX, "/foo"))
            .to_http_request();

        assert_eq!(
            ReconstructedPath::extract(&req).await.unwrap(),
            ReconstructedPath(PathAndQuery::from_static("/foo/bar")),
        );
    }
}