Skip to content

Commit

Permalink
fix: do not allow connecting to ourself (#2123)
Browse files Browse the repository at this point in the history
## 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

<!-- Any notes, remarks or open questions you have to make about the PR.
-->

## Change checklist

- [ ] Self-review.
- [ ] Documentation updates if relevant.
- [ ] Tests if relevant.
  • Loading branch information
Frando authored Mar 25, 2024
1 parent 2c59d7d commit a2af124
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions iroh-net/src/magic_endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<quinn::Connection> {
// 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())?;
}
Expand Down Expand Up @@ -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(())
}
Expand Down Expand Up @@ -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();
Expand Down

0 comments on commit a2af124

Please sign in to comment.