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
//! HTTP to HTTPS redirect middleware, with exempt path prefixes.
//!
//! Every plain-HTTP request gets a `301` to the same URL on HTTPS.
//! Behind a proxy that terminates TLS, set the trusted header with
//! [`SslRedirectLayer::proxy_ssl_header`]. Without it the layer
//! never sees the request as secure and redirects in a loop.
//!
//! ## Quick start
//!
//! ```ignore
//! use rustango::ssl_redirect::{SslRedirectLayer, SslRedirectRouterExt};
//!
//! let app = Router::new()
//! .route("/", get(home))
//! .ssl_redirect(
//! SslRedirectLayer::new()
//! .proxy_ssl_header("X-Forwarded-Proto", "https")
//! .exempt(["/health", "/ready"]),
//! );
//! ```
//!
//! ## Exempt paths
//!
//! [`SslRedirectLayer::exempt`] takes path prefixes, matched on whole
//! segments: `/health` exempts `/health` and `/health/db`, not
//! `/healthz`. This suits health checks reached over plain HTTP. By
//! default nothing is exempt.
//!
//! [`SslRedirectLayer::exempt`]: crate::ssl_redirect::SslRedirectLayer::exempt
//! [`SslRedirectLayer::proxy_ssl_header`]: crate::ssl_redirect::SslRedirectLayer::proxy_ssl_header
use std::sync::Arc;
use axum::body::Body;
use axum::extract::Request;
use axum::http::{HeaderName, HeaderValue, Response, StatusCode};
use axum::middleware::Next;
use axum::Router;
/// Redirect settings. Apply them with
/// [`SslRedirectRouterExt::ssl_redirect`].
#[derive(Clone, Debug)]
pub struct SslRedirectLayer {
/// Header name and value that mean "this request arrived over
/// HTTPS". With `None` the layer reads the URI scheme, which
/// only works when rustango terminates TLS itself.
proxy_ssl_header: Option<(HeaderName, HeaderValue)>,
/// Path prefixes that skip the redirect. Include the leading `/`.
exempt: Vec<String>,
/// `/health` and `/ready` pass: probes come over plain HTTP.
probes_exempt: bool,
}
impl Default for SslRedirectLayer {
fn default() -> Self {
Self::new()
}
}
impl SslRedirectLayer {
/// No proxy header, nothing exempt. Behind a TLS-terminating
/// proxy, add [`Self::proxy_ssl_header`] or you get a redirect
/// loop.
#[must_use]
pub fn new() -> Self {
Self {
proxy_ssl_header: None,
exempt: Vec::new(),
probes_exempt: false,
}
}
/// Let the built-in health endpoints through, as the server does
/// when it mounts them.
#[cfg_attr(not(all(feature = "manage", feature = "config")), allow(dead_code))]
#[must_use]
pub(crate) fn exempt_probes(mut self) -> Self {
self.probes_exempt = true;
self
}
/// Declare the header your proxy sets when the original request
/// used HTTPS. A matching value skips the redirect.
///
/// The layer trusts this header, so the proxy must strip any
/// copy the client sends.
///
/// ```ignore
/// SslRedirectLayer::new().proxy_ssl_header("X-Forwarded-Proto", "https")
/// ```
///
/// An invalid header name or value is ignored, as if you never
/// called this method.
#[must_use]
pub fn proxy_ssl_header(mut self, header: impl AsRef<str>, value: impl AsRef<str>) -> Self {
if let (Ok(h), Ok(v)) = (
HeaderName::try_from(header.as_ref()),
HeaderValue::try_from(value.as_ref()),
) {
self.proxy_ssl_header = Some((h, v));
}
self
}
/// Add path prefixes that skip the redirect, such as health
/// checks reached over plain HTTP.
#[must_use]
pub fn exempt<I, S>(mut self, paths: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.exempt.extend(paths.into_iter().map(Into::into));
self
}
/// `true` when the request already arrived over HTTPS, so no
/// redirect is needed.
#[must_use]
pub fn is_secure(&self, req: &Request<Body>) -> bool {
// The scheme is set only when rustango terminates TLS.
if req.uri().scheme_str() == Some("https") {
return true;
}
if let Some((header, expected)) = &self.proxy_ssl_header {
if let Some(got) = req.headers().get(header) {
if got == expected {
return true;
}
}
}
false
}
/// `true` when the request path is an exempt prefix or under one,
/// segment by segment.
#[must_use]
pub fn is_exempt(&self, path: &str) -> bool {
self.exempt
.iter()
.any(|p| crate::urls::path_under_prefix(path, p))
}
}
/// Adds `.ssl_redirect(layer)` to a router.
pub trait SslRedirectRouterExt {
#[must_use]
fn ssl_redirect(self, layer: SslRedirectLayer) -> Self;
}
impl<S: Clone + Send + Sync + 'static> SslRedirectRouterExt for Router<S> {
fn ssl_redirect(self, layer: SslRedirectLayer) -> Self {
let cfg = Arc::new(layer);
self.layer(axum::middleware::from_fn(
move |req: Request<Body>, next: Next| {
let cfg = cfg.clone();
async move { handle(cfg, req, next).await }
},
))
}
}
async fn handle(cfg: Arc<SslRedirectLayer>, req: Request<Body>, next: Next) -> Response<Body> {
let probe = cfg.probes_exempt && crate::health::is_probe_path(req.uri().path());
if probe || cfg.is_secure(&req) || cfg.is_exempt(req.uri().path()) {
return next.run(req).await;
}
// Target URL: Host header, then path and query from the request.
// HTTP/2 sends `:authority`, not `Host`.
let Some(host) = crate::urls::request_authority(req.headers(), req.uri())
.and_then(crate::urls::HostAuthority::parse)
else {
let mut resp = Response::new(Body::from("invalid Host header"));
*resp.status_mut() = StatusCode::BAD_REQUEST;
return resp;
};
let path_and_query = req
.uri()
.path_and_query()
.map(|pq| pq.as_str())
.unwrap_or("/");
let location = format!("https://{host}{path_and_query}");
let mut resp = Response::new(Body::empty());
*resp.status_mut() = StatusCode::MOVED_PERMANENTLY;
if let Ok(v) = HeaderValue::from_str(&location) {
resp.headers_mut().insert(axum::http::header::LOCATION, v);
}
resp
}
#[cfg(test)]
mod tests {
use super::*;
fn http_req(path: &str, host: &str) -> Request<Body> {
Request::builder()
.uri(path)
.method("GET")
.header("Host", host)
.body(Body::empty())
.unwrap()
}
#[test]
fn default_layer_treats_plain_http_as_insecure() {
let layer = SslRedirectLayer::new();
let req = http_req("/", "example.com");
assert!(!layer.is_secure(&req));
}
#[test]
fn proxy_header_match_marks_request_secure() {
let layer = SslRedirectLayer::new().proxy_ssl_header("X-Forwarded-Proto", "https");
let req = Request::builder()
.uri("/")
.method("GET")
.header("Host", "example.com")
.header("X-Forwarded-Proto", "https")
.body(Body::empty())
.unwrap();
assert!(layer.is_secure(&req));
}
#[test]
fn proxy_header_mismatch_stays_insecure() {
let layer = SslRedirectLayer::new().proxy_ssl_header("X-Forwarded-Proto", "https");
let req = Request::builder()
.uri("/")
.method("GET")
.header("Host", "example.com")
.header("X-Forwarded-Proto", "http")
.body(Body::empty())
.unwrap();
assert!(!layer.is_secure(&req));
}
#[test]
fn exempt_prefix_skips_redirect() {
let layer = SslRedirectLayer::new().exempt(["/health", "/ready"]);
assert!(layer.is_exempt("/health"));
assert!(layer.is_exempt("/health/db"));
assert!(layer.is_exempt("/ready"));
assert!(!layer.is_exempt("/api/users"));
}
/// A prefix exempts whole segments only: `/health` is not `/healthz`.
#[test]
fn a_mid_segment_match_does_not_exempt() {
let layer = SslRedirectLayer::new().exempt(["/health", "/static/"]);
assert!(!layer.is_exempt("/healthz"));
assert!(!layer.is_exempt("/health-check"));
assert!(layer.is_exempt("/static/app.js"));
assert!(!layer.is_exempt("/staticfoo"));
}
#[test]
fn invalid_proxy_header_pair_silently_dropped() {
let layer =
SslRedirectLayer::new().proxy_ssl_header("Invalid Header Name\nwith CRLF", "https");
// Nothing configured, so a plain HTTP request stays insecure.
let req = http_req("/", "example.com");
assert!(!layer.is_secure(&req));
assert!(layer.proxy_ssl_header.is_none());
}
}