iroh 0.98.0

p2p quic connections dialed by public key
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//! Patchbay network simulation tests.
//!
//! These tests use the [`patchbay`] crate to create virtual network topologies
//! in Linux user namespaces, testing iroh's NAT traversal, holepunching,
//! and connectivity under various network conditions.
//!
//! These tests require Linux with user namespace support. On non-Linux systems, you can use
//! the `patchbay` CLI to get a Linux container or VM with the required capabilities.
//! See patchbay docs for details.
//!
//! To run:
//!
//! ```sh
//! # On Linux (with user namespace support):
//! cargo nextest run -p iroh --test patchbay --profile patchbay
//! # or use the `cargo make` alias:
//! cargo make patchbay
//! # can also pass additional args:
//! cargo make patchbay holepunch_simple --no-capture
//!
//! # On macOS (runs in container via patchbay CLI):
//! patchbay test --release -p iroh --test patchbay
//! ```

// patchbay only runs on linux, and is skipped in cross-compile environments
// via a cfg directive
#![cfg(all(target_os = "linux", not(skip_patchbay)))]

use std::{net::Ipv4Addr, time::Duration};

use ipnet::Ipv4Net;
use iroh::endpoint::Side;
use n0_error::{Result, StackResultExt};
use n0_tracing_test::traced_test;
use patchbay::{IfaceConfig, LinkCondition, LinkDirection, Nat};
use testdir::testdir;
use tracing::info;

use self::util::{Pair, PathWatcherExt, lab_with_relay, ping_accept, ping_open};

// Because we're in an integration test, we can't declare modules under patchbay/
// without setting an explicit path.
#[path = "patchbay/degrade.rs"]
mod degrade;
#[path = "patchbay/nat.rs"]
mod nat;
#[path = "patchbay/switch-uplink.rs"]
mod switch_uplink;
#[path = "patchbay/util.rs"]
mod util;

/// Init the user namespace before any threads are spawned.
///
/// This gives us all permissions we need for the patchbay tests.
#[ctor::ctor]
fn userns_ctor() {
    patchbay::init_userns().expect("failed to init userns");
}

// ---
// Holepunch tests
// ---

/// Two devices behind destination-independent NATs holepunch a direct connection.
#[tokio::test]
#[traced_test]
async fn holepunch_simple() -> Result {
    let (lab, relay_map, _relay_guard, guard) = lab_with_relay(testdir!()).await?;
    let nat1 = lab.add_router("nat1").nat(Nat::Home).build().await?;
    let nat2 = lab.add_router("nat2").nat(Nat::Home).build().await?;
    let server = lab.add_device("server").uplink(nat1.id()).build().await?;
    let client = lab.add_device("client").uplink(nat2.id()).build().await?;
    let timeout = Duration::from_secs(10);
    Pair::new(relay_map)
        .server(server, async |_dev, _ep, conn| {
            conn.closed().await;
            Ok(())
        })
        .client(client, async move |_dev, _ep, conn| {
            let mut paths = conn.paths();
            assert!(paths.selected().is_relay(), "connection started relayed");
            paths
                .wait_ip(timeout)
                .await
                .context("holepunch to direct")?;
            info!("connection became direct");
            Ok(())
        })
        .run()
        .await?;
    guard.ok();
    Ok(())
}

