devsandbox 0.9.0

Manage devcontainer-style sandboxes on docker, podman, or Apple container — many throwaway instances per repo from one TOML config.
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
//! Remote bridges (docs/architecture/daemon/forwards.md, *Remote bridges*):
//! [`remote_opener`], the forward engine's opener that opens a `TUNNEL`
//! stream through a machine's link socket ([`Via::Fleet`]: the [`Request`]
//! line first; the machine's end is `serve::fleet::tunnel`), and the
//! one-line header that answers it.
//!
//! The far side resolves the route on its own host ([`resolve`]: its
//! config, state, runtime), writes a [`Header`], then runs the in-container
//! `devsbd bridge` on the rest of the stream, so it carries the usual bridge
//! handshake and mux right after the header line. This side reads the
//! header byte by byte (nothing past its newline is consumed) and hands the
//! rest of the stream to `bridge::attach`.

use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::time::{Duration, Instant};

use serde::{Deserialize, Serialize};

use super::port::{self, LoadState};
use crate::devsbd::bridge::{self, Bridge};
use crate::devsbd::forward::{Opened, Opener, ProcessLookup, Route};
use crate::serve::machines::ssh::{self, SkipError};

/// What starts the header line; lines before it are skipped, and it may
/// follow other bytes on its line.
const MAGIC: &str = "devsandbox-tunnel";

/// The header's format version, after the magic. Bumped only on an
/// incompatible change; a reader refuses any other.
const VERSION: u32 = 1;

/// How much a reader takes before giving up on a header: noise and the line
/// itself together.
const HEADER_LIMIT: usize = 64 * 1024;

/// How long the remote opener waits for the header: the far side's route
/// resolution (a helper install included). Matches the engine's handshake
/// wait.
const HEADER_WAIT: Duration = Duration::from_secs(10);

/// How often the remote opener checks `stop` while it waits.
const STOP_POLL: Duration = Duration::from_millis(50);

/// The one line a machine's `TUNNEL` stream starts with, before the
/// bridge's bytes: `devsandbox-tunnel 1 <json>\n`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Header {
    /// The route couldn't be resolved there: why, as the far side says it.
    Error { error: String },
    /// The route, resolved there: its label, what the far helper dials, the
    /// helper's hash (informational, for the Hello) and whether the port
    /// lives in the container the bridge runs in (`helper`: its helper can
    /// say who listens; not for a via-instance route).
    Route {
        label: String,
        host: String,
        port: u16,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        hash: Option<String>,
        #[serde(default)]
        helper: bool,
    },
}

impl Header {
    /// The header of a [`resolve`]: the route, or why there is none.
    pub fn of(route: &Result<Route, String>) -> Header {
        match route {
            Ok(route) => Header::of_route(route),
            Err(error) => Header::Error { error: error.clone() },
        }
    }

    /// The header of a route resolved on this host.
    fn of_route(route: &Route) -> Header {
        Header::Route {
            label: route.label.clone(),
            host: route.host.clone(),
            port: route.port,
            hash: route.arch.and_then(crate::devsbd::hash).map(Into::into),
            helper: route.process_container == route.container,
        }
    }

    /// The header as its line, newline included.
    pub fn line(&self) -> String {
        let json = serde_json::to_string(self).expect("a header serializes");
        format!("{MAGIC} {VERSION} {json}\n")
    }
}

/// Why no header was read.
#[derive(Debug)]
pub enum HeaderError {
    /// The stream ended first: the far side never got to write one (the
    /// link refused the stream, or it went away).
    Eof,
    /// [`HEADER_LIMIT`] bytes and no header.
    TooLong,
    /// A header line that doesn't parse (another version, garbage).
    Bad(String),
    Io(io::Error),
}

impl std::fmt::Display for HeaderError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HeaderError::Eof => write!(f, "the tunnel ended before its header"),
            HeaderError::TooLong => write!(f, "no tunnel header in the first {HEADER_LIMIT} bytes"),
            HeaderError::Bad(why) => write!(f, "{why}"),
            HeaderError::Io(e) => write!(f, "reading the tunnel header: {e}"),
        }
    }
}

/// Read the header from `r`, one byte at a time so nothing past its newline
/// is taken (the bridge's handshake follows). Lines without the magic are
/// skipped; the magic may follow noise on its line (a motd without a final
/// newline). Bounded by [`HEADER_LIMIT`].
pub fn read_header(r: &mut impl Read) -> Result<Header, HeaderError> {
    ssh::skip_lines(r, HEADER_LIMIT, &mut None, parse_line).map_err(|e| match e {
        SkipError::Eof => HeaderError::Eof,
        SkipError::TooLong => HeaderError::TooLong,
        SkipError::Io(e) => HeaderError::Io(e),
        SkipError::Refused(e) => e,
    })
}

