|
| 1 | +use axum::extract::ConnectInfo; |
| 2 | +use axum::http::Request; |
| 3 | +use std::net::IpAddr; |
| 4 | +use tower_governor::GovernorError; |
| 5 | +use tower_governor::key_extractor::KeyExtractor; |
| 6 | + |
| 7 | +pub fn extract_ip<T>(req: &Request<T>) -> Option<std::net::IpAddr> { |
| 8 | + let headers = req.headers(); |
| 9 | + |
| 10 | + // NOTE: This code is mimicking axum_client_ip's pre v1 `InsecureClientIp::from`: |
| 11 | + return client_ip::rightmost_x_forwarded_for(headers) |
| 12 | + .or_else(|_| client_ip::x_real_ip(headers)) |
| 13 | + .or_else(|_| client_ip::fly_client_ip(headers)) |
| 14 | + .or_else(|_| client_ip::true_client_ip(headers)) |
| 15 | + .or_else(|_| client_ip::cf_connecting_ip(headers)) |
| 16 | + .or_else(|_| client_ip::cloudfront_viewer_address(headers)) |
| 17 | + .ok() |
| 18 | + .or_else(|| { |
| 19 | + req |
| 20 | + .extensions() |
| 21 | + .get::<ConnectInfo<std::net::SocketAddr>>() |
| 22 | + .map(|ConnectInfo(addr)| addr.ip()) |
| 23 | + }); |
| 24 | +} |
| 25 | + |
| 26 | +#[derive(Debug, Clone)] |
| 27 | +pub struct RealIpKeyExtractor; |
| 28 | + |
| 29 | +impl KeyExtractor for RealIpKeyExtractor { |
| 30 | + type Key = IpAddr; |
| 31 | + |
| 32 | + fn extract<T>(&self, req: &Request<T>) -> Result<Self::Key, GovernorError> { |
| 33 | + return extract_ip(req).ok_or_else(|| GovernorError::UnableToExtractKey); |
| 34 | + } |
| 35 | + |
| 36 | + // fn name(&self) -> &'static str { |
| 37 | + // "smart IP" |
| 38 | + // } |
| 39 | + |
| 40 | + // fn key_name(&self, key: &Self::Key) -> Option<String> { |
| 41 | + // Some(key.to_string()) |
| 42 | + // } |
| 43 | +} |
| 44 | + |
| 45 | +#[allow(unused)] |
| 46 | +pub fn ipv6_privacy_mask(ip: IpAddr) -> IpAddr { |
| 47 | + return match ip { |
| 48 | + IpAddr::V4(ip) => IpAddr::V4(ip), |
| 49 | + IpAddr::V6(ip) => IpAddr::V6(From::from( |
| 50 | + ip.to_bits() & 0xFFFF_FFFF_FFFF_FFFF_0000_0000_0000_0000, |
| 51 | + )), |
| 52 | + }; |
| 53 | +} |
0 commit comments