Skip to main content

modo/ip/
client_ip.rs

1use std::net::IpAddr;
2
3use axum::extract::FromRequestParts;
4use http::request::Parts;
5
6use crate::error::Error;
7
8/// Resolved client IP address.
9///
10/// Inserted into request extensions by [`ClientIpLayer`](super::ClientIpLayer).
11/// Use as an axum extractor in handlers:
12///
13/// ```
14/// use modo::ClientIp;
15///
16/// async fn handler(ClientIp(ip): ClientIp) -> String {
17///     ip.to_string()
18/// }
19/// ```
20#[derive(Debug, Clone, Copy)]
21pub struct ClientIp(pub IpAddr);
22
23impl<S: Send + Sync> FromRequestParts<S> for ClientIp {
24    type Rejection = Error;
25
26    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
27        parts.extensions.get::<ClientIp>().copied().ok_or_else(|| {
28            Error::internal("ClientIp not found in request extensions — is ClientIpLayer applied?")
29        })
30    }
31}
32
33#[cfg(test)]
34mod tests {
35    use super::*;
36    use http::request::Parts;
37
38    fn parts_with_client_ip(ip: IpAddr) -> Parts {
39        let mut req = http::Request::builder().body(()).unwrap();
40        req.extensions_mut().insert(ClientIp(ip));
41        req.into_parts().0
42    }
43
44    fn parts_without_client_ip() -> Parts {
45        let req = http::Request::builder().body(()).unwrap();
46        req.into_parts().0
47    }
48
49    #[tokio::test]
50    async fn extracts_client_ip_from_extensions() {
51        let ip: IpAddr = "1.2.3.4".parse().unwrap();
52        let mut parts = parts_with_client_ip(ip);
53        let result = ClientIp::from_request_parts(&mut parts, &()).await;
54        assert!(result.is_ok());
55        assert_eq!(result.unwrap().0, ip);
56    }
57
58    #[tokio::test]
59    async fn returns_error_when_missing() {
60        let mut parts = parts_without_client_ip();
61        let result = ClientIp::from_request_parts(&mut parts, &()).await;
62        assert!(result.is_err());
63    }
64}