/// One line: `Ok(None)` when it's noise.
fn parse_line(line: &[u8]) -> Result<Option<Header>, HeaderError> {
    let line = String::from_utf8_lossy(line);
    let Some(at) = line.find(&format!("{MAGIC} ")) else { return Ok(None) };
    let rest = line[at + MAGIC.len() + 1..].trim_end_matches('\r');
    let (version, json) = rest.split_once(' ').unwrap_or((rest, ""));
    if version != VERSION.to_string() {
        return Err(HeaderError::Bad(format!(
            "tunnel header version `{version}`, this devsandbox speaks {VERSION}: update devsandbox on the older side"
        )));
    }
    serde_json::from_str(json).map(Some).map_err(|e| HeaderError::Bad(format!("bad tunnel header: {e}")))
}

/// What a machine's `TUNNEL` stream is asked, its first line (`{"root",
/// "instance"?, "service"?, "port"}`, JSON, then `\n`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Request {
    /// The config root there (absolute).
    pub root: PathBuf,
    /// An instance, as `resolve_instance` takes a name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub instance: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub service: Option<String>,
    pub port: u16,
}

impl Request {
    /// The request as its line, newline included.
    pub fn line(&self) -> String {
        let json = serde_json::to_string(self).expect("a request serializes");
        format!("{json}\n")
    }

    /// One line (its `\n` or `\r\n` optional) back as a request.
    pub fn parse(line: &[u8]) -> Result<Request, String> {
        let line = line.strip_suffix(b"\n").unwrap_or(line);
        let line = line.strip_suffix(b"\r").unwrap_or(line);
        serde_json::from_slice(line).map_err(|e| format!("bad tunnel request: {e}"))
    }
}

/// The route to `port` of `instance` (a name, as `resolve_instance` takes
/// it, among the instances `load` gives) and/or `service` in the config at
/// `dir`: what a machine's `TUNNEL` stream writes the [`Header`] of
/// (`serve::fleet::tunnel`).
pub fn resolve(
    dir: PathBuf,
    instance: Option<String>,
    service: Option<String>,
    port: u16,
    load: LoadState,
) -> Result<Route, String> {
    if instance.is_none() && service.is_none() {
        return Err("name an instance or a service".into());
    }
    let key = match &instance {
        Some(name) => {
            let state = load()?;
            Some(super::resolve_instance_noninteractive(&state, name).map_err(|e| format!("{e:#}"))?)
        }
        None => None,
    };
    port::resolver_in(dir, key, service, port, load)()
}

/// How one spawn of a remote forward's bridge reaches its machine.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Via {
    /// A machine whose link sockets are in the socket dir `dir`: one
    /// `TUNNEL` stream through its link, else its route
    /// (`fleet::route::connect`), and send `request`.
    Fleet { dir: PathBuf, request: Request },
}

/// Says a remote forward's [`Via`]; called on every spawn.
pub type TunnelVia = Box<dyn Fn() -> Result<Via, String> + Send + Sync>;

/// The opener of a forward into `machine`'s instance or service: `via()`
/// (asked per spawn, so a removed registry entry is the bridge's error),
/// then open its `TUNNEL` stream, read the [`Header`], then run the bridge
/// over the rest of its bytes (`bridge::attach`; a stream that ends is a
/// bridge that's done, as a dead child is). The route shows as
/// `<machine>/<label>`; the far helper answers the listening-process lookup
/// when the header says the port lives in its container, else it stays
/// unknown (the engine's probe fallback is the caller's: `None` for remote).
pub fn remote_opener(machine: String, via: TunnelVia) -> Opener {
    Box::new(move |stop| match via()? {
        Via::Fleet { dir, request } => open_fleet(&machine, &dir, &request, stop),
    })
}

/// How a wait for the header ended.
enum Waited<T> {
    Got(T),
    Stopped,
    TimedOut,
    ReaderDied,
}

