From a2af12440f07969429f30767ec0a8367ab9853ec Mon Sep 17 00:00:00 2001 From: Franz Heinzmann Date: Mon, 25 Mar 2024 13:58:06 +0100 Subject: [PATCH] fix: do not allow connecting to ourself (#2123) ## Description This changes the `MagicEndpoint::connect` method to always return an error if attempting to connect to ourselves (i.e. connecting to the node_id of the node initiating the connection). There is no use case for this, and it is better to surface the error quickly than having users deal with weird situations in their apps later on. ## Notes & open questions ## Change checklist - [ ] Self-review. - [ ] Documentation updates if relevant. - [ ] Tests if relevant. --- iroh-net/src/magic_endpoint.rs | 35 ++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/iroh-net/src/magic_endpoint.rs b/iroh-net/src/magic_endpoint.rs index 6301fd695d..318ce5da92 100644 --- a/iroh-net/src/magic_endpoint.rs +++ b/iroh-net/src/magic_endpoint.rs @@ -405,6 +405,14 @@ impl MagicEndpoint { /// If addresses or relay servers are neither provided nor can be discovered, the connection /// attempt will fail with an error. pub async fn connect(&self, node_addr: NodeAddr, alpn: &[u8]) -> Result { + // Connecting to ourselves is not supported. + if node_addr.node_id == self.node_id() { + bail!( + "Connecting to ourself is not supported ({} is the node id of this node)", + node_addr.node_id.fmt_short() + ); + } + if !node_addr.info.is_empty() { self.add_node_addr(node_addr.clone())?; } @@ -501,6 +509,13 @@ impl MagicEndpoint { /// If no UDP addresses are added, and the given `relay_url` cannot be dialed, it will error. // TODO: This is infallible, stop returning a result. pub fn add_node_addr(&self, node_addr: NodeAddr) -> Result<()> { + // Connecting to ourselves is not supported. + if node_addr.node_id == self.node_id() { + bail!( + "Adding our own address is not supported ({} is the node id of this node)", + node_addr.node_id.fmt_short() + ); + } self.msock.add_node_addr(node_addr); Ok(()) } @@ -620,6 +635,26 @@ mod tests { ); } + #[tokio::test] + async fn test_connect_self() { + let _guard = iroh_test::logging::setup(); + let ep = MagicEndpoint::builder() + .alpns(vec![TEST_ALPN.to_vec()]) + .bind(0) + .await + .unwrap(); + let my_addr = ep.my_addr().await.unwrap(); + let res = ep.connect(my_addr.clone(), TEST_ALPN).await; + assert!(res.is_err()); + let err = res.err().unwrap(); + assert!(err.to_string().starts_with("Connecting to ourself")); + + let res = ep.add_node_addr(my_addr); + assert!(res.is_err()); + let err = res.err().unwrap(); + assert!(err.to_string().starts_with("Adding our own address")); + } + #[tokio::test] async fn magic_endpoint_connect_close() { let _guard = iroh_test::logging::setup();