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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
//! Host-header allowlist middleware.
//!
//! The client sends the `Host:` header, so it is only a claim. Code
//! that builds absolute URLs, reset links or cache keys from it trusts
//! whoever called. This layer is the check: a request whose `Host` is
//! not on the list is rejected with a 400. It is an allowlist, not a
//! blocklist, so a host you never named is refused without you having
//! to predict it.
//!
//! Entries may be exact hosts (`example.com`), dot-prefix subdomain
//! wildcards (`.example.com` matches `api.example.com` and
//! `example.com` itself), or the catch-all `*`.
//!
//! ## Quick start
//!
//! ```ignore
//! use rustango::host_validation::{AllowedHostsLayer, AllowedHostsRouterExt};
//!
//! let app = Router::new()
//! .route("/", get(home))
//! .allowed_hosts(AllowedHostsLayer::new([
//! "example.com",
//! ".example.com", // any subdomain
//! "localhost",
//! ]));
//! ```
//!
//! The host is `Host`, or the HTTP/2 `:authority` when there is none.
//! A missing or unlisted host gets a `400 Bad Request`. The body
//! echoes the rejected host to help ops, but never the allowed list.
//!
//! ## Settings wiring
//!
//! `Settings.security.allowed_hosts: Vec<String>` feeds
//! [`AllowedHostsLayer::from_settings_list`]. An empty list turns the
//! check off, so the operator has to opt in. When the server mounts
//! `/health` and `/ready`, those two skip the check: probes send the
//! pod IP as host.
//!
//! [`AllowedHostsLayer::from_settings_list`]: crate::host_validation::AllowedHostsLayer::from_settings_list
use std::sync::Arc;
use axum::body::Body;
use axum::extract::Request;
use axum::http::{Response, StatusCode};
use axum::middleware::Next;
use axum::Router;
/// One allowed-host entry, pre-parsed so matching allocates nothing
/// per request.
#[derive(Clone, Debug)]
enum Pattern {
/// Catch-all `*`: every host matches, which switches the check
/// off. Dangerous in production — name your hosts instead.
Wildcard,
/// Exact match against the lowercased `Host` header.
Exact(String),
/// Dot-prefix wildcard `.example.com`: matches `example.com` and
/// any subdomain. Stored without the leading dot.
Subdomain(String),
}
impl Pattern {
fn parse(entry: &str) -> Option<Self> {
// Hosts are compared without the trailing FQDN dot; so are entries.
let entry = entry.trim();
let entry = entry.strip_suffix('.').unwrap_or(entry);
if entry.is_empty() {
return None;
}
if entry == "*" {
return Some(Self::Wildcard);
}
if let Some(rest) = entry.strip_prefix('.') {
if rest.is_empty() {
return None;
}
return Some(Self::Subdomain(rest.to_ascii_lowercase()));
}
Some(Self::Exact(entry.to_ascii_lowercase()))
}
fn matches(&self, host: &str) -> bool {
match self {
Self::Wildcard => true,
Self::Exact(h) => host == h,
Self::Subdomain(tail) => {
// Match the base domain itself, or a host ending in
// `.<tail>`. The dot matters: without it
// `eviltail.com` would match `.tail.com`.
host == tail
|| host
.strip_suffix(tail)
.is_some_and(|prefix| prefix.ends_with('.'))
}
}
}
}
/// The parsed pattern list. Apply it with
/// [`AllowedHostsRouterExt::allowed_hosts`].
#[derive(Clone)]
pub struct AllowedHostsLayer {
patterns: Arc<Vec<Pattern>>,
/// `/health` and `/ready` pass: probes send the pod IP as host.
probes_exempt: bool,
}
impl AllowedHostsLayer {
/// Build a layer from allowed-host entries: exact hostnames,
/// `.example.com` subdomain wildcards, or the catch-all `*`.
/// Blank entries are dropped.
#[must_use]
pub fn new<I, S>(entries: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let patterns: Vec<Pattern> = entries
.into_iter()
.filter_map(|s| Pattern::parse(s.as_ref()))
.collect();
Self {
patterns: Arc::new(patterns),
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
}
/// Wire from `Settings.security.allowed_hosts`. An empty list
/// disables the layer and every host passes.
#[must_use]
pub fn from_settings_list<I, S>(entries: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
Self::new(entries)
}
/// `true` when the list permits this host header. An empty list
/// passes every host: the operator opted out.
#[must_use]
pub fn permits(&self, host: &str) -> bool {
if self.patterns.is_empty() {
return true;
}
let Some(host) = crate::urls::normalize_host(host) else {
return false;
};
self.patterns.iter().any(|p| p.matches(&host))
}
}
/// Router extension: `.allowed_hosts(layer)`.
pub trait AllowedHostsRouterExt {
#[must_use]
fn allowed_hosts(self, layer: AllowedHostsLayer) -> Self;
}
impl<S: Clone + Send + Sync + 'static> AllowedHostsRouterExt for Router<S> {
fn allowed_hosts(self, layer: AllowedHostsLayer) -> 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<AllowedHostsLayer>, req: Request<Body>, next: Next) -> Response<Body> {
if cfg.probes_exempt && crate::health::is_probe_path(req.uri().path()) {
return next.run(req).await;
}
// HTTP/2 sends `:authority`, not `Host`.
let host = crate::urls::request_authority(req.headers(), req.uri()).unwrap_or("");
if cfg.permits(host) {
next.run(req).await
} else {
let msg = format!(
"DisallowedHost: rejected Host header {host:?} — \
add it to Settings.security.allowed_hosts to allow"
);
let mut resp = Response::new(Body::from(msg));
*resp.status_mut() = StatusCode::BAD_REQUEST;
resp
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_list_passes_every_host() {
let layer = AllowedHostsLayer::new(Vec::<String>::new());
assert!(layer.permits("anywhere.example.com"));
assert!(layer.permits(""));
}
#[test]
fn exact_match_is_case_insensitive() {
let layer = AllowedHostsLayer::new(["Example.COM"]);
assert!(layer.permits("example.com"));
assert!(layer.permits("EXAMPLE.com"));
assert!(!layer.permits("api.example.com"));
}
#[test]
fn dot_prefix_wildcard_matches_subdomains_plus_base() {
let layer = AllowedHostsLayer::new([".example.com"]);
assert!(layer.permits("example.com"));
assert!(layer.permits("api.example.com"));
assert!(layer.permits("a.b.example.com"));
// `evilexample.com` ends with "example.com" but is not a
// subdomain: the boundary character is not a dot.
assert!(!layer.permits("evilexample.com"));
}
#[test]
fn star_is_catchall() {
let layer = AllowedHostsLayer::new(["*"]);
assert!(layer.permits("anything"));
assert!(layer.permits("attacker.com"));
}
#[test]
fn port_is_stripped_before_comparison() {
let layer = AllowedHostsLayer::new(["example.com"]);
assert!(layer.permits("example.com:8080"));
assert!(layer.permits("example.com:443"));
}
#[test]
fn trailing_dot_host_matches_like_the_resolver() {
let layer = AllowedHostsLayer::new(["example.com", ".app.test", "fqdn.test."]);
assert!(layer.permits("example.com."));
assert!(layer.permits("Example.COM.:8080"));
assert!(layer.permits("acme.app.test."));
assert!(layer.permits("fqdn.test"));
assert!(!layer.permits("example.com.."));
}
#[test]
fn ipv6_with_port_is_handled() {
let layer = AllowedHostsLayer::new(["[::1]"]);
assert!(layer.permits("[::1]:8080"));
}
/// A non-digit port is refused, not cut to its first host (#2043).
#[test]
fn a_port_is_digits_only() {
let layer = AllowedHostsLayer::new(["good.com", "[::1]", "*"]);
assert!(layer.permits("good.com:80"));
assert!(layer.permits("[::1]:8080"));
for bad in [
"good.com:1@evil.com:2",
"good.com:@evil.com",
"[::1]:@evil.com",
] {
assert!(!layer.permits(bad), "{bad}");
}
}
#[test]
fn whitespace_entries_are_ignored() {
let layer = AllowedHostsLayer::new(["", " ", "example.com"]);
// Only the real entry counts; other hosts are still rejected.
assert!(layer.permits("example.com"));
assert!(!layer.permits("attacker.com"));
}
#[test]
fn rejected_host_does_not_match_other_patterns_in_list() {
let layer = AllowedHostsLayer::new(["a.com", ".b.com", "c.com"]);
assert!(layer.permits("a.com"));
assert!(layer.permits("foo.b.com"));
assert!(layer.permits("c.com"));
assert!(!layer.permits("d.com"));
assert!(!layer.permits("malicious.a.com"));
}
}