This commit is contained in:
Robin Appelman 2024-11-29 18:58:08 +01:00
commit 6f3a1977bc
3 changed files with 35 additions and 5 deletions

25
README.md Normal file
View file

@ -0,0 +1,25 @@
# real-ip
Get the "real-ip" of an incoming request using the "forwarded", "x-forwarded-for" or "x-real-ip" headers set by reverse proxies.
See the [crate documentation](https://docs.rs/real-ip) for more details and examples.
## Example
```rust
use http::Request;
use std::net::IpAddr;
use ipnetwork::IpNetwork;
use real_ip::real_ip;
// in a real program this info would of course come from the http server
let incoming_ip = IpAddr::from([10, 0, 0, 1]);
let request = Request::builder().header("x-forwarded-for", "192.0.2.1").body(()).unwrap();
// the reverse-proxies in our network that we trust
let trusted_proxies = [
IpAddr::from([10, 0, 0, 1]).into(),
];
let client_ip = real_ip(&request, incoming_ip, &trusted_proxies);
assert_eq!(Some(IpAddr::from([192, 0, 2, 1])), client_ip);
```

View file

@ -10,5 +10,7 @@
inputs.flakelight.follows = "flakelight"; inputs.flakelight.follows = "flakelight";
}; };
}; };
outputs = { mill-scale, ... }: mill-scale ./. { }; outputs = { mill-scale, ... }: mill-scale ./. {
extraFiles = [ "README.md" ];
};
} }

View file

@ -1,10 +1,6 @@
//! Get the "real-ip" of an incoming request. //! Get the "real-ip" of an incoming request.
//! //!
//! This uses the "forwarded", "x-forwarded-for" or "x-real-ip" headers set by reverse proxies. //! This uses the "forwarded", "x-forwarded-for" or "x-real-ip" headers set by reverse proxies.
//! To stop clients from abusing these headers, only headers set by trusted remotes will be accepted.
//!
//! Note that if multiple forwarded-for addresses are present, which can be the case when using nested reverse proxies,
//! all proxies in the chain have to be within the list of trusted proxies.
//! //!
//! ## Trusted proxies //! ## Trusted proxies
//! //!
@ -13,6 +9,9 @@
//! //!
//! Trusted proxies are configured as a list of [`IpNetwork`]s, which can be a single ip or an ip range. //! Trusted proxies are configured as a list of [`IpNetwork`]s, which can be a single ip or an ip range.
//! //!
//! Note that if multiple forwarded-for addresses are present, which can be the case when using nested reverse proxies,
//! all proxies in the chain have to be within the list of trusted proxies.
//!
//! ## Examples //! ## Examples
//! //!
//! A request originating from 192.0.2.1, being proxied through 10.10.10.10 and 10.0.0.1 before reaching our program //! A request originating from 192.0.2.1, being proxied through 10.10.10.10 and 10.0.0.1 before reaching our program
@ -169,3 +168,7 @@ fn maybe_bracketed(x: &str) -> &str {
x x
} }
} }
#[allow(dead_code)]
#[doc = include_str!("../README.md")]
fn test_readme_examples() {}