Skip to content

Commit 8d487d6

Browse files
committed
add endpoint hooks page
1 parent 71c97d3 commit 8d487d6

File tree

1 file changed

+143
-0
lines changed

1 file changed

+143
-0
lines changed

connecting/endpoint-hooks.mdx

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
---
2+
title: Endpoint Hooks
3+
---
4+
5+
Endpoint hooks allow you to intercept the connection-establishment process of an iroh `Endpoint`.
6+
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.
7+
8+
Hooks run at two points:
9+
10+
1. **Before an outgoing connection starts**. No packets have been sent yet.
11+
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.
12+
13+
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.
14+
15+
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.
16+
17+
> **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.
18+
19+
## Example: Observing connection events
20+
21+
This example shows a minimal hook implementation that logs the context available at each stage. It does not alter behavior, only observes.
22+
23+
```rust
24+
use iroh::{
25+
Endpoint, EndpointAddr, Watcher,
26+
endpoint::{AfterHandshakeOutcome, BeforeConnectOutcome, ConnectionInfo, EndpointHooks},
27+
};
28+
29+
/// Our hooks instance.
30+
///
31+
/// As we are only observing, we don't need to hold any state, thus we use a zero-sized struct.
32+
#[derive(Debug)]
33+
struct LogHooks;
34+
35+
/// To use hooks, you need to implement the `EndpointHooks` trait.
36+
impl EndpointHooks for LogHooks {
37+
// Runs before an outgoing connection begins.
38+
async fn before_connect(
39+
&self,
40+
remote_addr: &EndpointAddr,
41+
alpn: &[u8],
42+
) -> BeforeConnectOutcome {
43+
tracing::info!(?remote_addr, ?alpn, "attempting to connect");
44+
BeforeConnectOutcome::Accept
45+
}
46+
47+
// Runs after the handshake for both incoming and outgoing connections.
48+
//
49+
// `ConnectionInfo` gives information about a connection, but doesn't allow to use it otherwise.
50+
async fn after_handshake(&self, conn: &ConnectionInfo) -> AfterHandshakeOutcome {
51+
// This tells us whether `conn` is an incoming or outgoing connection.
52+
let side = conn.side();
53+
let remote = conn.remote_id().fmt_short();
54+
55+
tracing::info!(%remote, alpn=?conn.alpn(), ?side, "connection established");
56+
57+
// We can spawn a task to observe network path changes for this connection.
58+
let mut path_updates = conn.paths();
59+
tokio::spawn(async move {
60+
while let Ok(paths) = path_updates.updated().await {
61+
tracing::info!(%remote, ?paths, "paths updated");
62+
}
63+
});
64+
65+
AfterHandshakeOutcome::Accept
66+
}
67+
}
68+
69+
#[tokio::main]
70+
async fn main() -> n0_error::Result<()> {
71+
tracing_subscriber::fmt::init();
72+
// Install the hooks on our endpoint.
73+
let _endpoint = Endpoint::builder().hooks(LogHooks).bind().await?;
74+
// Use `endpoint` normally...
75+
Ok(())
76+
}
77+
```
78+
79+
## Example: Rejecting connections
80+
81+
Hooks can be used to enforce policy. If a hook returns a rejection result, the connection is immediately aborted.
82+
The example below rejects all incoming connections after the handshake. Outgoing connections will still dial.
83+
84+
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.
85+
86+
```rust
87+
use iroh::endpoint::{AfterHandshakeOutcome, ConnectionInfo, Endpoint, EndpointHooks, Side};
88+
89+
#[derive(Debug)]
90+
struct RejectIncomingHook;
91+
92+
impl EndpointHooks for RejectIncomingHook {
93+
async fn after_handshake(&self, conn: &ConnectionInfo) -> AfterHandshakeOutcome {
94+
// Unconditionally reject all incoming connections.
95+
// In actual apps, you could conditionally allow or accept by checking the connection's
96+
// ALPN and remote id.
97+
if conn.side() == Side::Server {
98+
AfterHandshakeOutcome::Reject {
99+
error_code: 403u32.into(),
100+
reason: b"rejected".into(),
101+
}
102+
} else {
103+
AfterHandshakeOutcome::Accept
104+
}
105+
}
106+
}
107+
108+
#[tokio::main]
109+
async fn main() -> n0_error::Result<()> {
110+
tracing_subscriber::fmt::init();
111+
let _endpoint = Endpoint::builder().hooks(RejectIncomingHook).bind().await?;
112+
Ok(())
113+
}
114+
```
115+
116+
## More examples
117+
118+
There are a few fully-featured examples for using hooks in the iroh repository.
119+
120+
### [Authentication layer](https://github.com/n0-computer/iroh/blob/feat-multipath/iroh/examples/auth-hook.rs)
121+
122+
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.
123+
124+
* We implement a dedicated “auth” protocol (with its own ALPN) for performing a pre-authentication handshake.
125+
* Outgoing connections run the pre-auth step before starting other connections.
126+
* Incoming connections are checked against a set of authorized remote ids.
127+
* If an incoming connection comes from a peer that hasn't successfully performed pre-auth, the connection is rejected.
128+
129+
### [Monitoring connection and path events](https://github.com/n0-computer/iroh/blob/feat-multipath/iroh/examples/monitor-connections.rs)
130+
131+
This example demonstrates how hooks can feed information to external tasks, giving you flexible observability.
132+
133+
* A hook sends each `ConnectionInfo` to a monitoring task.
134+
* The monitor can record events and stats.
135+
136+
### [Aggregating information about remote endpoints](https://github.com/n0-computer/iroh/blob/feat-multipath/iroh/examples/remote-info.rs)
137+
138+
This example implements a `RemoteMap` that tracks and aggregates information about all remotes our endpoint knows about.
139+
This can be useful if your app needs to chose between remotes, or for building diagnostic tools.
140+
141+
* A hook forwards `ConnectionInfo` updates into a worker task.
142+
* 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).
143+
* The `RemoteMap` exposes a simple API to query all known remotes and their aggregate metrics.

0 commit comments

Comments
 (0)