pai-sho 0.5.2

Forward ports between your own machines, peer to peer over iroh. Neither side needs an account, a public IP, or an open inbound port. A port is reachable only by the peers you grant it to.
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
//! Live tests over loopback: two daemons, real QUIC, no network.
//!
//! Endpoints are built with relays disabled and a `MemoryLookup` seeded with
//! each other's bound sockets, so nothing here reaches a relay, DNS, or the
//! LAN. What is covered is the part the pure core cannot reach: that bytes
//! actually cross a granted tunnel, and that the shell carries out the core's
//! verdicts.
//!
//! The admission and authorization rules themselves are asserted in
//! src/core/session.rs, without any of this machinery.

use crate::daemon::Daemon;
use crate::protocol::{Request, Response, ALPN, VERSION};
use iroh::address_lookup::memory::MemoryLookup;
use iroh::endpoint::{presets, PortmapperConfig};
use iroh::{Endpoint, EndpointAddr, RelayMode};
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};

/// A temp directory that cleans up when the test ends, pass or fail.
struct TempDir(PathBuf);

impl TempDir {
    fn new(tag: &str) -> Self {
        let path = std::env::temp_dir().join(format!(
            "pai-sho-test-{}-{}-{:?}",
            tag,
            std::process::id(),
            std::thread::current().id()
        ));
        std::fs::create_dir_all(&path).unwrap();
        Self(path)
    }

    fn prefix(&self) -> PathBuf {
        self.0.join("key")
    }
}

impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

