Skip to main content

axum/extract/
connect_info.rs

1//! Extractor for getting connection information from a client.
2//!
3//! See [`Router::into_make_service_with_connect_info`] for more details.
4//!
5//! [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info
6
7use crate::extension::AddExtension;
8
9use super::{Extension, FromRequestParts};
10use http::request::Parts;
11use std::{
12    convert::Infallible,
13    fmt,
14    future::ready,
15    marker::PhantomData,
16    net::SocketAddr,
17    task::{Context, Poll},
18};
19use tower_layer::Layer;
20use tower_service::Service;
21
22/// A [`MakeService`] created from a router.
23///
24/// See [`Router::into_make_service_with_connect_info`] for more details.
25///
26/// [`MakeService`]: tower::make::MakeService
27/// [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info
28pub struct IntoMakeServiceWithConnectInfo<S, C> {
29    svc: S,
30    _connect_info: PhantomData<fn() -> C>,
31}
32
33impl<S, C> IntoMakeServiceWithConnectInfo<S, C> {
34    pub(crate) fn new(svc: S) -> Self {
35        Self {
36            svc,
37            _connect_info: PhantomData,
38        }
39    }
40}
41
42impl<S, C> fmt::Debug for IntoMakeServiceWithConnectInfo<S, C>
43where
44    S: fmt::Debug,
45{
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        f.debug_struct("IntoMakeServiceWithConnectInfo")
48            .field("svc", &self.svc)
49            .finish()
50    }
51}
52
53impl<S, C> Clone for IntoMakeServiceWithConnectInfo<S, C>
54where
55    S: Clone,
56{
57    fn clone(&self) -> Self {
58        Self {
59            svc: self.svc.clone(),
60            _connect_info: PhantomData,
61        }
62    }
63}
64
65/// Trait that connected IO resources implement and use to produce information
66/// about the connection.
67///
68/// The goal for this trait is to allow users to implement custom IO types that
69/// can still provide the same connection metadata.
70///
71/// See [`Router::into_make_service_with_connect_info`] for more details.
72///
73/// [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info
74pub trait Connected<T>: Clone + Send + Sync + 'static {
75    /// Create type holding information about the connection.
76    fn connect_info(stream: T) -> Self;
77}
78
79#[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))]
80const _: () = {
81    use crate::serve;
82
83    impl<L> Connected<serve::IncomingStream<'_, L>> for SocketAddr
84    where
85        L: serve::Listener<Addr = Self>,
86    {
87        fn connect_info(stream: serve::IncomingStream<'_, L>) -> Self {
88            *stream.remote_addr()
89        }
90    }
91};
92
93impl Connected<Self> for SocketAddr {
94    fn connect_info(remote_addr: Self) -> Self {
95        remote_addr
96    }
97}
98
99impl<S, C, T> Service<T> for IntoMakeServiceWithConnectInfo<S, C>
100where
101    S: Clone,
102    C: Connected<T>,
103{
104    type Response = AddExtension<S, ConnectInfo<C>>;
105    type Error = Infallible;
106    type Future = ResponseFuture<S, C>;
107
108    #[inline]
109    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
110        Poll::Ready(Ok(()))
111    }
112
113    fn call(&mut self, target: T) -> Self::Future {
114        let connect_info = ConnectInfo(C::connect_info(target));
115        let svc = Extension(connect_info).layer(self.svc.clone());
116        ResponseFuture::new(ready(Ok(svc)))
117    }
118}
119
120opaque_future! {
121    /// Response future for [`IntoMakeServiceWithConnectInfo`].
122    pub type ResponseFuture<S, C> =
123        std::future::Ready<Result<AddExtension<S, ConnectInfo<C>>, Infallible>>;
124}
125
126/// Extractor for getting connection information produced by a [`Connected`].
127///
128/// Note this extractor requires you to use
129/// [`Router::into_make_service_with_connect_info`] to run your app
130/// otherwise it will fail at runtime.
131///
132/// See [`Router::into_make_service_with_connect_info`] for more details.
133///
134/// [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info
135#[derive(Clone, Copy, Debug)]
136pub struct ConnectInfo<T>(pub T);
137
138impl<S, T> FromRequestParts<S> for ConnectInfo<T>
139where
140    S: Send + Sync,
141    T: Clone + Send + Sync + 'static,
142{
143    type Rejection = <Extension<Self> as FromRequestParts<S>>::Rejection;
144
145    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
146        match Extension::<Self>::from_request_parts(parts, state).await {
147            Ok(Extension(connect_info)) => Ok(connect_info),
148            Err(err) => match parts.extensions.get::<MockConnectInfo<T>>() {
149                Some(MockConnectInfo(connect_info)) => Ok(Self(connect_info.clone())),
150                None => Err(err),
151            },
152        }
153    }
154}
155
156axum_core::__impl_deref!(ConnectInfo);
157
158/// Middleware used to mock [`ConnectInfo`] during tests.
159///
160/// If you're accidentally using [`MockConnectInfo`] and
161/// [`Router::into_make_service_with_connect_info`] at the same time then
162/// [`Router::into_make_service_with_connect_info`] takes precedence.
163///
164/// # Example
165///
166/// ```
167/// use axum::{
168///     Router,
169///     extract::connect_info::{MockConnectInfo, ConnectInfo},
170///     body::Body,
171///     routing::get,
172///     http::{Request, StatusCode},
173/// };
174/// use std::net::SocketAddr;
175/// use tower::ServiceExt;
176///
177/// async fn handler(ConnectInfo(addr): ConnectInfo<SocketAddr>) {}
178///
179/// // this router you can run with `app.into_make_service_with_connect_info::<SocketAddr>()`
180/// fn app() -> Router {
181///     Router::new().route("/", get(handler))
182/// }
183///
184/// // use this router for tests
185/// fn test_app() -> Router {
186///     app().layer(MockConnectInfo(SocketAddr::from(([0, 0, 0, 0], 1337))))
187/// }
188///
189/// // #[tokio::test]
190/// async fn some_test() {
191///     let app = test_app();
192///
193///     let request = Request::new(Body::empty());
194///     let response = app.oneshot(request).await.unwrap();
195///     assert_eq!(response.status(), StatusCode::OK);
196/// }
197/// #
198/// # #[tokio::main]
199/// # async fn main() {
200/// #     some_test().await;
201/// # }
202/// ```
203///
204/// [`Router::into_make_service_with_connect_info`]: crate::Router::into_make_service_with_connect_info
205#[derive(Clone, Copy, Debug)]
206pub struct MockConnectInfo<T>(pub T);
207
208impl<S, T> Layer<S> for MockConnectInfo<T>
209where
210    T: Clone + Send + Sync + 'static,
211{
212    type Service = <Extension<Self> as Layer<S>>::Service;
213
214    fn layer(&self, inner: S) -> Self::Service {
215        Extension(self.clone()).layer(inner)
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222    use crate::{
223        extract::connect_info::Connected, routing::get, serve::IncomingStream, serve::Listener,
224        test_helpers::TestClient, Router,
225    };
226    use tokio::net::{TcpListener, TcpStream};
227
228    #[test]
229    fn into_make_service_traits() {
230        use crate::test_helpers::*;
231        assert_send::<IntoMakeServiceWithConnectInfo<(), NotSendSync>>();
232    }
233
234    #[allow(dead_code)]
235    #[allow(clippy::todo)]
236    fn connected_traits() {
237        // Test that the `Connected` trait can be used with custom address and listener types.
238
239        fn create_router() -> Router {
240            todo!()
241        }
242
243        fn tcp_listener() -> TcpListener {
244            todo!()
245        }
246
247        #[derive(Clone)]
248        struct CustomAddr(SocketAddr);
249
250        impl Connected<IncomingStream<'_, TcpListener>> for CustomAddr {
251            fn connect_info(_stream: IncomingStream<'_, TcpListener>) -> Self {
252                todo!()
253            }
254        }
255
256        impl Connected<IncomingStream<'_, CustomListener>> for CustomAddr {
257            fn connect_info(_stream: IncomingStream<'_, CustomListener>) -> Self {
258                todo!()
259            }
260        }
261
262        struct CustomListener {}
263
264        impl Listener for CustomListener {
265            type Io = TcpStream;
266            type Addr = SocketAddr;
267
268            async fn accept(&mut self) -> (Self::Io, Self::Addr) {
269                todo!()
270            }
271
272            fn local_addr(&self) -> tokio::io::Result<Self::Addr> {
273                todo!()
274            }
275        }
276
277        fn custom_connected() {
278            let router = create_router();
279            let _ = crate::serve(
280                tcp_listener(),
281                router.into_make_service_with_connect_info::<CustomAddr>(),
282            );
283        }
284
285        fn custom_listener() {
286            let router = create_router();
287            let _ = crate::serve(CustomListener {}, router.into_make_service());
288        }
289
290        fn custom_listener_with_connect() {
291            let router = create_router();
292            let _ = crate::serve(
293                CustomListener {},
294                router.into_make_service_with_connect_info::<SocketAddr>(),
295            );
296        }
297
298        fn custom_listener_with_custom_connect() {
299            let router = create_router();
300            let _ = crate::serve(
301                CustomListener {},
302                router.into_make_service_with_connect_info::<CustomAddr>(),
303            );
304        }
305    }
306
307    #[crate::test]
308    async fn socket_addr() {
309        async fn handler(ConnectInfo(addr): ConnectInfo<SocketAddr>) -> String {
310            format!("{addr}")
311        }
312
313        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
314        let addr = listener.local_addr().unwrap();
315
316        let (tx, rx) = tokio::sync::oneshot::channel();
317        tokio::spawn(async move {
318            let app = Router::new().route("/", get(handler));
319            tx.send(()).unwrap();
320            crate::serve(
321                listener,
322                app.into_make_service_with_connect_info::<SocketAddr>(),
323            )
324            .await;
325        });
326        rx.await.unwrap();
327
328        let client = reqwest::Client::new();
329
330        let res = client.get(format!("http://{addr}")).send().await.unwrap();
331        let body = res.text().await.unwrap();
332        assert!(body.starts_with("127.0.0.1:"));
333    }
334
335    #[crate::test]
336    async fn custom() {
337        #[derive(Clone, Debug)]
338        struct MyConnectInfo {
339            value: &'static str,
340        }
341
342        impl Connected<IncomingStream<'_, TcpListener>> for MyConnectInfo {
343            fn connect_info(_target: IncomingStream<'_, TcpListener>) -> Self {
344                Self {
345                    value: "it worked!",
346                }
347            }
348        }
349
350        async fn handler(ConnectInfo(addr): ConnectInfo<MyConnectInfo>) -> &'static str {
351            addr.value
352        }
353
354        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
355        let addr = listener.local_addr().unwrap();
356
357        let (tx, rx) = tokio::sync::oneshot::channel();
358        tokio::spawn(async move {
359            let app = Router::new().route("/", get(handler));
360            tx.send(()).unwrap();
361            crate::serve(
362                listener,
363                app.into_make_service_with_connect_info::<MyConnectInfo>(),
364            )
365            .await;
366        });
367        rx.await.unwrap();
368
369        let client = reqwest::Client::new();
370
371        let res = client.get(format!("http://{addr}")).send().await.unwrap();
372        let body = res.text().await.unwrap();
373        assert_eq!(body, "it worked!");
374    }
375
376    #[crate::test]
377    async fn mock_connect_info() {
378        async fn handler(ConnectInfo(addr): ConnectInfo<SocketAddr>) -> String {
379            format!("{addr}")
380        }
381
382        let app = Router::new()
383            .route("/", get(handler))
384            .layer(MockConnectInfo(SocketAddr::from(([0, 0, 0, 0], 1337))));
385
386        let client = TestClient::new(app);
387
388        let res = client.get("/").await;
389        let body = res.text().await;
390        assert!(body.starts_with("0.0.0.0:1337"));
391    }
392
393    #[crate::test]
394    async fn both_mock_and_real_connect_info() {
395        async fn handler(ConnectInfo(addr): ConnectInfo<SocketAddr>) -> String {
396            format!("{addr}")
397        }
398
399        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
400        let addr = listener.local_addr().unwrap();
401
402        tokio::spawn(async move {
403            let app = Router::new()
404                .route("/", get(handler))
405                .layer(MockConnectInfo(SocketAddr::from(([0, 0, 0, 0], 1337))));
406
407            crate::serve(
408                listener,
409                app.into_make_service_with_connect_info::<SocketAddr>(),
410            )
411            .await;
412        });
413
414        let client = reqwest::Client::new();
415
416        let res = client.get(format!("http://{addr}")).send().await.unwrap();
417        let body = res.text().await.unwrap();
418        assert!(body.starts_with("127.0.0.1:"));
419    }
420}