Skip to main content

rama/http/client/proxy_connector/
forward.rs

1use crate::{
2    Service,
3    error::BoxError,
4    extensions::{Extensions, ExtensionsRef},
5    http::{
6        Request, Response, client::proxy::HttpForwardRoute,
7        layer::remove_header::remove_proxy_auth_request_headers,
8    },
9    net::{
10        ProtocolInputExt,
11        client::{
12            ConnectionError, ConnectorService, EstablishedClientConnection, ProxySelector as _,
13        },
14    },
15    telemetry::tracing,
16};
17
18/// Reach the origin of a request over the HTTP connection to the proxy forwarding it, or
19/// over a connection to the origin itself.
20///
21/// A forwarded request is served by `forward`, every other one by `origin`. Use
22/// [`HttpForwardProxyConnector`] on its own to require a forwarded request instead.
23///
24/// [`HttpForwardProxyConnector`]: crate::http::client::proxy::HttpForwardProxyConnector
25#[derive(Debug, Clone)]
26pub struct MaybeForwardedConnector<O, F> {
27    origin: O,
28    forward: F,
29}
30
31impl<O, F> MaybeForwardedConnector<O, F> {
32    /// Create a new [`MaybeForwardedConnector`] over the connector towards origins and the
33    /// one forwarding over HTTP proxies.
34    pub const fn new(origin: O, forward: F) -> Self {
35        Self { origin, forward }
36    }
37}
38
39impl<O, F, Input, Origin, Forward> Service<Input> for MaybeForwardedConnector<O, F>
40where
41    O: ConnectorService<Input, Connection = Origin>,
42    F: ConnectorService<Input, Connection = Forward>,
43    Origin: Send + ExtensionsRef + 'static,
44    Forward: Send + ExtensionsRef + 'static,
45    Input: ProtocolInputExt + ExtensionsRef + Send + 'static,
46{
47    type Output = EstablishedClientConnection<MaybeForwardedConnection<Origin, Forward>, Input>;
48    type Error = ConnectionError;
49
50    async fn serve(&self, input: Input) -> Result<Self::Output, Self::Error> {
51        if HttpForwardRoute::new().is_proxied(&input) {
52            tracing::trace!("maybe forwarded: a proxy forwards this request");
53            let EstablishedClientConnection { input, conn } = self.forward.connect(input).await?;
54            return Ok(EstablishedClientConnection {
55                input,
56                conn: MaybeForwardedConnection::Forward { conn },
57            });
58        }
59        let EstablishedClientConnection { input, conn } = self.origin.connect(input).await?;
60        Ok(EstablishedClientConnection {
61            input,
62            conn: MaybeForwardedConnection::Origin { conn },
63        })
64    }
65}
66
67/// The HTTP connection a [`MaybeForwardedConnector`] established, to the origin of a request
68/// or to the proxy forwarding it.
69#[derive(Debug, Clone)]
70pub enum MaybeForwardedConnection<O, F> {
71    /// Established towards the origin itself.
72    Origin { conn: O },
73    /// Established towards the proxy which forwards the request.
74    Forward { conn: F },
75}
76
77impl<O: ExtensionsRef, F: ExtensionsRef> ExtensionsRef for MaybeForwardedConnection<O, F> {
78    fn extensions(&self) -> &Extensions {
79        match self {
80            Self::Origin { conn } => conn.extensions(),
81            Self::Forward { conn } => conn.extensions(),
82        }
83    }
84}
85
86impl<O, F, Body> Service<Request<Body>> for MaybeForwardedConnection<O, F>
87where
88    O: Service<Request<Body>, Output = Response, Error: Into<BoxError>>,
89    F: Service<Request<Body>, Output = Response, Error: Into<BoxError>>,
90    Body: Send + 'static,
91{
92    type Output = Response;
93    type Error = BoxError;
94
95    async fn serve(&self, mut request: Request<Body>) -> Result<Self::Output, Self::Error> {
96        match self {
97            Self::Origin { conn } => {
98                // A Proxy-Authorization field belongs to an HTTP proxy hop. This connection
99                // has none: it reaches the origin, directly or through a tunnel that is
100                // already open. Inside EasyHttpWebClient its ConnectionEgress already keeps
101                // the field off this connection; this guards the connector on its own.
102                remove_proxy_auth_request_headers(request.headers_mut());
103                conn.serve(request).await.map_err(Into::into)
104            }
105            Self::Forward { conn } => conn.serve(request).await.map_err(Into::into),
106        }
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113    use crate::{
114        extensions::Extension,
115        http::{
116            Body, StatusCode, client::proxy::HttpForwardProxyConnector,
117            header::PROXY_AUTHORIZATION, layer::forward_proxy::HttpForwardProxyAuthRequired,
118            proxy::PlaintextHttpProxyMode,
119        },
120        net::{
121            Protocol,
122            address::HostWithPort,
123            client::{ConnectRequest, ConnectionErrorKind, EstablishedProxyRoute, ProxyRoute},
124        },
125        service::service_fn,
126    };
127    use std::convert::Infallible;
128
129    #[derive(Debug, Clone, Copy, PartialEq, Eq, Extension)]
130    struct Arm(&'static str);
131
132    #[derive(Debug, Clone, ExtensionsRef)]
133    struct Arrival {
134        extensions: Extensions,
135        status: StatusCode,
136    }
137
138    impl<B: Send + 'static> Service<Request<B>> for Arrival {
139        type Output = Response;
140        type Error = Infallible;
141
142        async fn serve(&self, request: Request<B>) -> Result<Self::Output, Self::Error> {
143            let mut response = Response::builder()
144                .status(self.status)
145                .header("proxy-authenticate", "Basic realm=upstream")
146                .body(Body::empty())
147                .unwrap();
148            if let Some(auth) = request.headers().get(PROXY_AUTHORIZATION) {
149                response.headers_mut().insert("x-auth", auth.clone());
150            }
151            Ok(response)
152        }
153    }
154
155    fn arm(name: &'static str) -> impl ConnectorService<ConnectRequest, Connection = Arrival> {
156        arm_answering(name, StatusCode::OK)
157    }
158
159    fn arm_answering(
160        name: &'static str,
161        status: StatusCode,
162    ) -> impl ConnectorService<ConnectRequest, Connection = Arrival> {
163        service_fn(move |input: ConnectRequest| async move {
164            let extensions = Extensions::new();
165            extensions.insert(Arm(name));
166            Ok::<_, ConnectionError>(EstablishedClientConnection {
167                input,
168                conn: Arrival { extensions, status },
169            })
170        })
171    }
172
173    fn plaintext(route: Option<&str>, mode: Option<PlaintextHttpProxyMode>) -> ConnectRequest {
174        let input = ConnectRequest::new(HostWithPort::try_from("origin.example:80").unwrap())
175            .with_application_protocol(Protocol::HTTP);
176        if let Some(route) = route {
177            input
178                .extensions
179                .insert(ProxyRoute::Proxy(route.parse().unwrap()));
180        }
181        if let Some(mode) = mode {
182            input.extensions.insert(mode);
183        }
184        input
185    }
186
187    #[tokio::test]
188    async fn only_a_forwarded_request_reaches_the_forward_arm() {
189        let connector = MaybeForwardedConnector::new(arm("origin"), arm("forward"));
190        for (input, expected) in [
191            (plaintext(None, None), "origin"),
192            (
193                plaintext(Some("http://proxy.example:8080"), None),
194                "forward",
195            ),
196            (
197                plaintext(
198                    Some("http://proxy.example:8080"),
199                    Some(PlaintextHttpProxyMode::Tunnel),
200                ),
201                "origin",
202            ),
203            (
204                plaintext(Some("socks5://proxy.example:1080"), None),
205                "origin",
206            ),
207        ] {
208            let established = connector.connect(input).await.unwrap();
209            assert_eq!(
210                established.conn.extensions().get_ref::<Arm>(),
211                Some(&Arm(expected)),
212            );
213        }
214    }
215
216    #[tokio::test]
217    async fn proxy_credentials_never_travel_on_a_connection_to_the_origin() {
218        let connector = MaybeForwardedConnector::new(arm("origin"), arm("forward"));
219        let request = || {
220            Request::builder()
221                .uri("http://origin.example/path")
222                .header(PROXY_AUTHORIZATION, "Basic bWFudWFs")
223                .body(Body::empty())
224                .unwrap()
225        };
226
227        let origin = connector.connect(plaintext(None, None)).await.unwrap();
228        let response = origin.conn.serve(request()).await.unwrap();
229        assert!(response.headers().get("x-auth").is_none());
230
231        let forward = connector
232            .connect(plaintext(Some("http://proxy.example:8080"), None))
233            .await
234            .unwrap();
235        let response = forward.conn.serve(request()).await.unwrap();
236        assert_eq!(response.headers()["x-auth"], "Basic bWFudWFs");
237    }
238
239    #[tokio::test]
240    async fn auth_challenge_is_isolated_only_for_an_established_forward_route() {
241        let challenge = || arm_answering("challenge", StatusCode::PROXY_AUTHENTICATION_REQUIRED);
242        let proxy = "http://proxy.example:8080";
243        let request = |stale: EstablishedProxyRoute| {
244            let request = Request::builder()
245                .uri("http://origin.example/resource")
246                .body(Body::empty())
247                .unwrap();
248            request.extensions().insert(stale);
249            request
250        };
251
252        for isolate in [false, true] {
253            let connector = MaybeForwardedConnector::new(
254                challenge(),
255                HttpForwardProxyConnector::new(challenge()).with_isolate_auth_error(isolate),
256            );
257            for (input, is_forward) in [
258                (plaintext(None, None), false),
259                (plaintext(Some("socks5://proxy.example:1080"), None), false),
260                (
261                    plaintext(Some(proxy), Some(PlaintextHttpProxyMode::Tunnel)),
262                    false,
263                ),
264                (plaintext(Some(proxy), None), true),
265            ] {
266                // Whatever the request claims about its connection, the established route
267                // decides.
268                let stale = if is_forward {
269                    EstablishedProxyRoute::Direct
270                } else {
271                    EstablishedProxyRoute::Forward(proxy.parse().unwrap())
272                };
273                let established = connector.connect(input).await.unwrap();
274                let result = established.conn.serve(request(stale)).await;
275
276                if isolate && is_forward {
277                    let error = result.unwrap_err();
278                    assert!(
279                        error
280                            .downcast_ref::<HttpForwardProxyAuthRequired>()
281                            .is_some(),
282                        "{error:?}"
283                    );
284                } else {
285                    let response = result.unwrap();
286                    assert_eq!(response.status(), StatusCode::PROXY_AUTHENTICATION_REQUIRED);
287                    assert_eq!(
288                        response.headers()["proxy-authenticate"],
289                        "Basic realm=upstream",
290                    );
291                }
292            }
293        }
294    }
295
296    #[tokio::test]
297    async fn a_socks5_route_is_never_a_forwarded_one() {
298        let connector =
299            HttpForwardProxyConnector::new(arm("forward")).with_isolate_auth_error(true);
300        let error = connector
301            .connect(plaintext(Some("socks5://proxy.example:1080"), None))
302            .await
303            .unwrap_err();
304
305        assert_eq!(error.kind(), ConnectionErrorKind::InvalidInput);
306    }
307}