product_os_router/
dual_protocol.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
use std::prelude::v1::*;

use std::fmt::{self, Debug, Formatter};
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

use product_os_http_body::Bytes;
use product_os_http::header::{HOST, LOCATION, UPGRADE};
use product_os_http::uri::{Authority, Scheme};
use product_os_http::{HeaderValue, Request, Response, StatusCode, Uri};
use product_os_http_body::{Either, Empty};
use pin_project::pin_project;
use tower_layer::Layer;
use tower_service::Service as TowerService;



#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Protocol {
    /// This connection is encrypted with TLS.
    Tls,
    /// This connection is unencrypted.
    Plain,
}


#[derive(Clone, Copy, Debug)]
pub struct UpgradeHttpLayer;

impl<Service> Layer<Service> for UpgradeHttpLayer {
    type Service = UpgradeHttp<Service>;

    fn layer(&self, inner: Service) -> Self::Service {
        UpgradeHttp::new(inner)
    }
}


/// [`Service`](TowerService) upgrading HTTP requests to HTTPS by using a
/// [301 "Moved Permanently"](https://tools.ietf.org/html/rfc7231#section-6.4.2)
/// status code.
///
/// Note that this [`Service`](TowerService) always redirects with the given
/// path and query. Depending on how you apply this [`Service`](TowerService) it
/// will redirect even in the case of a resulting 404 "Not Found" status code at
/// the destination.
#[derive(Clone, Debug)]
pub struct UpgradeHttp<Service> {
    /// Wrapped user-provided [`Service`](TowerService).
    service: Service,
}

impl<Service> UpgradeHttp<Service> {
    /// Creates a new [`UpgradeHttp`].
    pub const fn new(service: Service) -> Self {
        Self { service }
    }

    /// Consumes the [`UpgradeHttp`], returning the wrapped
    /// [`Service`](TowerService).
    pub fn into_inner(self) -> Service {
        self.service
    }

    /// Return a reference to the wrapped [`Service`](TowerService).
    pub const fn get_ref(&self) -> &Service {
        &self.service
    }

    /// Return a mutable reference to the wrapped [`Service`](TowerService).
    pub fn get_mut(&mut self) -> &mut Service {
        &mut self.service
    }
}

impl<Service, RequestBody, ResponseBody> TowerService<Request<RequestBody>> for UpgradeHttp<Service>
where
    Service: TowerService<Request<RequestBody>, Response = Response<ResponseBody>>,
{
    type Response = Response<Either<ResponseBody, Empty<Bytes>>>;
    type Error = Service::Error;
    type Future = UpgradeHttpFuture<Service, Request<RequestBody>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.service.poll_ready(cx)
    }

    fn call(&mut self, req: Request<RequestBody>) -> Self::Future {
        match req
            .extensions()
            .get::<Protocol>()
            .expect("`Protocol` should always be set by `DualProtocolService`")
        {
            Protocol::Tls => UpgradeHttpFuture::new_service(self.service.call(req)),
            Protocol::Plain => {
                let response = Response::builder();

                let response = if let Some((authority, scheme)) =
                    extract_authority(&req).and_then(|authority| {
                        let uri = req.uri();

                        // Depending on the scheme we need a different scheme to redirect to.

                        // WebSocket handshakes often don't send a scheme, so we check the "Upgrade"
                        // header as well.
                        if uri.scheme_str() == Some("ws")
                            || req.headers().get(UPGRADE)
                            == Some(&HeaderValue::from_static("websocket"))
                        {
                            Some((
                                authority,
                                Scheme::try_from("wss").expect("ASCII string is valid"),
                            ))
                        }
                        // HTTP requests often don't send a scheme.
                        else if uri.scheme() == Some(&Scheme::HTTP) || uri.scheme_str().is_none()
                        {
                            Some((authority, Scheme::HTTPS))
                        }
                        // Unknown scheme, abort.
                        else {
                            None
                        }
                    }) {
                    // Build URI to redirect to.
                    let mut uri = Uri::builder().scheme(scheme).authority(authority);

                    if let Some(path_and_query) = req.uri().path_and_query() {
                        uri = uri.path_and_query(path_and_query.clone());
                    }

                    let uri = uri.build().expect("invalid path and query");

                    response
                        .status(StatusCode::MOVED_PERMANENTLY)
                        .header(LOCATION, uri.to_string())
                } else {
                    // If we can't extract the host or have an unknown scheme, tell the client there
                    // is something wrong with their request.
                    response.status(StatusCode::BAD_REQUEST)
                }
                    .body(Empty::new())
                    .expect("invalid header or body");

                UpgradeHttpFuture::new_upgrade(response)
            }
        }
    }
}

/// [`Future`](TowerService::Future) type for [`UpgradeHttp`].
#[pin_project]
pub struct UpgradeHttpFuture<Service, Request>(#[pin] FutureServe<Service, Request>)
where
    Service: TowerService<Request>;

/// Holds [`Future`] to serve for [`UpgradeHttpFuture`].
#[derive(Debug)]
#[pin_project(project = UpgradeHttpFutureProj)]
enum FutureServe<Service, Request>
where
    Service: TowerService<Request>,
{
    /// The request was using the HTTPS protocol, so we
    /// will pass-through the wrapped [`Service`](TowerService).
    Service(#[pin] Service::Future),
    /// The request was using the HTTP protocol, so we
    /// will upgrade the connection.
    Upgrade(Option<Response<Empty<Bytes>>>),
}

// Rust can't figure out the correct bounds.
impl<Service, Request> Debug for UpgradeHttpFuture<Service, Request>
where
    Service: TowerService<Request>,
    FutureServe<Service, Request>: Debug,
{
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter
            .debug_tuple("UpgradeHttpFuture")
            .field(&self.0)
            .finish()
    }
}

impl<Service, Request> UpgradeHttpFuture<Service, Request>
where
    Service: TowerService<Request>,
{
    /// Create a [`UpgradeHttpFuture`] in the [`Service`](FutureServe::Service)
    /// state.
    const fn new_service(future: Service::Future) -> Self {
        Self(FutureServe::Service(future))
    }

    /// Create a [`UpgradeHttpFuture`] in the [`Upgrade`](FutureServe::Upgrade)
    /// state.
    const fn new_upgrade(response: Response<Empty<Bytes>>) -> Self {
        Self(FutureServe::Upgrade(Some(response)))
    }
}

impl<Service, Request, ResponseBody> Future for UpgradeHttpFuture<Service, Request>
where
    Service: TowerService<Request, Response = Response<ResponseBody>>,
{
    type Output = Result<Response<Either<ResponseBody, Empty<Bytes>>>, Service::Error>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        match self.project().0.project() {
            UpgradeHttpFutureProj::Service(future) => {
                future.poll(cx).map_ok(|result| result.map(Either::Left))
            }
            UpgradeHttpFutureProj::Upgrade(response) => Poll::Ready(Ok(response
                .take()
                .expect("polled again after `Poll::Ready`")
                .map(Either::Right))),
        }
    }
}

/// Extracts the host from a request, converting it to an [`Authority`].
fn extract_authority<Body>(request: &Request<Body>) -> Option<Authority> {
    /// `X-Forwarded-Host` header string.
    const X_FORWARDED_HOST: &str = "x-forwarded-host";

    let headers = request.headers();

    headers
        .get(X_FORWARDED_HOST)
        .or_else(|| headers.get(HOST))
        .and_then(|header| header.to_str().ok())
        .or_else(|| request.uri().host())
        .and_then(|host| Authority::try_from(host).ok())
}