/// An endpoint that cannot leave the machine: no relays, no address lookup
/// beyond what we seed by hand, no port mapping.
async fn test_endpoint(lookup: &MemoryLookup) -> Endpoint {
    Endpoint::builder(presets::Minimal)
        .relay_mode(RelayMode::Disabled)
        .portmapper_config(PortmapperConfig::Disabled)
        .clear_address_lookup()
        .address_lookup(lookup.clone())
        .alpns(vec![ALPN.to_vec()])
        .bind_addr(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
        .unwrap()
        .bind()
        .await
        .unwrap()
}

fn addr_of(ep: &Endpoint) -> EndpointAddr {
    let mut addr = EndpointAddr::new(ep.id());
    for sock in ep.bound_sockets() {
        addr = addr.with_ip_addr(sock);
    }
    addr
}

struct TestDaemon {
    daemon: Arc<Daemon>,
    _router: iroh::protocol::Router,
    _dir: TempDir,
}

impl TestDaemon {
    async fn start(tag: &str, lookup: &MemoryLookup, host: IpAddr) -> Self {
        let dir = TempDir::new(tag);
        let endpoint = test_endpoint(lookup).await;
        let daemon = Daemon::with_endpoint(endpoint, host, &dir.prefix(), None, None)
            .await
            .unwrap();
        let router = daemon.spawn_router();
        Self {
            daemon,
            _router: router,
            _dir: dir,
        }
    }

    fn key(&self) -> String {
        self.daemon.endpoint().id().to_string()
    }

    async fn request(&self, req: Request) -> Response {
        self.daemon.handle_request(req).await
    }
}

/// Two daemons that can find each other, and nothing else.
async fn pair(host: IpAddr) -> (TestDaemon, TestDaemon) {
    let (lookup_a, lookup_b) = (MemoryLookup::new(), MemoryLookup::new());
    let a = TestDaemon::start("a", &lookup_a, host).await;
    let b = TestDaemon::start("b", &lookup_b, host).await;

    lookup_a.add_endpoint_info(addr_of(b.daemon.endpoint()));
    lookup_b.add_endpoint_info(addr_of(a.daemon.endpoint()));

    (a, b)
}

/// Link `b` to `a` the way an operator would: `a` extends an invitation and
/// `b` takes it up.
async fn enroll(a: &TestDaemon, b: &TestDaemon, name: &str) {
    let invite = match a
        .request(Request::Invite {
            key: None,
            name: Some(name.to_string()),
            expose: vec![],
        })
        .await
    {
        Response::Invite(i) => i,
        other => panic!("expected an invitation, got {:?}", other),
    };

    match b
        .request(Request::Accept {
            handle: invite,
            name: Some("a".to_string()),
        })
        .await
    {
        Response::Ok => {}
        other => panic!("accept failed: {:?}", other),
    }
}

/// A TCP echo server on 127.0.0.1, standing in for whatever a daemon forwards
/// to. Returns the port it bound.
async fn echo_server() -> u16 {
    let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
    let port = listener.local_addr().unwrap().port();
    tokio::spawn(async move {
        while let Ok((mut sock, _)) = listener.accept().await {
            tokio::spawn(async move {
                let mut buf = [0u8; 1024];
                loop {
                    match sock.read(&mut buf).await {
                        Ok(0) | Err(_) => return,
                        Ok(n) => {
                            if sock.write_all(&buf[..n]).await.is_err() {
                                return;
                            }
                        }
                    }
                }
            });
        }
    });
    port
}

/// Poll until `f` returns Some, or fail after `secs`. Nothing here waits on a
/// fixed sleep: the daemons settle at their own pace.
async fn until<T, F, Fut>(secs: u64, mut f: F) -> T
where
    F: FnMut() -> Fut,
    Fut: std::future::Future<Output = Option<T>>,
{
    let deadline = tokio::time::Instant::now() + Duration::from_secs(secs);
    loop {
        if let Some(v) = f().await {
            return v;
        }
        if tokio::time::Instant::now() > deadline {
            panic!("timed out after {}s", secs);
        }
        tokio::time::sleep(Duration::from_millis(25)).await;
    }
}

/// Where `b` has bound `a`'s `port`, once it has.
async fn bound_addr(b: &TestDaemon, port: u16) -> SocketAddr {
    until(20, || async {
        let peers = b.daemon.peers().list().await;
        let p = peers.iter().find(|p| p.bound.contains(&port))?;
        let ip: IpAddr = p.ip.as_ref()?.parse().ok()?;
        Some(SocketAddr::from((ip, port)))
    })
    .await
}

// ---------------------------------------------------------------------------

/// Write `data: ping`, wait until the caller says so, then write `\n\n`.
/// Stays open. Returns the port and a oneshot that releases the terminator.
async fn sse_split_server() -> (u16, tokio::sync::oneshot::Sender<()>) {
    let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
    let port = listener.local_addr().unwrap().port();
    let (release_rest, wait_rest) = tokio::sync::oneshot::channel();
    tokio::spawn(async move {
        let (mut sock, _) = listener.accept().await.unwrap();
        sock.set_nodelay(true).ok();
        sock.write_all(b"data: ping").await.unwrap();
        sock.flush().await.ok();
        let _ = wait_rest.await;
        sock.write_all(b"\n\n").await.unwrap();
        sock.flush().await.ok();
        std::future::pending::<()>().await;
    });
    (port, release_rest)
}

#[tokio::test]
async fn a_granted_port_carries_bytes() {
    let port = echo_server().await;
    let (a, b) = pair(IpAddr::V4(Ipv4Addr::LOCALHOST)).await;
    enroll(&a, &b, "b").await;

    a.request(Request::Expose {
        port,
        to: vec![b.key()],
        all: false,
    })
    .await;

    let addr = bound_addr(&b, port).await;
    let mut sock = TcpStream::connect(addr).await.unwrap();
    sock.write_all(b"hello pai-sho").await.unwrap();

    let mut buf = [0u8; 13];
    sock.read_exact(&mut buf).await.unwrap();
    assert_eq!(&buf, b"hello pai-sho");
}

#[tokio::test]
async fn an_sse_fragment_arrives_before_the_rest_is_sent() {
    let (port, release_rest) = sse_split_server().await;
    let (a, b) = pair(IpAddr::V4(Ipv4Addr::LOCALHOST)).await;
    enroll(&a, &b, "b").await;

    a.request(Request::Expose {
        port,
        to: vec![b.key()],
        all: false,
    })
    .await;

    let addr = bound_addr(&b, port).await;
    let mut sock = TcpStream::connect(addr).await.unwrap();
    sock.set_nodelay(true).ok();

    let mut first = [0u8; 10];
    tokio::time::timeout(Duration::from_secs(2), sock.read_exact(&mut first))
        .await
        .expect("first SSE fragment did not arrive before the terminator was sent")
        .unwrap();
    assert_eq!(&first, b"data: ping");

    release_rest.send(()).unwrap();

    let mut rest = [0u8; 2];
    tokio::time::timeout(Duration::from_secs(2), sock.read_exact(&mut rest))
        .await
        .expect("SSE terminator did not arrive")
        .unwrap();
    assert_eq!(&rest, b"\n\n");
}

#[tokio::test]
async fn an_ungranted_port_is_never_announced() {
    let port = echo_server().await;
    let (a, b) = pair(IpAddr::V4(Ipv4Addr::LOCALHOST)).await;
    enroll(&a, &b, "b").await;

    // Grant, wait for the binding, then revoke.
    a.request(Request::Expose {
        port,
        to: vec![b.key()],
        all: false,
    })
    .await;
    bound_addr(&b, port).await;

    a.request(Request::Unexpose { port, to: None }).await;

    // The revocation reaches b and its binding goes away.
    until(20, || async {
        let peers = b.daemon.peers().list().await;
        peers.iter().all(|p| !p.bound.contains(&port)).then_some(())
    })
    .await;
}

#[tokio::test]
async fn a_peer_with_no_grant_is_told_nothing() {
    let (a, b) = pair(IpAddr::V4(Ipv4Addr::LOCALHOST)).await;
    enroll(&a, &b, "b").await;

    // Wait for the link, then confirm b was announced no ports at all.
    until(20, || async {
        let peers = b.daemon.peers().list().await;
        peers.iter().find(|p| p.online).map(|_| ())
    })
    .await;

    let peers = b.daemon.peers().list().await;
    let a_seen = peers.iter().find(|p| p.key == a.key()).unwrap();
    assert!(a_seen.they_expose.is_empty());
}

#[tokio::test]
async fn list_shows_our_version_and_the_peers() {
    let (a, b) = pair(IpAddr::V4(Ipv4Addr::LOCALHOST)).await;
    enroll(&a, &b, "b").await;

    until(20, || async {
        let Response::List(a_list) = a.request(Request::List).await else {
            return None;
        };
        let Response::List(b_list) = b.request(Request::List).await else {
            return None;
        };
        let a_sees_b = a_list.peers.iter().find(|p| p.key == b.key())?;
        let b_sees_a = b_list.peers.iter().find(|p| p.key == a.key())?;
        (a_list.daemon == VERSION
            && b_list.daemon == VERSION
            && a_sees_b.version.as_deref() == Some(VERSION)
            && b_sees_a.version.as_deref() == Some(VERSION))
        .then_some(())
    })
    .await;
}

#[tokio::test]
async fn an_unenrolled_peer_is_refused() {
    let (a, b) = pair(IpAddr::V4(Ipv4Addr::LOCALHOST)).await;

    // b reaches for a by key alone, with no invitation. a admits nothing.
    b.request(Request::Accept {
        handle: a.key(),
        name: None,
    })
    .await;

    tokio::time::sleep(Duration::from_millis(500)).await;

    let peers = a.daemon.peers().list().await;
    assert!(
        peers.is_empty(),
        "a admitted an unenrolled peer: {:?}",
        peers
    );
}

#[tokio::test]
async fn forwarding_honours_the_host_address() {
    // A daemon told to forward to an address with nothing on it still
    // announces the grant; the tunnel just finds no service.
    let port = echo_server().await;
    let (a, b) = pair(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2))).await;
    enroll(&a, &b, "b").await;

    a.request(Request::Expose {
        port,
        to: vec![b.key()],
        all: false,
    })
    .await;

    let addr = bound_addr(&b, port).await;
    let mut sock = TcpStream::connect(addr).await.unwrap();

    // 127.0.0.2 has no listener on that port, so the tunnel closes without
    // ever reaching the echo server on 127.0.0.1.
    let mut buf = [0u8; 1];
    let _ = sock.write_all(b"x").await;
    assert_eq!(sock.read(&mut buf).await.unwrap(), 0);
}

