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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
use std::{borrow::ToOwned, cell::Ref};
use super::config::WebAppConfig;
use crate::http::{RequestHead, header, header::HeaderName};
const X_FORWARDED_FOR: HeaderName = HeaderName::from_static("x-forwarded-for");
const X_FORWARDED_HOST: HeaderName = HeaderName::from_static("x-forwarded-host");
const X_FORWARDED_PROTO: HeaderName = HeaderName::from_static("x-forwarded-proto");
/// `HttpRequest` connection information
#[derive(Debug, Clone, Default)]
pub struct ConnectionInfo {
scheme: String,
host: String,
remote: Option<String>,
peer: Option<String>,
}
/// Returns `host` if it is a valid `host[:port]`.
fn valid_host(host: &str) -> Option<&str> {
urly::Authority::new(host)
.is_ok_and(|a| a.userinfo().is_none() && !a.host().is_empty())
.then_some(host)
}
impl ConnectionInfo {
/// Create *`ConnectionInfo`* instance for a request.
pub fn get<'a>(req: &'a RequestHead, cfg: &'a WebAppConfig) -> Ref<'a, Self> {
if !req.extensions().contains::<ConnectionInfo>() {
req.extensions_mut().insert(ConnectionInfo::new(req, cfg));
}
Ref::map(req.extensions(), |e| e.get().unwrap())
}
fn new(req: &RequestHead, cfg: &WebAppConfig) -> ConnectionInfo {
let mut host = None;
let mut scheme = None;
let mut remote = None;
let mut peer = None;
// load forwarded header
for hdr in req.headers.get_all(&header::FORWARDED) {
if let Ok(val) = hdr.to_str() {
for pair in val.split(';') {
for el in pair.split(',') {
let mut items = el.trim().splitn(2, '=');
if let Some(name) = items.next()
&& let Some(val) = items.next()
{
match &name.to_lowercase() as &str {
"for" if remote.is_none() => {
remote = Some(val.trim());
}
"proto" if scheme.is_none() => {
scheme = Some(val.trim());
}
"host" if host.is_none() => {
host = Some(val.trim());
}
_ => (),
}
}
}
}
}
}
// scheme
if scheme.is_none() {
if let Some(h) = req.headers.get(&X_FORWARDED_PROTO)
&& let Ok(h) = h.to_str()
{
scheme = h.split(',').next().map(str::trim);
}
if scheme.is_none() {
scheme = req.uri.scheme_str();
if scheme.is_none() && cfg.secure() {
scheme = Some("https");
}
}
}
// host, invalid values are skipped
host = host
.and_then(valid_host)
.or_else(|| {
let h = req.headers.get(&X_FORWARDED_HOST)?.to_str().ok()?;
valid_host(h.split(',').next()?.trim())
})
// the authority of an absolute-form target takes precedence over
// `Host`, see RFC 9112 section 3.2.2
.or_else(|| Some(req.uri.authority()?.host_port()).filter(|h| !h.is_empty()))
.or_else(|| valid_host(req.headers.get(&header::HOST)?.to_str().ok()?))
.or_else(|| Some(cfg.host()));
// remote addr
if remote.is_none() {
if let Some(h) = req.headers.get(&X_FORWARDED_FOR)
&& let Ok(h) = h.to_str()
{
remote = h.split(',').next().map(str::trim);
}
if remote.is_none() {
// get peeraddr from socketaddr
peer = req.peer_addr().map(|addr| format!("{addr}"));
}
}
ConnectionInfo {
peer,
scheme: scheme.unwrap_or("http").to_owned(),
host: host.unwrap_or("localhost").to_owned(),
remote: remote.map(ToOwned::to_owned),
}
}
/// Scheme of the request.
///
/// Scheme is resolved through the following headers, in this order:
///
/// - Forwarded
/// - X-Forwarded-Proto
/// - Uri
#[inline]
pub fn scheme(&self) -> &str {
&self.scheme
}
/// Hostname of the request.
///
/// Hostname is resolved through the following headers, in this order:
///
/// - Forwarded
/// - X-Forwarded-Host
/// - Uri
/// - Host
/// - Server hostname
///
/// Header values that are not a valid `host[:port]` are skipped.
pub fn host(&self) -> &str {
&self.host
}
/// Remote socket addr of client initiated HTTP request.
///
/// The addr is resolved through the following headers, in this order:
///
/// - Forwarded
/// - X-Forwarded-For
/// - peer name of opened socket
///
/// # Security
/// Do not use this function for security purposes, unless you can ensure the Forwarded and
/// X-Forwarded-For headers cannot be spoofed by the client. If you want the client's socket
/// address explicitly, use
/// [`HttpRequest::peer_addr()`](crate::web::HttpRequest::peer_addr) instead.
#[inline]
pub fn remote(&self) -> Option<&str> {
if let Some(ref r) = self.remote {
Some(r)
} else if let Some(ref peer) = self.peer {
Some(peer)
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::web::test::TestRequest;
/// STATEMENT: Connection information uses defaults and supported forwarding headers.
///
/// HOW:
/// - Build requests with no headers, `Forwarded`, `Host`, and each `X-Forwarded-*` header.
/// - Assert the expected scheme, host, and optional remote address for each source.
#[test]
fn test_forwarded() {
let req = TestRequest::default().to_http_request();
let info = req.connection_info();
assert_eq!(info.scheme(), "http");
assert_eq!(info.host(), "localhost:8080");
let req = TestRequest::default()
.header(
header::FORWARDED,
"for=192.0.2.60; proto=https; by=203.0.113.43; host=rust-lang.org",
)
.to_http_request();
let info = req.connection_info();
assert_eq!(info.scheme(), "https");
assert_eq!(info.host(), "rust-lang.org");
assert_eq!(info.remote(), Some("192.0.2.60"));
let req = TestRequest::default()
.header(header::HOST, "rust-lang.org")
.to_http_request();
let info = req.connection_info();
assert_eq!(info.scheme(), "http");
assert_eq!(info.host(), "rust-lang.org");
assert_eq!(info.remote(), None);
let req = TestRequest::default()
.header(X_FORWARDED_FOR, "192.0.2.60")
.to_http_request();
let info = req.connection_info();
assert_eq!(info.remote(), Some("192.0.2.60"));
let req = TestRequest::default()
.header(X_FORWARDED_HOST, "192.0.2.60")
.to_http_request();
let info = req.connection_info();
assert_eq!(info.host(), "192.0.2.60");
assert_eq!(info.remote(), None);
let req = TestRequest::default()
.header(X_FORWARDED_PROTO, "https")
.to_http_request();
let info = req.connection_info();
assert_eq!(info.scheme(), "https");
}
/// STATEMENT: Forwarded connection information retains the first recognized values.
///
/// HOW:
/// - Supply multiple `for`, `host`, and `proto` values plus ignored items.
/// - Assert the first remote address, host, and scheme are selected.
#[test]
fn test_forwarded_ignored_items() {
let req = TestRequest::default()
.header(
header::FORWARDED,
"for=192.0.2.60, for=192.0.2.61; by=203.0.113.43; host=a.org; host=b.org; proto=https; proto=http; unknown",
)
.to_http_request();
let info = req.connection_info();
assert_eq!(info.remote(), Some("192.0.2.60"));
assert_eq!(info.host(), "a.org");
assert_eq!(info.scheme(), "https");
}
/// STATEMENT: Host selection respects absolute targets and skips invalid authority values.
///
/// HOW:
/// - Combine an absolute target containing userinfo with a conflicting `Host` header.
/// - Assert the target authority wins without userinfo, then check invalid forwarded hosts
/// fall back to `Host` or the configured default.
#[test]
fn test_host_sources() {
// absolute-form target takes precedence over `Host`, userinfo is dropped
let req = TestRequest::with_uri("http://u:p@a.org:8080/p")
.header(header::HOST, "b.org")
.to_http_request();
assert_eq!(req.connection_info().host(), "a.org:8080");
// invalid values are skipped
let req = TestRequest::default()
.header(header::FORWARDED, "host=a/b")
.header(X_FORWARDED_HOST, "evil/x#, c.org")
.header(header::HOST, "b.org:81")
.to_http_request();
assert_eq!(req.connection_info().host(), "b.org:81");
let req = TestRequest::default()
.header(X_FORWARDED_HOST, "u@c.org")
.header(header::HOST, "")
.to_http_request();
assert_eq!(req.connection_info().host(), "localhost:8080");
}
/// STATEMENT: Secure application configuration determines the default connection scheme.
///
/// HOW:
/// - Create `ConnectionInfo` for the same request with secure and ordinary configurations.
/// - Assert their schemes are `https` and `http`, respectively.
#[test]
fn test_secure_config() {
let req = TestRequest::default().to_http_request();
let info = ConnectionInfo::new(req.head(), &WebAppConfig::new().set_secure());
assert_eq!(info.scheme(), "https");
let info = ConnectionInfo::new(req.head(), &WebAppConfig::new());
assert_eq!(info.scheme(), "http");
}
/// STATEMENT: A forwarded remote address takes precedence over the transport peer address.
///
/// HOW:
/// - Build requests with a peer address, with and without `X-Forwarded-For`.
/// - Assert the remote value is the peer socket first and the forwarded address second.
#[crate::rt_test]
async fn test_peer_addr() {
let req = TestRequest::default()
.peer_addr("192.0.2.1:8080".parse().unwrap())
.to_http_request();
let info = req.connection_info();
assert_eq!(info.remote(), Some("192.0.2.1:8080"));
let req = TestRequest::default()
.peer_addr("192.0.2.1:8080".parse().unwrap())
.header(X_FORWARDED_FOR, "192.0.2.60")
.to_http_request();
let info = req.connection_info();
assert_eq!(info.remote(), Some("192.0.2.60"));
}
}