/// Wait up to [`HEADER_WAIT`] for the header reader's answer on `rx`,
/// checking `stop` every [`STOP_POLL`].
fn wait_header<T>(rx: &mpsc::Receiver<T>, stop: &AtomicBool) -> Waited<T> {
    let deadline = Instant::now() + HEADER_WAIT;
    loop {
        if stop.load(Ordering::Relaxed) {
            return Waited::Stopped;
        }
        let left = deadline.saturating_duration_since(Instant::now());
        if left.is_zero() {
            return Waited::TimedOut;
        }
        match rx.recv_timeout(STOP_POLL.min(left)) {
            Ok(got) => return Waited::Got(got),
            Err(mpsc::RecvTimeoutError::Timeout) => {}
            Err(mpsc::RecvTimeoutError::Disconnected) => return Waited::ReaderDied,
        }
    }
}

/// [`Via::Fleet`]: connect to `machine` from socket dir `dir`, send
/// `request`'s line, read the worker's [`Header`], then attach the bridge
/// to the stream itself.
fn open_fleet(machine: &str, dir: &Path, request: &Request, stop: &AtomicBool) -> Result<(Opened, Bridge), String> {
    let stream = crate::serve::fleet::route::connect(dir, machine, crate::devsbd::proto::channel::TUNNEL)
        .map_err(|e| format!("machine `{machine}`: {e}"))?;
    let clones = (stream.try_clone(), stream.try_clone());
    let (Ok(mut reader), Ok(writer)) = clones else {
        return Err("cannot clone the tunnel's socket".into());
    };
    (&stream)
        .write_all(request.line().as_bytes())
        .map_err(|e| format!("machine `{machine}`: cannot send the tunnel request: {e}"))?;
    let (tx, rx) = mpsc::channel();
    let started = std::thread::Builder::new().name("tunnel-header".into()).spawn(move || {
        let header = read_header(&mut reader);
        let _ = tx.send((header, reader));
    });
    if let Err(e) = started {
        return Err(format!("cannot start the tunnel's reader: {e}"));
    }
    let give_up = |why: String| {
        // Ends the reader's read.
        let _ = stream.shutdown(std::net::Shutdown::Both);
        Err(why)
    };
    let (header, reader) = match wait_header(&rx, stop) {
        Waited::Got(got) => got,
        Waited::Stopped => return give_up("stopped".into()),
        Waited::TimedOut => return give_up(format!("no answer from {machine}")),
        Waited::ReaderDied => return give_up("the tunnel's reader died".into()),
    };
    match header {
        Ok(Header::Route { label, host, port, hash, helper }) => {
            let label = format!("{machine}/{label}");
            let bridge = bridge::attach(stream, writer, reader, io::empty(), hash.as_deref().unwrap_or_default(), &label, Some(machine));
            let lookup = if helper { ProcessLookup::Helper { container: String::new() } } else { ProcessLookup::None };
            Ok((Opened { label, host, port, lookup }, bridge))
        }
        Ok(Header::Error { error }) => give_up(error),
        Err(e) => give_up(format!("{machine}: {e}")),
    }
}

#[cfg(test)]
mod tests {
    use std::net::{IpAddr, Ipv4Addr, TcpStream};
    use std::os::unix::net::UnixStream;
    use std::sync::Arc;

    use super::*;
    use crate::devsbd::forward::{Forward, ForwardSpec, ForwardState, HostPort};

    fn route_header() -> Header {
        Header::Route { label: "web:3000".into(), host: "127.0.0.1".into(), port: 3000, hash: Some("abc".into()), helper: true }
    }

    #[test]
    fn headers_round_trip() {
        for header in [
            route_header(),
            Header::Route { label: "db:5432 (via instance web)".into(), host: "db".into(), port: 5432, hash: None, helper: false },
            Header::Error { error: "no sandbox instance `web`".into() },
        ] {
            let line = header.line();
            assert!(line.starts_with("devsandbox-tunnel 1 {") && line.ends_with("}\n"), "{line}");
            assert_eq!(read_header(&mut line.as_bytes()).unwrap(), header);
        }
        assert_eq!(
            Header::Error { error: "x".into() }.line(),
            "devsandbox-tunnel 1 {\"error\":\"x\"}\n"
        );
    }

    #[test]
    fn the_route_header_says_where_the_port_lives() {
        let route = |process_container: &str| Route {
            container: "c".into(),
            arch: None,
            host: "db".into(),
            port: 5432,
            label: "db:5432".into(),
            process_container: process_container.into(),
        };
        let header = |helper| Header::Route { label: "db:5432".into(), host: "db".into(), port: 5432, hash: None, helper };
        assert_eq!(Header::of_route(&route("c")), header(true));
        assert_eq!(Header::of_route(&route("svc")), header(false));
    }

