Skip to main content

ntex/web/
info.rs

1use std::{cell::Ref, fmt, net::IpAddr, net::SocketAddr, sync::Arc};
2
3use super::config::WebAppConfig;
4use crate::http::{RequestHead, header, header::HeaderName};
5
6const X_FORWARDED_FOR: HeaderName = HeaderName::from_static("x-forwarded-for");
7const X_FORWARDED_HOST: HeaderName = HeaderName::from_static("x-forwarded-host");
8const X_FORWARDED_PROTO: HeaderName = HeaderName::from_static("x-forwarded-proto");
9
10/// Trust policy for the `Forwarded` and `X-Forwarded-*` request headers.
11///
12/// Clients can send these headers themselves, so they are only meaningful if
13/// they are set by a proxy you control. The policy is configured with
14/// [`WebAppConfig::set_forwarded()`] and used by [`ConnectionInfo`].
15///
16/// The default policy is [`ForwardedPolicy::ignore()`].
17///
18/// ```rust
19/// use ntex::web::{self, App, ForwardedPolicy, HttpRequest, WebAppConfig};
20///
21/// async fn index(req: HttpRequest) -> String {
22///     format!("client: {:?}", req.connection_info().remote())
23/// }
24///
25/// let config = WebAppConfig::new()
26///     .set_forwarded(ForwardedPolicy::trust_proxies(["10.0.0.1".parse().unwrap()]));
27///
28/// App::default()
29///     .with_config(config)
30///     .route("/", web::get().to(index));
31/// ```
32#[derive(Clone, Default)]
33pub struct ForwardedPolicy(Policy);
34
35#[derive(Clone, Default)]
36enum Policy {
37    #[default]
38    Ignore,
39    TrustAll,
40    Trust(Arc<dyn Fn(IpAddr) -> bool + Send + Sync>),
41}
42
43impl ForwardedPolicy {
44    /// Ignore forwarding headers.
45    ///
46    /// Connection information comes from the connection and the request only:
47    /// the peer address, the request target, the `Host` header and the server
48    /// configuration. This is the default.
49    pub fn ignore() -> Self {
50        ForwardedPolicy(Policy::Ignore)
51    }
52
53    /// Trust forwarding headers from every peer.
54    ///
55    /// The first (client-most) value of each header is used, as ntex did before
56    /// 4.7.0. Use this only if every connection comes through a proxy that
57    /// removes or overwrites client-supplied forwarding headers.
58    pub fn trust_all() -> Self {
59        ForwardedPolicy(Policy::TrustAll)
60    }
61
62    /// Trust forwarding headers only from the listed proxy addresses.
63    ///
64    /// See [`ForwardedPolicy::trust_fn()`] for how the headers are evaluated.
65    pub fn trust_proxies<I>(proxies: I) -> Self
66    where
67        I: IntoIterator<Item = IpAddr>,
68    {
69        let proxies: Vec<IpAddr> = proxies.into_iter().map(|ip| ip.to_canonical()).collect();
70        Self::trust_fn(move |ip| proxies.contains(&ip))
71    }
72
73    /// Trust forwarding headers from proxies for which `f` returns `true`.
74    ///
75    /// The headers are used only if the peer of the connection is trusted. The
76    /// hops listed in `Forwarded`, or in `X-Forwarded-For` if there is no
77    /// `Forwarded` header, are then walked from the nearest one, skipping
78    /// trusted proxies. The first untrusted hop is the client, or the farthest
79    /// hop if all of them are trusted. With `Forwarded` the scheme and host
80    /// come from the client's element. With `X-Forwarded-Proto` and
81    /// `X-Forwarded-Host` the values are matched to `X-Forwarded-For`
82    /// entries counting from the end.
83    ///
84    /// Trusted proxies must add their own entries, and must not pass along a
85    /// client's `X-Forwarded-Proto` or `X-Forwarded-Host` without setting them.
86    ///
87    /// `f` receives addresses with IPv4-mapped IPv6 addresses converted to IPv4.
88    pub fn trust_fn<F>(f: F) -> Self
89    where
90        F: Fn(IpAddr) -> bool + Send + Sync + 'static,
91    {
92        ForwardedPolicy(Policy::Trust(Arc::new(f)))
93    }
94}
95
96impl fmt::Debug for ForwardedPolicy {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        let name = match self.0 {
99            Policy::Ignore => "Ignore",
100            Policy::TrustAll => "TrustAll",
101            Policy::Trust(_) => "Trust",
102        };
103        f.debug_tuple("ForwardedPolicy").field(&name).finish()
104    }
105}
106
107/// `HttpRequest` connection information
108///
109/// Values from the `Forwarded` and `X-Forwarded-*` headers are used only as
110/// allowed by the application's [`ForwardedPolicy`].
111#[derive(Debug, Clone, Default)]
112pub struct ConnectionInfo {
113    scheme: String,
114    host: String,
115    remote: Option<String>,
116}
117
118/// Returns `host` if it is a valid `host[:port]`.
119fn valid_host(host: &str) -> Option<&str> {
120    urly::Authority::new(host)
121        .is_ok_and(|a| a.userinfo().is_none() && !a.host().is_empty())
122        .then_some(host)
123}
124
125/// One element of a `Forwarded` header, added by a single proxy.
126#[derive(Debug, Default, PartialEq)]
127struct Element {
128    for_: Option<String>,
129    proto: Option<String>,
130    host: Option<String>,
131}
132
133/// Parse `Forwarded` header values into elements, see RFC 7239 section 4.
134///
135/// Quoted values are unquoted. Parameters without a value, and repeated
136/// parameters within an element, are ignored.
137fn parse_forwarded<'a>(values: impl Iterator<Item = &'a str>) -> Vec<Element> {
138    let mut elements = Vec::new();
139    for val in values {
140        let mut el = Element::default();
141        let mut rest = val;
142        loop {
143            let end = rest.find(['=', ';', ',']).unwrap_or(rest.len());
144            let name = rest[..end].trim();
145            rest = &rest[end..];
146            let value = if let Some(after) = rest.strip_prefix('=') {
147                let (value, after) = parse_value(after);
148                rest = after;
149                value
150            } else {
151                None
152            };
153            if let Some(value) = value {
154                let slot = if name.eq_ignore_ascii_case("for") {
155                    Some(&mut el.for_)
156                } else if name.eq_ignore_ascii_case("proto") {
157                    Some(&mut el.proto)
158                } else if name.eq_ignore_ascii_case("host") {
159                    Some(&mut el.host)
160                } else {
161                    None
162                };
163                if let Some(slot) = slot {
164                    slot.get_or_insert(value);
165                }
166            }
167            match rest.as_bytes().first() {
168                Some(b';') => rest = &rest[1..],
169                Some(b',') => {
170                    elements.push(std::mem::take(&mut el));
171                    rest = &rest[1..];
172                }
173                _ => break,
174            }
175        }
176        elements.push(el);
177    }
178    elements
179}
180
181/// Parse a token or a quoted string, returning it and the remaining input
182/// starting at the next `;` or `,`.
183fn parse_value(input: &str) -> (Option<String>, &str) {
184    let input = input.trim_start();
185    if let Some(quoted) = input.strip_prefix('"') {
186        let mut value = String::new();
187        let mut chars = quoted.char_indices();
188        while let Some((idx, ch)) = chars.next() {
189            match ch {
190                '"' => {
191                    let rest = &quoted[idx + 1..];
192                    let end = rest.find([';', ',']).unwrap_or(rest.len());
193                    // nothing but whitespace may follow the closing quote
194                    let value = rest[..end].trim().is_empty().then_some(value);
195                    return (value, &rest[end..]);
196                }
197                '\\' => match chars.next() {
198                    Some((_, ch)) => value.push(ch),
199                    None => break,
200                },
201                _ => value.push(ch),
202            }
203        }
204        // unterminated quoted string
205        (None, "")
206    } else {
207        let end = input.find([';', ',']).unwrap_or(input.len());
208        let value = input[..end].trim();
209        ((!value.is_empty()).then(|| value.to_owned()), &input[end..])
210    }
211}
212
213/// Parse a node address: `ip`, `ip:port`, `[ipv6]` or `[ipv6]:port`.
214fn parse_ip(node: &str) -> Option<IpAddr> {
215    let ip = if let Ok(addr) = node.parse::<SocketAddr>() {
216        addr.ip()
217    } else {
218        let node = node
219            .strip_prefix('[')
220            .and_then(|node| node.strip_suffix(']'))
221            .unwrap_or(node);
222        node.parse().ok()?
223    };
224    Some(ip.to_canonical())
225}
226
227/// Comma separated values of all `name` headers.
228fn header_list<'a>(req: &'a RequestHead, name: &HeaderName) -> Vec<&'a str> {
229    req.headers
230        .get_all(name)
231        .filter_map(|val| val.to_str().ok())
232        .flat_map(|val| val.split(','))
233        .map(str::trim)
234        .collect()
235}
236
237/// Index of the client in `hops`, walking from the nearest hop and skipping
238/// trusted proxies.
239fn client_hop<T>(
240    hops: &[T],
241    node: impl Fn(&T) -> Option<&str>,
242    trusted: &dyn Fn(IpAddr) -> bool,
243) -> usize {
244    (1..hops.len())
245        .rev()
246        .find(|&idx| !node(&hops[idx]).and_then(parse_ip).is_some_and(trusted))
247        .unwrap_or(0)
248}
249
250/// The value of a per-hop header list matching the hop that is `from_end`
251/// hops before the nearest one, or the farthest value if the list is shorter.
252fn aligned<'a>(values: &[&'a str], from_end: usize) -> Option<&'a str> {
253    let idx = values.len().checked_sub(1)?.saturating_sub(from_end);
254    Some(values[idx]).filter(|val| !val.is_empty())
255}
256
257#[derive(Default)]
258struct Forwarded {
259    scheme: Option<String>,
260    host: Option<String>,
261    remote: Option<String>,
262}
263
264impl Forwarded {
265    /// Forwarded values trusted for every peer, the first value of each.
266    fn trust_all(req: &RequestHead) -> Self {
267        let elements = parse_forwarded(
268            req.headers
269                .get_all(&header::FORWARDED)
270                .filter_map(|val| val.to_str().ok()),
271        );
272        let first = |f: fn(&Element) -> Option<&String>| elements.iter().find_map(f).cloned();
273        let first_xf = |name| header_list(req, &name).first().map(|v| (*v).to_owned());
274
275        let host = first(|el| el.host.as_ref())
276            .filter(|h| valid_host(h).is_some())
277            .or_else(|| first_xf(X_FORWARDED_HOST).filter(|h| valid_host(h).is_some()));
278        Forwarded {
279            host,
280            scheme: first(|el| el.proto.as_ref()).or_else(|| first_xf(X_FORWARDED_PROTO)),
281            remote: first(|el| el.for_.as_ref()).or_else(|| first_xf(X_FORWARDED_FOR)),
282        }
283    }
284
285    /// Forwarded values set by trusted proxies.
286    fn trusted(req: &RequestHead, trusted: &dyn Fn(IpAddr) -> bool) -> Self {
287        let peer = req.peer_addr().map(|addr| addr.ip().to_canonical());
288        if !peer.is_some_and(trusted) {
289            return Forwarded::default();
290        }
291
292        if req.headers.contains_key(&header::FORWARDED) {
293            let elements = parse_forwarded(
294                req.headers
295                    .get_all(&header::FORWARDED)
296                    .filter_map(|val| val.to_str().ok()),
297            );
298            let el = &elements[client_hop(&elements, |el| el.for_.as_deref(), trusted)];
299            Forwarded {
300                scheme: el.proto.clone(),
301                host: el.host.clone().filter(|h| valid_host(h).is_some()),
302                remote: el.for_.clone(),
303            }
304        } else {
305            let hops = header_list(req, &X_FORWARDED_FOR);
306            let (remote, from_end) = if hops.is_empty() {
307                (None, 0)
308            } else {
309                let idx = client_hop(&hops, |hop| Some(*hop), trusted);
310                (
311                    Some(hops[idx]).filter(|hop| !hop.is_empty()),
312                    hops.len() - 1 - idx,
313                )
314            };
315            let aligned = |name| aligned(&header_list(req, &name), from_end).map(ToOwned::to_owned);
316            Forwarded {
317                scheme: aligned(X_FORWARDED_PROTO),
318                host: aligned(X_FORWARDED_HOST).filter(|h| valid_host(h).is_some()),
319                remote: remote.map(ToOwned::to_owned),
320            }
321        }
322    }
323}
324
325impl ConnectionInfo {
326    /// Create *`ConnectionInfo`* instance for a request.
327    pub fn get<'a>(req: &'a RequestHead, cfg: &'a WebAppConfig) -> Ref<'a, Self> {
328        if !req.extensions().contains::<ConnectionInfo>() {
329            req.extensions_mut().insert(ConnectionInfo::new(req, cfg));
330        }
331        Ref::map(req.extensions(), |e| e.get().unwrap())
332    }
333
334    fn new(req: &RequestHead, cfg: &WebAppConfig) -> ConnectionInfo {
335        let fwd = match &cfg.forwarded().0 {
336            Policy::Ignore => Forwarded::default(),
337            Policy::TrustAll => Forwarded::trust_all(req),
338            Policy::Trust(f) => Forwarded::trusted(req, f.as_ref()),
339        };
340
341        let scheme = fwd
342            .scheme
343            .or_else(|| req.scheme().map(ToOwned::to_owned))
344            .unwrap_or_else(|| if cfg.secure() { "https" } else { "http" }.to_owned());
345
346        let host = fwd.host.unwrap_or_else(|| {
347            // the authority of an absolute-form target or the HTTP/2 `:authority`
348            // takes precedence over `Host`, see RFC 9112 section 3.2.2 and
349            // RFC 9113 section 8.3.1
350            req.authority()
351                .map(|a| a.rsplit_once('@').map_or(a, |(_, host_port)| host_port))
352                .filter(|h| !h.is_empty())
353                .or_else(|| valid_host(req.headers.get(&header::HOST)?.to_str().ok()?))
354                .unwrap_or(cfg.host())
355                .to_owned()
356        });
357
358        let remote = fwd
359            .remote
360            .or_else(|| req.peer_addr().map(|addr| addr.to_string()));
361
362        ConnectionInfo {
363            scheme,
364            host,
365            remote,
366        }
367    }
368
369    /// Scheme of the request.
370    ///
371    /// Scheme is resolved from the following sources, in this order:
372    ///
373    /// - `Forwarded` or `X-Forwarded-Proto`, if allowed by the [`ForwardedPolicy`]
374    /// - Uri or the HTTP/2 `:scheme`, see [`RequestHead::scheme`]
375    /// - `https` if the server is configured as secure, `http` otherwise
376    #[inline]
377    pub fn scheme(&self) -> &str {
378        &self.scheme
379    }
380
381    /// Hostname of the request.
382    ///
383    /// Hostname is resolved from the following sources, in this order:
384    ///
385    /// - `Forwarded` or `X-Forwarded-Host`, if allowed by the [`ForwardedPolicy`]
386    /// - Uri or the HTTP/2 `:authority`, see [`RequestHead::authority`]
387    /// - Host
388    /// - Server hostname
389    ///
390    /// Header values that are not a valid `host[:port]` are skipped.
391    pub fn host(&self) -> &str {
392        &self.host
393    }
394
395    /// Address of the client that initiated the HTTP request.
396    ///
397    /// The address is resolved from the following sources, in this order:
398    ///
399    /// - `Forwarded` or `X-Forwarded-For`, if allowed by the [`ForwardedPolicy`]
400    /// - peer address of the connection
401    ///
402    /// Forwarded values are returned as sent by the proxy, for example
403    /// `192.0.2.1`, `[2001:db8::1]:4711` or `unknown`. With the default policy
404    /// this is always the peer address. Use
405    /// [`HttpRequest::peer_addr()`](crate::web::HttpRequest::peer_addr) for
406    /// the address of the connection itself.
407    #[inline]
408    pub fn remote(&self) -> Option<&str> {
409        self.remote.as_deref()
410    }
411}
412
413#[cfg(test)]
414mod tests {
415    use super::*;
416    use crate::web::{HttpRequest, test::TestRequest};
417
418    fn conn_info(req: &HttpRequest, policy: ForwardedPolicy) -> ConnectionInfo {
419        ConnectionInfo::new(req.head(), &WebAppConfig::new().set_forwarded(policy))
420    }
421
422    fn proxies() -> ForwardedPolicy {
423        ForwardedPolicy::trust_proxies(["10.0.0.1".parse().unwrap(), "10.0.0.2".parse().unwrap()])
424    }
425
426    /// STATEMENT: By default forwarding headers are ignored and connection information
427    /// comes from the connection and the request.
428    ///
429    /// HOW:
430    /// - Send `Forwarded` and every `X-Forwarded-*` header with a `Host` header and a peer
431    ///   address through the default configuration.
432    /// - Assert the scheme is `http`, the host is the `Host` value and the remote address
433    ///   is the peer address.
434    #[crate::rt_test]
435    async fn test_default_ignores_forwarded() {
436        let req = TestRequest::default()
437            .peer_addr("192.0.2.1:8080".parse().unwrap())
438            .header(header::HOST, "example.com")
439            .header(header::FORWARDED, "for=1.2.3.4;proto=https;host=evil.com")
440            .header(X_FORWARDED_FOR, "1.2.3.4")
441            .header(X_FORWARDED_HOST, "evil.com")
442            .header(X_FORWARDED_PROTO, "https")
443            .to_http_request();
444        let info = req.connection_info();
445        assert_eq!(info.scheme(), "http");
446        assert_eq!(info.host(), "example.com");
447        assert_eq!(info.remote(), Some("192.0.2.1:8080"));
448        assert_eq!(
449            format!("{:?}", ForwardedPolicy::default()),
450            "ForwardedPolicy(\"Ignore\")"
451        );
452    }
453
454    /// STATEMENT: `ForwardedPolicy::trust_all()` uses defaults and supported forwarding headers.
455    ///
456    /// HOW:
457    /// - Build requests with no headers, `Forwarded`, `Host`, and each `X-Forwarded-*` header.
458    /// - Assert the expected scheme, host, and optional remote address for each source.
459    #[test]
460    fn test_forwarded() {
461        let trust = ForwardedPolicy::trust_all;
462        let req = TestRequest::default().to_http_request();
463        let info = conn_info(&req, trust());
464        assert_eq!(info.scheme(), "http");
465        assert_eq!(info.host(), "localhost:8080");
466
467        let req = TestRequest::default()
468            .header(
469                header::FORWARDED,
470                "for=192.0.2.60; proto=https; by=203.0.113.43; host=rust-lang.org",
471            )
472            .to_http_request();
473        let info = conn_info(&req, trust());
474        assert_eq!(info.scheme(), "https");
475        assert_eq!(info.host(), "rust-lang.org");
476        assert_eq!(info.remote(), Some("192.0.2.60"));
477
478        let req = TestRequest::default()
479            .header(header::HOST, "rust-lang.org")
480            .to_http_request();
481        let info = conn_info(&req, trust());
482        assert_eq!(info.scheme(), "http");
483        assert_eq!(info.host(), "rust-lang.org");
484        assert_eq!(info.remote(), None);
485
486        let req = TestRequest::default()
487            .header(X_FORWARDED_FOR, "192.0.2.60")
488            .to_http_request();
489        assert_eq!(conn_info(&req, trust()).remote(), Some("192.0.2.60"));
490
491        let req = TestRequest::default()
492            .header(X_FORWARDED_HOST, "192.0.2.60")
493            .to_http_request();
494        let info = conn_info(&req, trust());
495        assert_eq!(info.host(), "192.0.2.60");
496        assert_eq!(info.remote(), None);
497
498        let req = TestRequest::default()
499            .header(X_FORWARDED_PROTO, "https")
500            .to_http_request();
501        assert_eq!(conn_info(&req, trust()).scheme(), "https");
502    }
503
504    /// STATEMENT: With `trust_all()` the first recognized forwarded values are used.
505    ///
506    /// HOW:
507    /// - Supply multiple `for`, `host`, and `proto` values plus ignored items.
508    /// - Assert the first remote address, host, and scheme are selected.
509    #[test]
510    fn test_forwarded_ignored_items() {
511        let req = TestRequest::default()
512            .header(
513                header::FORWARDED,
514                "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",
515            )
516            .to_http_request();
517        let info = conn_info(&req, ForwardedPolicy::trust_all());
518        assert_eq!(info.remote(), Some("192.0.2.60"));
519        assert_eq!(info.host(), "a.org");
520        assert_eq!(info.scheme(), "https");
521    }
522
523    /// STATEMENT: `Forwarded` values are split into elements and unquoted as in RFC 7239.
524    ///
525    /// HOW:
526    /// - Parse quoted values containing `;`, `,`, escapes and bracketed IPv6 addresses,
527    ///   mixed-case names, repeated parameters and multiple header values.
528    /// - Assert the parsed elements, and that unterminated quotes, data after a closing
529    ///   quote and empty values are dropped.
530    #[test]
531    fn test_parse_forwarded() {
532        let el = |for_: Option<&str>, proto: Option<&str>, host: Option<&str>| Element {
533            for_: for_.map(Into::into),
534            proto: proto.map(Into::into),
535            host: host.map(Into::into),
536        };
537        assert_eq!(
538            parse_forwarded(
539                [
540                    r#"For="[2001:db8::1]:4711";PROTO="https";host="a;b,c", for=1.2.3.4"#,
541                    r#" for = "x\"y" ; for=dup ;proto=http"#,
542                ]
543                .into_iter()
544            ),
545            [
546                el(Some("[2001:db8::1]:4711"), Some("https"), Some("a;b,c")),
547                el(Some("1.2.3.4"), None, None),
548                el(Some("x\"y"), Some("http"), None),
549            ]
550        );
551        assert_eq!(
552            parse_forwarded([r#"for="1.2.3.4" x;proto="https"#].into_iter()),
553            [el(None, None, None)]
554        );
555        assert_eq!(
556            parse_forwarded(["for=;proto=\"\\"].into_iter()),
557            [el(None, None, None)]
558        );
559        assert_eq!(parse_ip("[2001:db8::1]:4711"), "2001:db8::1".parse().ok());
560        assert_eq!(parse_ip("[2001:db8::1]"), "2001:db8::1".parse().ok());
561        assert_eq!(parse_ip("192.0.2.1:80"), "192.0.2.1".parse().ok());
562        assert_eq!(parse_ip("::ffff:192.0.2.1"), "192.0.2.1".parse().ok());
563        assert_eq!(parse_ip("unknown"), None);
564    }
565
566    /// STATEMENT: Quoted `Forwarded` values are returned without quotes.
567    ///
568    /// HOW:
569    /// - Send quoted `for`, `proto` and `host` values with `trust_all()`.
570    /// - Assert `remote()`, `scheme()` and `host()` return the unquoted values.
571    #[test]
572    fn test_forwarded_quoted() {
573        let req = TestRequest::default()
574            .header(
575                header::FORWARDED,
576                r#"for="[2001:db8::1]:4711";proto="https";host="example.com:8443""#,
577            )
578            .to_http_request();
579        let info = conn_info(&req, ForwardedPolicy::trust_all());
580        assert_eq!(info.remote(), Some("[2001:db8::1]:4711"));
581        assert_eq!(info.scheme(), "https");
582        assert_eq!(info.host(), "example.com:8443");
583    }
584
585    /// STATEMENT: Trusted proxies' `X-Forwarded-*` headers are used only from a trusted
586    /// peer, and the client is the nearest untrusted hop.
587    ///
588    /// HOW:
589    /// - Send several spoofed leading entries through trusted peers, including an IPv4-mapped peer,
590    ///   and assert the nearest untrusted `X-Forwarded-For` hop with the matching
591    ///   `X-Forwarded-Proto` value and a shorter `X-Forwarded-Host` list clamped to its
592    ///   first value.
593    /// - Assert the farthest hop is used when every hop is trusted, the last values are used
594    ///   without `X-Forwarded-For`, and untrusted or missing peers ignore the headers.
595    #[crate::rt_test]
596    async fn test_trust_proxies_x_forwarded() {
597        let req = |peer: &str| {
598            TestRequest::default()
599                .peer_addr(peer.parse().unwrap())
600                .header(header::HOST, "internal")
601                .header(X_FORWARDED_FOR, "6.6.6.6, 7.7.7.7, 203.0.113.9")
602                .header(X_FORWARDED_FOR, "10.0.0.2")
603                .header(X_FORWARDED_PROTO, "spoof, https, http")
604                .header(X_FORWARDED_HOST, "example.com")
605                .to_http_request()
606        };
607        for peer in ["10.0.0.1:1000", "[::ffff:10.0.0.1]:1000"] {
608            let info = conn_info(&req(peer), proxies());
609            assert_eq!(info.remote(), Some("203.0.113.9"), "{peer}");
610            assert_eq!(info.scheme(), "https");
611            assert_eq!(info.host(), "example.com");
612        }
613
614        let info = conn_info(&req("192.0.2.1:1000"), proxies());
615        assert_eq!(info.remote(), Some("192.0.2.1:1000"));
616        assert_eq!(info.scheme(), "http");
617        assert_eq!(info.host(), "internal");
618
619        let req = TestRequest::default()
620            .header(X_FORWARDED_FOR, "203.0.113.9")
621            .to_http_request();
622        assert_eq!(conn_info(&req, proxies()).remote(), None);
623
624        let req = TestRequest::default()
625            .peer_addr("10.0.0.1:1000".parse().unwrap())
626            .header(X_FORWARDED_FOR, "10.0.0.2, 10.0.0.1")
627            .to_http_request();
628        assert_eq!(conn_info(&req, proxies()).remote(), Some("10.0.0.2"));
629
630        let req = TestRequest::default()
631            .peer_addr("10.0.0.1:1000".parse().unwrap())
632            .header(X_FORWARDED_PROTO, "http, https")
633            .header(X_FORWARDED_HOST, "a.org, b.org")
634            .to_http_request();
635        let info = conn_info(&req, proxies());
636        assert_eq!(info.remote(), Some("10.0.0.1:1000"));
637        assert_eq!(info.scheme(), "https");
638        assert_eq!(info.host(), "b.org");
639    }
640
641    /// STATEMENT: Empty or invalid values from trusted proxies fall back to the request,
642    /// and listed IPv4-mapped proxy addresses match IPv4 peers.
643    ///
644    /// HOW:
645    /// - Trust only `::ffff:10.0.0.1` and send an empty `X-Forwarded-Proto` entry and an
646    ///   invalid `X-Forwarded-Host` from peer `10.0.0.1`.
647    /// - Assert the forwarded client is used while the scheme and host come from the
648    ///   request, then repeat with an invalid `Forwarded` host.
649    #[crate::rt_test]
650    async fn test_trust_proxies_invalid_values() {
651        let mapped = || ForwardedPolicy::trust_proxies(["::ffff:10.0.0.1".parse().unwrap()]);
652        let req = TestRequest::default()
653            .peer_addr("10.0.0.1:1000".parse().unwrap())
654            .header(header::HOST, "internal")
655            .header(X_FORWARDED_FOR, "203.0.113.9")
656            .header(X_FORWARDED_PROTO, "https, ")
657            .header(X_FORWARDED_HOST, "evil/x")
658            .to_http_request();
659        let info = conn_info(&req, mapped());
660        assert_eq!(info.remote(), Some("203.0.113.9"));
661        assert_eq!(info.scheme(), "http");
662        assert_eq!(info.host(), "internal");
663
664        let req = TestRequest::default()
665            .peer_addr("10.0.0.1:1000".parse().unwrap())
666            .header(header::HOST, "internal")
667            .header(header::FORWARDED, "for=203.0.113.9;host=evil/x")
668            .to_http_request();
669        let info = conn_info(&req, mapped());
670        assert_eq!(info.remote(), Some("203.0.113.9"));
671        assert_eq!(info.host(), "internal");
672    }
673
674    /// STATEMENT: With trusted proxies, `Forwarded` takes precedence over `X-Forwarded-*`
675    /// and the client's element supplies the scheme and host.
676    ///
677    /// HOW:
678    /// - Send a spoofed first element, a client element with a quoted IPv6 node and a
679    ///   trusted proxy element, plus a conflicting `X-Forwarded-For`.
680    /// - Assert the remote address, scheme and host of the client element, that an
681    ///   unparsable node stops the walk, and that `trust_fn()` predicates are applied.
682    #[crate::rt_test]
683    async fn test_trust_proxies_forwarded() {
684        let req = TestRequest::default()
685            .peer_addr("10.0.0.1:1000".parse().unwrap())
686            .header(
687                header::FORWARDED,
688                r#"for=6.6.6.6;proto=http;host=evil.com, for="[2001:db8::1]:4711";proto=https;host=example.com"#,
689            )
690            .header(header::FORWARDED, "for=10.0.0.2;proto=http;host=internal")
691            .header(X_FORWARDED_FOR, "7.7.7.7")
692            .to_http_request();
693        let info = conn_info(&req, proxies());
694        assert_eq!(info.remote(), Some("[2001:db8::1]:4711"));
695        assert_eq!(info.scheme(), "https");
696        assert_eq!(info.host(), "example.com");
697
698        let req = TestRequest::default()
699            .peer_addr("10.0.0.1:1000".parse().unwrap())
700            .header(header::FORWARDED, "for=6.6.6.6, for=_hidden, for=10.0.0.2")
701            .to_http_request();
702        assert_eq!(conn_info(&req, proxies()).remote(), Some("_hidden"));
703
704        let req = TestRequest::default()
705            .peer_addr("127.0.0.1:1000".parse().unwrap())
706            .header(header::FORWARDED, "for=6.6.6.6, for=127.0.0.2")
707            .to_http_request();
708        let loopback = || ForwardedPolicy::trust_fn(|ip| ip.is_loopback());
709        assert_eq!(conn_info(&req, loopback()).remote(), Some("6.6.6.6"));
710        assert_eq!(conn_info(&req, proxies()).remote(), Some("127.0.0.1:1000"));
711    }
712
713    /// STATEMENT: Host selection respects absolute targets and skips invalid authority values.
714    ///
715    /// HOW:
716    /// - Combine an absolute target containing userinfo with a conflicting `Host` header.
717    /// - Assert the target authority wins without userinfo, then check invalid forwarded hosts
718    ///   fall back to `Host` or the configured default with `trust_all()`.
719    #[test]
720    fn test_host_sources() {
721        // absolute-form target takes precedence over `Host`, userinfo is dropped
722        let req = TestRequest::with_uri("http://u:[email protected]:8080/p")
723            .header(header::HOST, "b.org")
724            .to_http_request();
725        assert_eq!(req.connection_info().host(), "a.org:8080");
726
727        // invalid values are skipped
728        let req = TestRequest::default()
729            .header(header::FORWARDED, "host=a/b")
730            .header(X_FORWARDED_HOST, "evil/x#, c.org")
731            .header(header::HOST, "b.org:81")
732            .to_http_request();
733        assert_eq!(
734            conn_info(&req, ForwardedPolicy::trust_all()).host(),
735            "b.org:81"
736        );
737
738        let req = TestRequest::default()
739            .header(X_FORWARDED_HOST, "[email protected]")
740            .header(header::HOST, "")
741            .to_http_request();
742        assert_eq!(
743            conn_info(&req, ForwardedPolicy::trust_all()).host(),
744            "localhost:8080"
745        );
746    }
747
748    /// STATEMENT: The HTTP/2 `:scheme` and `:authority` take precedence over `Host` and
749    /// the configured defaults.
750    ///
751    /// HOW:
752    /// - Set the head scheme and an authority containing userinfo next to a conflicting
753    ///   `Host` header, and assert both are used with the userinfo dropped.
754    /// - Set an empty authority and assert the host falls back to `Host`.
755    #[test]
756    fn test_h2_pseudo_headers() {
757        let mut req = TestRequest::default()
758            .header(header::HOST, "b.org")
759            .to_http_request();
760        req.head_mut().scheme = Some("https".into());
761        req.head_mut().authority = Some("u:[email protected]:8443".into());
762        let info = ConnectionInfo::new(req.head(), &WebAppConfig::new());
763        assert_eq!(info.scheme(), "https");
764        assert_eq!(info.host(), "a.org:8443");
765
766        req.head_mut().authority = Some("".into());
767        assert_eq!(req.connection_info().host(), "b.org");
768    }
769
770    /// STATEMENT: Secure application configuration determines the default connection scheme.
771    ///
772    /// HOW:
773    /// - Create `ConnectionInfo` for the same request with secure and ordinary configurations.
774    /// - Assert their schemes are `https` and `http`, respectively.
775    #[test]
776    fn test_secure_config() {
777        let req = TestRequest::default().to_http_request();
778        let info = ConnectionInfo::new(req.head(), &WebAppConfig::new().set_secure());
779        assert_eq!(info.scheme(), "https");
780
781        let info = ConnectionInfo::new(req.head(), &WebAppConfig::new());
782        assert_eq!(info.scheme(), "http");
783    }
784
785    /// STATEMENT: A forwarded remote address replaces the peer address only if trusted.
786    ///
787    /// HOW:
788    /// - Build requests with a peer address, with and without `X-Forwarded-For`.
789    /// - Assert the remote value is the peer socket by default and the forwarded address
790    ///   with `trust_all()`.
791    #[crate::rt_test]
792    async fn test_peer_addr() {
793        let req = TestRequest::default()
794            .peer_addr("192.0.2.1:8080".parse().unwrap())
795            .to_http_request();
796        let info = req.connection_info();
797        assert_eq!(info.remote(), Some("192.0.2.1:8080"));
798
799        let req = TestRequest::default()
800            .peer_addr("192.0.2.1:8080".parse().unwrap())
801            .header(X_FORWARDED_FOR, "192.0.2.60")
802            .to_http_request();
803        assert_eq!(req.connection_info().remote(), Some("192.0.2.1:8080"));
804        assert_eq!(
805            conn_info(&req, ForwardedPolicy::trust_all()).remote(),
806            Some("192.0.2.60")
807        );
808    }
809}