/// Adds a faster LAN interface on one side and verifies the path switches to it.
///
/// The active side has two uplinks: eth0 (4G-impaired) and eth1 (LAN to the
/// peer's NAT, starts down). After holepunching over 4G, eth1 comes up and
/// the selected path should switch to the faster LAN link.
async fn run_add_faster_link(active_side: Side) -> Result {
    let (lab, relay_map, _relay_guard, guard) = lab_with_relay(testdir!()).await?;
    let nat_a = lab.add_router("nat_a").nat(Nat::Home).build().await?;
    let nat_b = lab.add_router("nat_b").nat(Nat::Home).build().await?;

    let active = lab
        .add_device("active")
        .iface(
            "eth0",
            IfaceConfig::routed(nat_a.id()).condition(LinkCondition::Mobile4G, LinkDirection::Both),
        )
        .iface("eth1", IfaceConfig::routed(nat_b.id()).down())
        .build()
        .await?;
    let passive = lab
        .add_device("passive")
        .iface("eth0", nat_b.id())
        .build()
        .await?;

    let timeout = Duration::from_secs(15);
    Pair::new(relay_map)
        .left(active_side, active, async move |dev, _ep, conn| {
            let mut paths = conn.paths();
            assert!(paths.selected().is_relay(), "connection started relayed");
            let first = paths
                .wait_ip(timeout)
                .await
                .context("did not become direct")?;
            info!(addr=?first.remote_addr(), "connection became direct");
            ping_accept(&conn, timeout)
                .await
                .context("ping_accept before switch")?;

            info!("bring up faster link (eth1)");
            dev.iface("eth1").unwrap().link_up().await?;

            let next = paths
                .wait_selected(timeout, |p| {
                    p.is_ip() && p.remote_addr() != first.remote_addr()
                })
                .await
                .context("did not switch paths")?;
            info!(addr=?next.remote_addr(), "new direct path established");
            ping_accept(&conn, timeout)
                .await
                .context("ping_accept after switch")?;

            conn.closed().await;
            Ok(())
        })
        .right(passive, async move |_dev, _ep, conn| {
            let mut paths = conn.paths();
            assert!(paths.selected().is_relay(), "connection started relayed");
            let first = paths
                .wait_ip(timeout)
                .await
                .context("did not become direct")?;
            info!(addr=?first.remote_addr(), "connection became direct");
            ping_open(&conn, timeout)
                .await
                .context("ping_open before switch")?;

            let next = paths
                .wait_selected(timeout, |p| {
                    p.is_ip() && p.remote_addr() != first.remote_addr()
                })
                .await
                .context("did not switch paths")?;
            info!(addr=?next.remote_addr(), "new direct path established");
            ping_open(&conn, timeout)
                .await
                .context("ping_open after switch")?;

            conn.close(0u32.into(), b"bye");
            Ok(())
        })
        .run()
        .await?;
    guard.ok();
    Ok(())
}

#[tokio::test]
#[traced_test]
async fn add_faster_link_client() -> Result {
    run_add_faster_link(Side::Client).await
}

#[tokio::test]
#[traced_test]
async fn add_faster_link_server() -> Result {
    run_add_faster_link(Side::Server).await
}

/// Takes one side's link down after holepunching, then brings it back.
///
/// After recovery, verifies connectivity (via relay fallback or re-established
/// direct path), then waits for a direct path to be selected again.
async fn run_link_outage_recovery(outage_side: Side, downtime: Duration) -> Result {
    let (lab, relay_map, _relay_guard, guard) = lab_with_relay(testdir!()).await?;
    let nat1 = lab.add_router("nat1").nat(Nat::Home).build().await?;
    let nat2 = lab.add_router("nat2").nat(Nat::Home).build().await?;
    let outage = lab.add_device("outage").uplink(nat1.id()).build().await?;
    let peer = lab.add_device("peer").uplink(nat2.id()).build().await?;
    let timeout = Duration::from_secs(15);
    Pair::new(relay_map)
        .left(outage_side, outage, async move |dev, _ep, conn| {
            let mut paths = conn.paths();
            paths.wait_ip(timeout).await.context("initial holepunch")?;
            info!("holepunched, now killing link for {downtime:?}");
            dev.iface("eth0").unwrap().link_down().await?;
            tokio::time::sleep(downtime).await;
            dev.iface("eth0").unwrap().link_up().await?;
            info!("link restored, waiting for recovery");

            ping_open(&conn, timeout)
                .await
                .context("ping_open after link_up")?;
            info!("connection recovered after link outage");

            paths
                .wait_ip(timeout)
                .await
                .context("did not re-establish direct path")?;
            ping_open(&conn, timeout)
                .await
                .context("ping_open after direct")?;
            conn.close(0u32.into(), b"bye");
            Ok(())
        })
        .right(peer, async move |_dev, _ep, conn| {
            ping_accept(&conn, timeout).await.context("ping_accept 1")?;
            ping_accept(&conn, timeout).await.context("ping_accept 2")?;
            conn.closed().await;
            Ok(())
        })
        .run()
        .await?;
    guard.ok();
    Ok(())
}

#[tokio::test]
#[traced_test]
async fn link_outage_recovery_client() -> Result {
    run_link_outage_recovery(Side::Client, Duration::from_secs(5)).await
}

#[tokio::test]
#[traced_test]
async fn link_outage_recovery_server() -> Result {
    run_link_outage_recovery(Side::Server, Duration::from_secs(5)).await
}