    #[test]
    fn noise_before_the_header_is_skipped_and_nothing_after_it_is_read() {
        let stream = format!("Welcome to box!\r\nLast login: today\n\nmotd without a newline{}BRIDGE", route_header().line());
        let mut r = stream.as_bytes();
        assert_eq!(read_header(&mut r).unwrap(), route_header());
        assert_eq!(r, b"BRIDGE", "the bridge's bytes stay unread");
        // CRLF on the header line itself.
        let crlf = route_header().line().replace('\n', "\r\n");
        assert_eq!(read_header(&mut crlf.as_bytes()).unwrap(), route_header());
    }

    #[test]
    fn a_reader_is_bounded_and_refuses_what_it_cant_read() {
        let noise = "x".repeat(HEADER_LIMIT + 1);
        assert!(matches!(read_header(&mut noise.as_bytes()), Err(HeaderError::TooLong)));
        let lines = "noise\n".repeat(HEADER_LIMIT / 6 + 1) + &route_header().line();
        assert!(matches!(read_header(&mut lines.as_bytes()), Err(HeaderError::TooLong)));
        let e = read_header(&mut &b"devsandbox-tunnel 2 {}\n"[..]).unwrap_err();
        assert!(matches!(&e, HeaderError::Bad(m) if m.contains("version `2`")), "{e}");
        let e = read_header(&mut &b"devsandbox-tunnel 1 {\"label\":3}\n"[..]).unwrap_err();
        assert!(matches!(&e, HeaderError::Bad(m) if m.starts_with("bad tunnel header")), "{e}");
        assert!(matches!(read_header(&mut &b"devsandbox-tunnel 1\n"[..]), Err(HeaderError::Bad(_))));
        assert!(matches!(read_header(&mut &b"motd\nno header yet"[..]), Err(HeaderError::Eof)));
        assert!(matches!(read_header(&mut &b""[..]), Err(HeaderError::Eof)));
    }

    #[test]
    fn a_failed_via_is_the_error() {
        let bad = remote_opener("box".into(), Box::new(|| Err("no machine `box`".into())));
        assert_eq!(bad(&AtomicBool::new(false)).err().as_deref(), Some("no machine `box`"));
    }

    /// The far side stays silent: the opener gives up once stopped.
    #[test]
    fn a_silent_tunnel_gives_up_when_stopped() {
        let (socket, worker) = fake_worker("silent", |s, _| {
            let mut sink = [0u8; 1];
            // Until the opener gives up and shuts its end.
            let _ = (&s).read(&mut sink);
        });
        let stop = Arc::new(AtomicBool::new(false));
        let setter = {
            let stop = Arc::clone(&stop);
            std::thread::spawn(move || {
                std::thread::sleep(Duration::from_millis(200));
                stop.store(true, Ordering::Relaxed);
            })
        };
        let started = Instant::now();
        let got = remote_opener("lap".into(), fleet(&socket, &web_request()))(&stop);
        assert_eq!(got.err().as_deref(), Some("stopped"));
        assert!(started.elapsed() < Duration::from_secs(2), "took {:?}", started.elapsed());
        setter.join().unwrap();
        worker.join().unwrap();
        let _ = std::fs::remove_dir_all(socket.parent().unwrap());
    }

    #[test]
    fn requests_round_trip_and_refuse_what_isnt_one() {
        let full = Request { root: "/f/cfg".into(), instance: Some("web".into()), service: Some("db".into()), port: 5432 };
        let bare = Request { root: "/f/cfg".into(), instance: None, service: Some("db".into()), port: 5432 };
        assert_eq!(bare.line(), "{\"root\":\"/f/cfg\",\"service\":\"db\",\"port\":5432}\n");
        for r in [full, bare] {
            assert_eq!(Request::parse(r.line().as_bytes()).unwrap(), r);
            assert_eq!(Request::parse(r.line().replace('\n', "\r\n").as_bytes()).unwrap(), r);
        }
        for bad in [&b"{\"root\":\"/f\"}\n"[..], b"{\"root\":\"/f\",\"port\":70000}", b"{\"root\":\"/f\",\"port\":1,\"x\":1}", b"hi"] {
            assert!(Request::parse(bad).unwrap_err().starts_with("bad tunnel request"), "{bad:?}");
        }
    }

    // ---- the fleet opener against a fake worker on a socket ----