#[tokio::test]
async fn a_peer_added_before_its_daemon_is_up_is_still_recorded() {
    let lookup = MemoryLookup::new();
    let b = TestDaemon::start("b", &lookup, IpAddr::V4(Ipv4Addr::LOCALHOST)).await;

    // A key that resolves to nothing: the dial cannot succeed.
    let absent = iroh::SecretKey::from_bytes(&[7u8; 32]).public().to_string();
    b.request(Request::Accept {
        handle: absent.clone(),
        name: None,
    })
    .await;

    let peers = b.daemon.peers().list().await;
    assert_eq!(peers.len(), 1);
    assert_eq!(peers[0].key, absent);
    assert!(!peers[0].online);
}

#[tokio::test]
async fn a_port_blocked_at_first_still_binds() {
    let port = echo_server().await;
    let (a, b) = pair(IpAddr::V4(Ipv4Addr::LOCALHOST)).await;
    enroll(&a, &b, "b").await;

    // Occupy the address b will project onto, so its first bind attempt
    // fails. b announces nothing new afterwards, so without a retry the port
    // would stay dark.
    let blocker = TcpListener::bind(SocketAddr::from((
        IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)),
        port,
    )))
    .await
    .unwrap();

    a.request(Request::Expose {
        port,
        to: vec![b.key()],
        all: false,
    })
    .await;

    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(250)).await;
        drop(blocker);
    });

    let addr = bound_addr(&b, port).await;
    let mut sock = TcpStream::connect(addr).await.unwrap();
    sock.write_all(b"late").await.unwrap();
    let mut buf = [0u8; 4];
    sock.read_exact(&mut buf).await.unwrap();
    assert_eq!(&buf, b"late");
}