/// Starts one side behind a symmetric NAT (no holepunch possible), then replugs
/// it to a Home NAT and verifies a direct path is established.
async fn run_hard_nat_to_holepunchable(replug_side: Side) -> Result {
    let (lab, relay_map, _relay_guard, guard) = lab_with_relay(testdir!()).await?;
    let nat_easy = lab.add_router("nat_easy").nat(Nat::Home).build().await?;
    let nat_hard = lab
        .add_router("nat_hard")
        .nat(Nat::Corporate)
        .build()
        .await?;
    let nat_peer = lab.add_router("nat_peer").nat(Nat::Home).build().await?;

    let replug = lab
        .add_device("replug")
        .uplink(nat_hard.id())
        .build()
        .await?;
    let stable = lab
        .add_device("stable")
        .uplink(nat_peer.id())
        .build()
        .await?;

    let timeout = Duration::from_secs(15);
    Pair::new(relay_map)
        .left(replug_side, replug, async move |dev, _ep, conn| {
            let mut paths = conn.paths();
            assert!(paths.selected().is_relay(), "connection started relayed");

            ping_accept(&conn, timeout)
                .await
                .context("ping 1 (relay)")?;

            tokio::time::sleep(Duration::from_secs(3)).await;
            assert!(
                paths.selected().is_relay(),
                "should still be relayed behind symmetric NAT"
            );

            info!("replug to holepunchable NAT");
            dev.iface("eth0").unwrap().replug(nat_easy.id()).await?;

            paths
                .wait_ip(timeout)
                .await
                .context("did not become direct after replug")?;
            info!("connection became direct");

            ping_accept(&conn, timeout)
                .await
                .context("ping 2 (direct)")?;
            conn.closed().await;
            Ok(())
        })
        .right(stable, async move |_dev, _ep, conn| {
            let mut paths = conn.paths();
            assert!(paths.selected().is_relay(), "connection started relayed");
            ping_open(&conn, timeout).await.context("ping 1 (relay)")?;
            paths
                .wait_ip(timeout)
                .await
                .context("did not become direct after replug")?;
            info!("connection became direct");
            ping_open(&conn, timeout).await.context("ping 2 (direct)")?;
            conn.close(0u32.into(), b"bye");
            Ok(())
        })
        .run()
        .await?;
    guard.ok();
    Ok(())
}

#[tokio::test]
#[traced_test]
async fn hard_nat_to_holepunchable_client() -> Result {
    run_hard_nat_to_holepunchable(Side::Client).await
}

#[tokio::test]
#[traced_test]
async fn hard_nat_to_holepunchable_server() -> Result {
    run_hard_nat_to_holepunchable(Side::Server).await
}

/// Holepunching succeeds despite many unreachable local addresses on one side.
async fn run_holepunch_many_addrs(many_addrs_side: Side, addr_count: u8) -> Result {
    let (lab, relay_map, _relay_guard, guard) = lab_with_relay(testdir!()).await?;
    let nat1 = lab.add_router("nat1").nat(Nat::Home).build().await?;
    let nat2 = lab.add_router("nat2").nat(Nat::Home).build().await?;

    let mut builder = lab.add_device("many_addrs").uplink(nat1.id());
    for i in 0..addr_count {
        builder = builder.iface(
            &format!("virt{i}"),
            IfaceConfig::dummy().addr(Ipv4Net::new_assert(Ipv4Addr::new(172, 16, 0, i + 1), 24)),
        );
    }
    let many_addrs = builder.build().await?;
    let plain = lab.add_device("plain").uplink(nat2.id()).build().await?;

    let timeout = Duration::from_secs(15);
    Pair::new(relay_map)
        .left(many_addrs_side, many_addrs, async move |_dev, _ep, conn| {
            let mut paths = conn.paths();
            assert!(paths.selected().is_relay(), "connection started relayed");
            paths
                .wait_ip(timeout)
                .await
                .context("holepunch to direct with many addrs")?;
            info!("connection became direct");
            ping_accept(&conn, timeout).await.context("ping_accept")?;
            conn.closed().await;
            Ok(())
        })
        .right(plain, async move |_dev, _ep, conn| {
            let mut paths = conn.paths();
            assert!(paths.selected().is_relay(), "connection started relayed");
            paths
                .wait_ip(timeout)
                .await
                .context("holepunch to direct with many addrs")?;
            info!("connection became direct");
            ping_open(&conn, timeout).await.context("ping_accept")?;
            conn.close(0u32.into(), b"bye");
            Ok(())
        })
        .run()
        .await?;
    guard.ok();
    Ok(())
}

#[tokio::test]
#[traced_test]
async fn holepunch_many_addrs_client_8() -> Result {
    run_holepunch_many_addrs(Side::Client, 8).await
}

#[tokio::test]
#[traced_test]
async fn holepunch_many_addrs_server_8() -> Result {
    run_holepunch_many_addrs(Side::Server, 8).await
}

#[tokio::test]
#[traced_test]
#[ignore = "not yet passing"]
async fn holepunch_many_addrs_client_16() -> Result {
    run_holepunch_many_addrs(Side::Client, 16).await
}

#[tokio::test]
#[traced_test]
#[ignore = "not yet passing"]
async fn holepunch_many_addrs_server_16() -> Result {
    run_holepunch_many_addrs(Side::Server, 16).await
}