    /// A socket in a fresh dir whose one connection `worker` takes, with
    /// the request line it read.
    fn fake_worker(
        tag: &str,
        worker: impl FnOnce(UnixStream, Request) + Send + 'static,
    ) -> (PathBuf, std::thread::JoinHandle<()>) {
        let dir = std::env::temp_dir().join(format!("dsv-tunnel-{tag}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let socket = dir.join("fleet-lap.sock");
        let listener = std::os::unix::net::UnixListener::bind(&socket).unwrap();
        let t = std::thread::spawn(move || {
            let (s, _) = listener.accept().unwrap();
            let mut byte = [0u8; 1];
            (&s).read_exact(&mut byte).unwrap();
            assert_eq!(byte[0], crate::devsbd::proto::channel::TUNNEL, "the connection names its channel");
            let mut line = Vec::new();
            while (&s).read(&mut byte).unwrap() == 1 && byte[0] != b'\n' {
                line.push(byte[0]);
            }
            worker(s, Request::parse(&line).unwrap());
        });
        (socket, t)
    }

    /// `socket`'s dir is the socket dir (`socket` is `fleet-lap.sock` there).
    fn fleet(socket: &Path, request: &Request) -> TunnelVia {
        let (dir, request) = (socket.parent().unwrap().to_path_buf(), request.clone());
        Box::new(move || Ok(Via::Fleet { dir: dir.clone(), request: request.clone() }))
    }

    fn web_request() -> Request {
        Request { root: "/worker/fleet/hub/cfg".into(), instance: Some("web".into()), service: None, port: 3000 }
    }

    /// The worker's route header, then its end of the bridge handshake; it
    /// reads the host's first frame (its caps) and goes away: the bridge
    /// came up, then is seen dead.
    #[test]
    fn a_fleet_tunnel_runs_the_bridge_on_its_stream_and_a_closed_stream_ends_it() {
        use crate::devsbd::proto::{self, caps};
        let (socket, worker) = fake_worker("route", |s, req| {
            assert_eq!(req, web_request());
            (&s).write_all(route_header().line().as_bytes()).unwrap();
            let (mut r, mut w) = (&s, &s);
            proto::handshake(&mut r, &mut w, "abc", caps::TCP_FORWARD).unwrap();
            assert!(matches!(proto::read_frame(&mut r), Ok(Some(proto::Frame::Caps(_)))));
        });
        let (opened, bridge) = remote_opener("lap".into(), fleet(&socket, &web_request()))(&AtomicBool::new(false)).unwrap();
        assert_eq!((opened.label.as_str(), opened.host.as_str(), opened.port), ("lap/web:3000", "127.0.0.1", 3000));
        assert_eq!(opened.lookup, ProcessLookup::Helper { container: String::new() });
        assert_eq!(bridge.outcome(Duration::from_secs(5)), Some(Ok(())));
        assert_eq!(bridge.peer_caps(), Some(caps::TCP_FORWARD));
        worker.join().unwrap();
        let deadline = Instant::now() + Duration::from_secs(5);
        while !bridge.is_done() {
            assert!(Instant::now() < deadline, "the closed stream ends the bridge");
            std::thread::sleep(Duration::from_millis(20));
        }
        let _ = std::fs::remove_dir_all(socket.parent().unwrap());
    }

    #[test]
    fn a_fleet_tunnels_refusals_are_the_error() {
        let refusal = Header::Error { error: "no instance `web` in /worker/fleet/hub/cfg".into() };
        let line = refusal.line();
        let (socket, worker) = fake_worker("refused", move |s, _| (&s).write_all(line.as_bytes()).unwrap());
        let got = remote_opener("lap".into(), fleet(&socket, &web_request()))(&AtomicBool::new(false));
        assert_eq!(got.err().as_deref(), Some("no instance `web` in /worker/fleet/hub/cfg"));
        worker.join().unwrap();

        // The link refused the stream (or the worker went away): no header.
        let (socket, worker) = fake_worker("closed", |_, _| {});
        let got = remote_opener("lap".into(), fleet(&socket, &web_request()))(&AtomicBool::new(false));
        assert_eq!(got.err().as_deref(), Some("lap: the tunnel ended before its header"));
        worker.join().unwrap();

        // No link: no socket.
        std::fs::remove_file(&socket).unwrap();
        let got = remote_opener("lap".into(), fleet(&socket, &web_request()))(&AtomicBool::new(false));
        let e = got.err().unwrap();
        assert!(e.starts_with("machine `lap`: no link to `lap` is up (") && e.contains("route-lap.sock"), "{e}");
        let _ = std::fs::remove_dir_all(socket.parent().unwrap());
    }

    /// Docker-gated: a forward through the remote opener over a fake
    /// machine's link socket, whose end of each stream writes a header,
    /// then runs the bridge into the container on the rest of it, as
    /// `serve::fleet::tunnel` does. The echo round-trips and the listening
    /// process comes from the helper over that stream.
    #[test_utils::docker_test(helper)]
    fn forwards_through_a_tunnel_with_docker() -> Result<(), &'static str> {
        use std::os::fd::OwnedFd;
        use std::process::{Command, Stdio};

        let ok = |cmd: &mut Command| matches!(cmd.output(), Ok(o) if o.status.success());
        let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
        let name = format!("devsandbox-fwd-tunnel-{stamp}");
        let serve = "busybox nc -lk -s 127.0.0.1 -p 8080 -e cat";
        let cleanup = || {
            let _ = crate::test_support::runtime_cmd().args(["rm", "-f", &name]).output();
        };
        crate::test_support::with_cleanup(cleanup, || {
            assert!(ok(crate::test_support::runtime_cmd().args(["run", "-d", "--name", &name, "alpine:3.20", "sh", "-c", serve])));
            let arch = crate::devsbd::install(&name, None).unwrap();
            let header = Header::Route {
                label: "web:8080".into(),
                host: "127.0.0.1".into(),
                port: 8080,
                hash: crate::devsbd::hash(arch).map(Into::into),
                helper: true,
            };
            let dir = std::env::temp_dir().join(format!("dsv-tunnel-docker-{stamp}"));
            std::fs::create_dir_all(&dir).unwrap();
            let socket = dir.join("fleet-box.sock");
            let listener = std::os::unix::net::UnixListener::bind(&socket).unwrap();
            let container = name.clone();
            // Every stream the forward opens (it may reopen one): the request
            // line, the header, then the bridge on the stream's fd.
            std::thread::spawn(move || {
                for s in listener.incoming().flatten() {
                    let mut byte = [0u8; 1];
                    while (&s).read(&mut byte).is_ok_and(|n| n == 1) && byte[0] != b'\n' {}
                    if (&s).write_all(header.line().as_bytes()).is_err() {
                        continue;
                    }
                    let (Ok(input), Ok(output)) = (s.try_clone(), s.try_clone()) else { continue };
                    let _ = bridge::bridge_command(&container)
                        .stdin(Stdio::from(OwnedFd::from(input)))
                        .stdout(Stdio::from(OwnedFd::from(output)))
                        .spawn();
                }
            });
            let via = Via::Fleet { dir: dir.clone(), request: web_request() };
            let forward = Forward::start(ForwardSpec {
                bind: IpAddr::V4(Ipv4Addr::LOCALHOST),
                host_port: HostPort::Prefer(0),
                open: remote_opener("box".into(), Box::new(move || Ok(via.clone()))),
                probe: Box::new(|_, _| None),
            })
            .unwrap();
            let deadline = Instant::now() + Duration::from_secs(15);
            while forward.status().state != ForwardState::Active && Instant::now() < deadline {
                std::thread::sleep(Duration::from_millis(50));
            }
            assert_eq!(forward.status().state, ForwardState::Active);
            assert_eq!(forward.status().route_label, "box/web:8080");
            let addr = forward.status().local_addr;
            let ping = || -> io::Result<bool> {
                let mut c = TcpStream::connect(addr)?;
                c.set_read_timeout(Some(Duration::from_secs(5)))?;
                c.write_all(b"ping\n")?;
                let mut buf = [0u8; 5];
                c.read_exact(&mut buf)?;
                Ok(&buf == b"ping\n")
            };
            let mut round_tripped = false;
            for _ in 0..40 {
                if matches!(ping(), Ok(true)) {
                    round_tripped = true;
                    break;
                }
                std::thread::sleep(Duration::from_millis(200));
            }
            assert!(round_tripped, "echo did not round-trip");
            // The first probe may beat `nc`'s bind; the next is 10 s later.
            let deadline = Instant::now() + Duration::from_secs(15);
            let found = loop {
                if let Some(p) = forward.status().process {
                    break p;
                }
                if Instant::now() >= deadline {
                    return Err("listening process never found");
                }
                std::thread::sleep(Duration::from_millis(100));
            };
            assert!(found.contains(" (pid "), "{found}");
            drop(forward);
            let _ = std::fs::remove_dir_all(&dir);
            Ok(())
        })
    }
}