#[tokio::test]
async fn an_invitation_can_bring_its_own_grant() {
    let port = echo_server().await;
    let (a, b) = pair(IpAddr::V4(Ipv4Addr::LOCALHOST)).await;

    // One command on a: the invitation carries the grant.
    let invite = match a
        .request(Request::Invite {
            key: None,
            name: Some("b".into()),
            expose: vec![port],
        })
        .await
    {
        Response::Invite(i) => i,
        other => panic!("expected an invitation, got {:?}", other),
    };

    // One command on b, and the port is reachable. No expose step.
    b.request(Request::Accept {
        handle: invite,
        name: Some("a".into()),
    })
    .await;

    let addr = bound_addr(&b, port).await;
    let mut sock = TcpStream::connect(addr).await.unwrap();
    sock.write_all(b"carried").await.unwrap();
    let mut buf = [0u8; 7];
    sock.read_exact(&mut buf).await.unwrap();
    assert_eq!(&buf, b"carried");
}

#[tokio::test]
async fn an_unnamed_peer_still_gets_a_name() {
    let port = echo_server().await;
    let (a, b) = pair(IpAddr::V4(Ipv4Addr::LOCALHOST)).await;

    // Neither side passes --as.
    let invite = match a
        .request(Request::Invite {
            key: None,
            name: None,
            expose: vec![port],
        })
        .await
    {
        Response::Invite(i) => i,
        other => panic!("expected an invitation, got {:?}", other),
    };
    b.request(Request::Accept {
        handle: invite,
        name: None,
    })
    .await;

    bound_addr(&b, port).await;

    let peers = b.daemon.peers().list().await;
    let seen = peers.iter().find(|p| p.key == a.key()).unwrap();
    assert!(seen.name.is_none(), "nothing named it");

    // The surface is still reachable by name: a short form of the key.
    let short: String = a.key().chars().take(8).collect();
    assert!(b.daemon.peers().resolve_name(&short).await.is_some());
}