From 8d487d6918d28dc8ffce8eb3b2637ab03b2502d4 Mon Sep 17 00:00:00 2001 From: Frando Date: Fri, 5 Dec 2025 14:55:55 +0100 Subject: [PATCH 1/4] add endpoint hooks page --- connecting/endpoint-hooks.mdx | 143 ++++++++++++++++++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 connecting/endpoint-hooks.mdx diff --git a/connecting/endpoint-hooks.mdx b/connecting/endpoint-hooks.mdx new file mode 100644 index 0000000..139dbe5 --- /dev/null +++ b/connecting/endpoint-hooks.mdx @@ -0,0 +1,143 @@ +--- +title: Endpoint Hooks +--- + +Endpoint hooks allow you to intercept the connection-establishment process of an iroh `Endpoint`. +They are a lightweight, flexible mechanism for observing connection events or rejecting connections based on conditions. The latter can be used to implement custom authentication schemes. + +Hooks run at two points: + +1. **Before an outgoing connection starts**. No packets have been sent yet. +2. **After the QUIC/TLS handshake completes** for both incoming and outgoing connections. The remote endpoint ID, ALPN, and other metadata are available, but no application data has been sent or received yet. + +Hooks are registered with `Endpoint::builder().hooks(...)`. If multiple hooks are installed, they run in the order they were added, and a rejection from any hook short-circuits the rest. + +Note that hooks cannot *use* connections, they can only *observe* or *reject* them. This is an important seperation of concerns: If hooks were allowed to use the connections in any way, they could interfer with the actual protocols running within these connections. Hooks can, however, *reject* connections before they are passed on to protocol handlers. This makes it possible to implement custom authentication schemes with hooks that work without any support from the protocols running in these connections. + +> **Note:** Hooks live on the `Endpoint` instance. Never store an `Endpoint` inside your hook type (even indirectly), or it may cause reference-counting cycles and prevent clean shutdown. + +## Example: Observing connection events + +This example shows a minimal hook implementation that logs the context available at each stage. It does not alter behavior, only observes. + +```rust +use iroh::{ + Endpoint, EndpointAddr, Watcher, + endpoint::{AfterHandshakeOutcome, BeforeConnectOutcome, ConnectionInfo, EndpointHooks}, +}; + +/// Our hooks instance. +/// +/// As we are only observing, we don't need to hold any state, thus we use a zero-sized struct. +#[derive(Debug)] +struct LogHooks; + +/// To use hooks, you need to implement the `EndpointHooks` trait. +impl EndpointHooks for LogHooks { + // Runs before an outgoing connection begins. + async fn before_connect( + &self, + remote_addr: &EndpointAddr, + alpn: &[u8], + ) -> BeforeConnectOutcome { + tracing::info!(?remote_addr, ?alpn, "attempting to connect"); + BeforeConnectOutcome::Accept + } + + // Runs after the handshake for both incoming and outgoing connections. + // + // `ConnectionInfo` gives information about a connection, but doesn't allow to use it otherwise. + async fn after_handshake(&self, conn: &ConnectionInfo) -> AfterHandshakeOutcome { + // This tells us whether `conn` is an incoming or outgoing connection. + let side = conn.side(); + let remote = conn.remote_id().fmt_short(); + + tracing::info!(%remote, alpn=?conn.alpn(), ?side, "connection established"); + + // We can spawn a task to observe network path changes for this connection. + let mut path_updates = conn.paths(); + tokio::spawn(async move { + while let Ok(paths) = path_updates.updated().await { + tracing::info!(%remote, ?paths, "paths updated"); + } + }); + + AfterHandshakeOutcome::Accept + } +} + +#[tokio::main] +async fn main() -> n0_error::Result<()> { + tracing_subscriber::fmt::init(); + // Install the hooks on our endpoint. + let _endpoint = Endpoint::builder().hooks(LogHooks).bind().await?; + // Use `endpoint` normally... + Ok(()) +} +``` + +## Example: Rejecting connections + +Hooks can be used to enforce policy. If a hook returns a rejection result, the connection is immediately aborted. +The example below rejects all incoming connections after the handshake. Outgoing connections will still dial. + +In real applications, you would inspect `ConnectionInfo` and reject connections by checking the connection's remote id or aLPN against authentication state in your app. + +```rust +use iroh::endpoint::{AfterHandshakeOutcome, ConnectionInfo, Endpoint, EndpointHooks, Side}; + +#[derive(Debug)] +struct RejectIncomingHook; + +impl EndpointHooks for RejectIncomingHook { + async fn after_handshake(&self, conn: &ConnectionInfo) -> AfterHandshakeOutcome { + // Unconditionally reject all incoming connections. + // In actual apps, you could conditionally allow or accept by checking the connection's + // ALPN and remote id. + if conn.side() == Side::Server { + AfterHandshakeOutcome::Reject { + error_code: 403u32.into(), + reason: b"rejected".into(), + } + } else { + AfterHandshakeOutcome::Accept + } + } +} + +#[tokio::main] +async fn main() -> n0_error::Result<()> { + tracing_subscriber::fmt::init(); + let _endpoint = Endpoint::builder().hooks(RejectIncomingHook).bind().await?; + Ok(()) +} +``` + +## More examples + +There are a few fully-featured examples for using hooks in the iroh repository. + +### [Authentication layer](https://github.com/n0-computer/iroh/blob/feat-multipath/iroh/examples/auth-hook.rs) + +Demonstrates how to build an authentication flow on top of hooks. This pattern keeps authentication separate from your application protocols while still integrating cleanly with iroh’s connection lifecycle. + +* We implement a dedicated “auth” protocol (with its own ALPN) for performing a pre-authentication handshake. +* Outgoing connections run the pre-auth step before starting other connections. +* Incoming connections are checked against a set of authorized remote ids. +* If an incoming connection comes from a peer that hasn't successfully performed pre-auth, the connection is rejected. + +### [Monitoring connection and path events](https://github.com/n0-computer/iroh/blob/feat-multipath/iroh/examples/monitor-connections.rs) + +This example demonstrates how hooks can feed information to external tasks, giving you flexible observability. + +* A hook sends each `ConnectionInfo` to a monitoring task. +* The monitor can record events and stats. + +### [Aggregating information about remote endpoints](https://github.com/n0-computer/iroh/blob/feat-multipath/iroh/examples/remote-info.rs) + +This example implements a `RemoteMap` that tracks and aggregates information about all remotes our endpoint knows about. +This can be useful if your app needs to chose between remotes, or for building diagnostic tools. + +* A hook forwards `ConnectionInfo` updates into a worker task. +* The worker maintains a map of all remotes with counts of active connections and observed statistics (e.g. latency/RTT, whether relay/IP paths were used, etc). +* The `RemoteMap` exposes a simple API to query all known remotes and their aggregate metrics. From a167002f5dc654138419bdeefaa1d83756c6d73d Mon Sep 17 00:00:00 2001 From: Frando Date: Fri, 5 Dec 2025 15:01:55 +0100 Subject: [PATCH 2/4] add to nav --- docs.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs.json b/docs.json index b859373..50c3a55 100644 --- a/docs.json +++ b/docs.json @@ -39,7 +39,8 @@ "connecting/dns-discovery", "connecting/dht-discovery", "connecting/local-discovery", - "connecting/gossip" + "connecting/gossip", + "connecting/endpoint-hooks" ] }, { From 1b60127be652104f173058de76848aff9f09ca66 Mon Sep 17 00:00:00 2001 From: Frando Date: Fri, 5 Dec 2025 15:04:38 +0100 Subject: [PATCH 3/4] chore: spelling --- connecting/endpoint-hooks.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/connecting/endpoint-hooks.mdx b/connecting/endpoint-hooks.mdx index 139dbe5..7a39e74 100644 --- a/connecting/endpoint-hooks.mdx +++ b/connecting/endpoint-hooks.mdx @@ -12,7 +12,7 @@ Hooks run at two points: Hooks are registered with `Endpoint::builder().hooks(...)`. If multiple hooks are installed, they run in the order they were added, and a rejection from any hook short-circuits the rest. -Note that hooks cannot *use* connections, they can only *observe* or *reject* them. This is an important seperation of concerns: If hooks were allowed to use the connections in any way, they could interfer with the actual protocols running within these connections. Hooks can, however, *reject* connections before they are passed on to protocol handlers. This makes it possible to implement custom authentication schemes with hooks that work without any support from the protocols running in these connections. +Note that hooks cannot *use* connections, they can only *observe* or *reject* them. This is an important separation of concerns: If hooks were allowed to use the connections in any way, they could interfer with the actual protocols running within these connections. Hooks can, however, *reject* connections before they are passed on to protocol handlers. This makes it possible to implement custom authentication schemes with hooks that work without any support from the protocols running in these connections. > **Note:** Hooks live on the `Endpoint` instance. Never store an `Endpoint` inside your hook type (even indirectly), or it may cause reference-counting cycles and prevent clean shutdown. From 7a62f5c852f44778121385454b8cffded187568c Mon Sep 17 00:00:00 2001 From: Frando Date: Fri, 5 Dec 2025 15:10:49 +0100 Subject: [PATCH 4/4] update --- connecting/endpoint-hooks.mdx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/connecting/endpoint-hooks.mdx b/connecting/endpoint-hooks.mdx index 7a39e74..8bde351 100644 --- a/connecting/endpoint-hooks.mdx +++ b/connecting/endpoint-hooks.mdx @@ -25,6 +25,7 @@ use iroh::{ Endpoint, EndpointAddr, Watcher, endpoint::{AfterHandshakeOutcome, BeforeConnectOutcome, ConnectionInfo, EndpointHooks}, }; +use tracing::info; /// Our hooks instance. /// @@ -40,7 +41,7 @@ impl EndpointHooks for LogHooks { remote_addr: &EndpointAddr, alpn: &[u8], ) -> BeforeConnectOutcome { - tracing::info!(?remote_addr, ?alpn, "attempting to connect"); + info!(?remote_addr, ?alpn, "attempting to connect"); BeforeConnectOutcome::Accept } @@ -52,13 +53,13 @@ impl EndpointHooks for LogHooks { let side = conn.side(); let remote = conn.remote_id().fmt_short(); - tracing::info!(%remote, alpn=?conn.alpn(), ?side, "connection established"); + info!(%remote, alpn=?conn.alpn(), ?side, "connection established"); // We can spawn a task to observe network path changes for this connection. let mut path_updates = conn.paths(); tokio::spawn(async move { while let Ok(paths) = path_updates.updated().await { - tracing::info!(%remote, ?paths, "paths updated"); + info!(%remote, ?paths, "paths updated"); } });