Skip to main content

isothrum_runner/graphical/
tunnel.rs

1//! An SSH tunnel to a machine's console that answers only on the run's own networks (a Windows
2//! VM's Remote Desktop behind the module's Linux machine): `ssh -N -L
3//! 127.0.0.1:<local>:<host>:<port>` to the machine it goes through, with the run's key and the
4//! run's pinned host keys ([`crate::ssh`]). It listens on this computer's loopback only, at a
5//! free port no run holds, and lives as long as its [`Tunnel`]: dropping it ends its `ssh`. Its
6//! process is recorded in the run's tool ledger while it lives, so the next operation after a
7//! crash of the process holding it ends it, and so does a `down` from any process.
8//!
9//! Not the [`crate::ProcessRunner`] port: a tunnel is a pipe for as long as a viewer is
10//! connected, not a tool run to its end.
11
12use std::net::{IpAddr, Ipv4Addr, SocketAddr};
13use std::path::{Path, PathBuf};
14use std::time::Duration;
15
16use super::no_console;
17use crate::Result;
18use crate::error::Error;
19use crate::name::RunName;
20use crate::process::ProcessSpec;
21use crate::process::ledger::Recorded;
22use crate::project::platform::Protocol;
23use crate::runner::Runner;
24use crate::ssh::Login;
25
26/// Where a tunnel listens: this computer's loopback.
27const LOOPBACK: IpAddr = IpAddr::V4(Ipv4Addr::LOCALHOST);
28
29/// How long the tunnel may take to listen.
30const OPENING: Duration = Duration::from_secs(20);
31
32/// How long a tunnel that didn't open is given to exit, then to finish writing why.
33const SAYING_WHY: Duration = Duration::from_secs(2);
34
35/// The step id a missing `ssh` is reported under.
36const STEP: &str = "console";
37
38/// Where a tunnel goes, as a driver reads it from its tool.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub(crate) struct To {
41    /// The machine it goes through, and the user there.
42    pub(crate) via: Login,
43    /// The console's machine's address, as `via` reaches it.
44    pub(crate) host: String,
45    /// The console's port there.
46    pub(crate) port: u16,
47    /// The private key that signs in to `via` (the run's `ssh_private_key_file`); none: the
48    /// runner's own.
49    pub(crate) key: Option<PathBuf>,
50    /// A `known_hosts` file of `via`'s keys, only read; none: pinned in the run's own.
51    pub(crate) known_hosts: Option<PathBuf>,
52}
53
54/// What a tunnel is for, which its errors name.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub(crate) enum Purpose<'a> {
57    /// A machine's console: its errors are `no_console`.
58    Console(&'a str),
59    /// A service endpoint the deployment publishes: its errors are `tool_failed`.
60    Endpoint(&'a str),
61}
62
63impl Purpose<'_> {
64    /// Why a tunnel for it couldn't open, as its error.
65    pub(crate) fn refused(self, why: impl Into<String>) -> Error {
66        match self {
67            Purpose::Console(machine) => no_console(machine, why),
68            Purpose::Endpoint(name) => Error::ToolFailed {
69                step: "endpoint".to_owned(),
70                reason: format!("`{name}`: {}", why.into()),
71            },
72        }
73    }
74}
75
76/// An open tunnel to a machine's console: where it listens, and its `ssh`, ended when it is
77/// dropped (and its ledger entry removed).
78#[derive(Debug)]
79pub struct Tunnel {
80    /// Where it listens.
81    local: SocketAddr,
82    /// `user@host` it goes through.
83    via: String,
84    /// Its `ssh`, killed when the tunnel is dropped.
85    ssh: tokio::process::Child,
86    /// The reader of its `ssh`'s standard error, owned so it ends with the tunnel.
87    drain: Option<tokio::task::JoinHandle<()>>,
88    /// Its entry in the run's tool ledger, removed after its `ssh` is ended.
89    _recorded: Option<Recorded>,
90}
91
92impl Drop for Tunnel {
93    fn drop(&mut self) {
94        // `kill_on_drop` too: the tunnel ends with its holder, whatever drops it.
95        if let Err(e) = self.ssh.start_kill() {
96            tracing::debug!(error = %e, "a console's tunnel had ended already");
97        }
98        if let Some(drain) = self.drain.take() {
99            drain.abort();
100        }
101    }
102}
103
104impl Tunnel {
105    /// Where it listens: a port of this computer's loopback.
106    #[must_use]
107    pub fn local(&self) -> SocketAddr {
108        self.local
109    }
110
111    /// Whether its `ssh` still runs (it listens).
112    pub(crate) fn runs(&mut self) -> bool {
113        matches!(self.ssh.try_wait(), Ok(None))
114    }
115
116    /// The machine it goes through, as `user@host`.
117    #[must_use]
118    pub fn via(&self) -> &str {
119        &self.via
120    }
121
122    /// Waits for its `ssh` to end (the connection dropped, the machine it goes through gone, a
123    /// `down`), and says how it ended: the tunnel no longer listens. A viewer waits on it beside
124    /// its own end.
125    pub async fn closed(&mut self) -> String {
126        match self.ssh.wait().await {
127            Ok(status) => match status.code() {
128                Some(code) => format!("its ssh exited with code {code}"),
129                None => "its ssh was ended by a signal".to_owned(),
130            },
131            Err(e) => format!("its ssh couldn't be waited for: {e}"),
132        }
133    }
134
135    /// The last line `ssh` wrote to its standard error, once it is stopped: why a tunnel that
136    /// didn't open closed (a host key that changed, a key refused). None when it said nothing.
137    async fn why_closed(&mut self) -> Option<String> {
138        use tokio::io::AsyncReadExt;
139        // An `ssh` that failed has exited, or is about to: it is given a moment to say why.
140        if tokio::time::timeout(SAYING_WHY, self.ssh.wait()).await.is_err()
141            && let Err(e) = self.ssh.start_kill()
142        {
143            tracing::debug!(error = %e, "a console's tunnel couldn't be stopped");
144        }
145        let mut stderr = self.ssh.stderr.take()?;
146        let mut said = Vec::new();
147        if let Ok(Err(e)) = tokio::time::timeout(SAYING_WHY, stderr.read_to_end(&mut said)).await {
148            tracing::debug!(error = %e, "a console's tunnel's standard error couldn't be read");
149        }
150        String::from_utf8_lossy(&said)
151            .lines()
152            .map(str::trim)
153            .rfind(|l| !l.is_empty())
154            .map(str::to_owned)
155    }
156
157    /// Reads what `ssh` writes to its standard error while the tunnel is open, into the trace, so
158    /// a full pipe never stalls it.
159    fn drain(&mut self) {
160        let Some(stderr) = self.ssh.stderr.take() else { return };
161        self.drain = Some(tokio::spawn(async move {
162            use tokio::io::AsyncBufReadExt;
163            let mut lines = tokio::io::BufReader::new(stderr).lines();
164            while let Ok(Some(line)) = lines.next_line().await {
165                tracing::debug!(%line, "a console's tunnel's ssh said");
166            }
167        }));
168    }
169}
170
171/// `ssh`'s process for a tunnel to `machine`'s console from loopback port `local` to `to`, signing
172/// in with `key`, the run's state folder `state_dir` holding its pinned host keys.
173fn ssh_spec(purpose: Purpose<'_>, to: &To, key: &Path, state_dir: &Path, local: u16) -> Result<ProcessSpec> {
174    let address = |h: &str| !h.is_empty() && !h.starts_with('-') && h.chars().all(|c| c.is_ascii_alphanumeric() || ".:-".contains(c));
175    if !address(&to.host) {
176        return Err(purpose.refused(format!("its address `{}` isn't one a tunnel goes to", to.host.escape_debug())));
177    }
178    let forward = format!("{LOOPBACK}:{local}:{}:{}", bracketed(&to.host), to.port);
179    let mut args = crate::ssh::options(key, state_dir, crate::ssh::First::given(to.known_hosts.as_deref()))?;
180    args.extend(["-N", "-o", "ExitOnForwardFailure=yes", "-L", &forward].map(String::from));
181    args.push(to.via.target());
182    let mut spec = ProcessSpec::new("ssh", args);
183    spec.cwd = Some(state_dir.to_path_buf());
184    Ok(spec)
185}
186
187/// An IPv6 address in brackets, as `-L` takes it.
188fn bracketed(host: &str) -> String {
189    if host.contains(':') { format!("[{host}]") } else { host.to_owned() }
190}
191
192/// Opens a tunnel to `to` for run `run`'s `machine`'s console: `via`'s host keys readied
193/// ([`crate::ssh::ready`]: pinned the first time, unless `to` gives them), a free loopback port no run holds, `ssh` started and recorded in
194/// the run's tool ledger, and the port answering within [`OPENING`]; when it doesn't, why, in
195/// `ssh`'s own words when it said any.
196pub(crate) async fn open(runner: &Runner, run: &RunName, state_dir: &Path, purpose: Purpose<'_>, to: &To) -> Result<Tunnel> {
197    let config = &runner.config;
198    crate::ssh::ready(
199        config.processes.as_ref(),
200        state_dir,
201        &to.via.host,
202        crate::ssh::First::given(to.known_hosts.as_deref()),
203    )
204    .await?;
205    let key = to.key.clone().unwrap_or_else(|| crate::ssh::key_path(&config.home));
206    let free = runner
207        .pick_unreserved(run, Protocol::Tcp)
208        .map_err(Error::io("a tcp port on 127.0.0.1", "bound"))?
209        .ok_or_else(|| purpose.refused("no free port on this computer's loopback for its tunnel"))?;
210    let local = free.port.get();
211    // Freed for `ssh` to bind it.
212    drop(free);
213    let spec = ssh_spec(purpose, to, &key, state_dir, local)?;
214    let ledger = state_dir.join(crate::process::ledger::DIR);
215    let mut tunnel = started(purpose, &spec, SocketAddr::new(LOOPBACK, local), &to.via.target(), &ledger)?;
216    let probe = || config.ports.reachable(LOOPBACK_TEXT, local, PROBE);
217    if !answers(&mut tunnel, probe, OPENING).await {
218        let because = tunnel.why_closed().await.map_or_else(String::new, |line| format!(": ssh said `{line}`"));
219        return Err(purpose.refused(format!(
220            "its tunnel through {} didn't open (SSH refused, or {}:{} doesn't answer from there){because}",
221            tunnel.via, to.host, to.port
222        )));
223    }
224    tunnel.drain();
225    Ok(tunnel)
226}
227
228/// How long one probe of a tunnel's port may take.
229const PROBE: Duration = Duration::from_secs(2);
230
231/// How often a tunnel's port is probed while its `ssh` opens it.
232const POLL: Duration = Duration::from_millis(200);
233
234/// The loopback, as text a probe connects to.
235const LOOPBACK_TEXT: &str = "127.0.0.1";
236
237/// Whether `tunnel`'s port answers `probe` within `within`, probed again while its `ssh` runs:
238/// `ssh` listens only once it has signed in through the machine it goes through, which takes a
239/// moment. A single probe, made at once, found nothing listening yet and gave a tunnel up that was
240/// opening. False as soon as its `ssh` ended.
241async fn answers<'a>(tunnel: &mut Tunnel, probe: impl Fn() -> crate::BoxFuture<'a, bool>, within: Duration) -> bool {
242    let deadline = tokio::time::Instant::now() + within;
243    loop {
244        if probe().await {
245            return true;
246        }
247        if !tunnel.runs() || tokio::time::Instant::now() >= deadline {
248            return false;
249        }
250        tokio::time::sleep(POLL).await;
251    }
252}
253
254/// [`start`] for `machine`'s console: a program that isn't installed is `tool_missing`, another
255/// failure to start it `no_console` saying why.
256fn started(purpose: Purpose<'_>, spec: &ProcessSpec, local: SocketAddr, via: &str, ledger: &Path) -> Result<Tunnel> {
257    start(spec, local, via, ledger).map_err(|e| match e.kind() {
258        std::io::ErrorKind::NotFound => Error::ToolMissing {
259            step: STEP.to_owned(),
260            tool: spec.program.clone(),
261        },
262        _ => purpose.refused(format!("its tunnel's `{}` didn't start: {e}", spec.program)),
263    })
264}
265
266/// Starts `spec` as a tunnel listening at `local` through `via`, in a process group of its own,
267/// recorded in `ledger` and stopped when the tunnel is dropped; its standard error kept for
268/// [`Tunnel::why_closed`].
269#[expect(
270    clippy::disallowed_methods,
271    reason = "the SSH tunnel is a long-lived child its `Tunnel` owns and stops, not a call the process module waits on"
272)]
273fn start(spec: &ProcessSpec, local: SocketAddr, via: &str, ledger: &Path) -> std::io::Result<Tunnel> {
274    let mut command = tokio::process::Command::new(&spec.program);
275    command
276        .args(&spec.args)
277        .envs(spec.env.iter().map(|(k, v)| (k, v)))
278        .stdin(std::process::Stdio::null())
279        .stdout(std::process::Stdio::null())
280        .stderr(std::process::Stdio::piped())
281        .kill_on_drop(true);
282    if let Some(cwd) = &spec.cwd {
283        command.current_dir(cwd);
284    }
285    own_group(&mut command);
286    let ssh = command.spawn()?;
287    let recorded = ssh.id().and_then(|pid| Recorded::tunnel(ledger, pid));
288    Ok(Tunnel {
289        local,
290        via: via.to_owned(),
291        ssh,
292        drain: None,
293        _recorded: recorded,
294    })
295}
296
297/// The tunnel's `ssh` leads a process group of its own (what the ledger ends), and gets no
298/// signal meant for the viewer's terminal (its Ctrl-C ends the viewer, which ends the tunnel).
299#[cfg(unix)]
300fn own_group(command: &mut tokio::process::Command) {
301    command.process_group(0);
302}
303
304/// No console window for the tunnel's `ssh` on Windows, as for every tool the runner starts: from
305/// a GUI app it would get one of its own, open as long as the tunnel, and closing it ends `ssh`.
306#[cfg(windows)]
307fn own_group(command: &mut tokio::process::Command) {
308    use windows::Win32::System::Threading::CREATE_NO_WINDOW;
309    command.creation_flags(CREATE_NO_WINDOW.0);
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315
316    fn to(host: &str) -> To {
317        To {
318            via: Login::new("admin", "203.0.113.7").unwrap(),
319            host: host.to_owned(),
320            port: 3389,
321            key: None,
322            known_hosts: None,
323        }
324    }
325
326    #[test]
327    fn the_forward_listens_on_the_loopback_and_checks_the_pinned_keys() {
328        use crate::process::fake::CallView as _;
329        let dir = tempfile::tempdir().unwrap();
330        let spec = ssh_spec(Purpose::Console("dc"), &to("10.9.0.20"), Path::new("/k/id"), dir.path(), 40000).unwrap();
331        assert_eq!(spec.flag("-L"), Some("127.0.0.1:40000:10.9.0.20:3389"), "{:?}", spec.args);
332        for never_waits in ["StrictHostKeyChecking=yes", "BatchMode=yes", "ConnectTimeout=10"] {
333            assert!(spec.has_run(&["-o", never_waits]), "{never_waits}: {:?}", spec.args);
334        }
335        assert!(!spec.args.iter().any(|a| a.ends_with("=accept-new")), "{:?}", spec.args);
336        assert_eq!((spec.flag("-F"), spec.flag("-i")), (Some("none"), Some("/k/id")), "{:?}", spec.args);
337        assert_eq!(spec.args.last().map(String::as_str), Some("admin@203.0.113.7"));
338        let refused = ssh_spec(Purpose::Console("dc"), &to("-oProxyCommand=x"), Path::new("/k"), dir.path(), 1).unwrap_err();
339        assert_eq!(refused.code(), crate::ErrorCode::NoConsole, "an option, never an address: {refused}");
340    }
341
342    #[test]
343    fn an_ipv6_host_is_bracketed_in_the_forward() {
344        assert_eq!(bracketed("fd00::5"), "[fd00::5]");
345        assert_eq!(bracketed("10.0.1.5"), "10.0.1.5");
346    }
347
348    #[test]
349    fn a_missing_ssh_is_a_tool_missing() {
350        let dir = tempfile::tempdir().unwrap();
351        let spec = ProcessSpec::new("isothrum-no-such-ssh", ["-N"]);
352        let err = started(Purpose::Console("dc"), &spec, "127.0.0.1:1".parse().unwrap(), "a@b", dir.path()).unwrap_err();
353        assert_eq!(err.code(), crate::ErrorCode::ToolMissing, "{err}");
354    }
355
356    /// A tunnel of `script` run by `sh` (a stand-in `ssh`), recorded in a ledger under `dir`.
357    #[cfg(unix)]
358    fn stand_in(script: &str, dir: &Path) -> Tunnel {
359        let spec = ProcessSpec::new("sh", ["-c", script]);
360        start(&spec, "127.0.0.1:1".parse().unwrap(), "admin@203.0.113.7", dir).unwrap()
361    }
362
363    /// Regression: `ssh`'s standard error went to null, so a tunnel that didn't open never said
364    /// why (a host key that changed, a key refused).
365    #[cfg(unix)]
366    #[tokio::test]
367    async fn a_tunnel_that_closed_says_the_last_line_its_ssh_said() {
368        let dir = tempfile::tempdir().unwrap();
369        let mut refused = stand_in("echo 'debug1: x' >&2; echo 'Host key verification failed.' >&2; exit 255", dir.path());
370        assert_eq!(refused.why_closed().await.as_deref(), Some("Host key verification failed."));
371        assert_eq!(stand_in("exit 255", dir.path()).why_closed().await, None, "nothing said, nothing made up");
372    }
373
374    /// Regression (#126): nothing said when a tunnel's `ssh` ended, so `isothrum screen` kept
375    /// saying a dead tunnel was open.
376    #[cfg(unix)]
377    #[tokio::test]
378    async fn a_tunnel_says_when_its_ssh_ended() {
379        let dir = tempfile::tempdir().unwrap();
380        let mut tunnel = stand_in("exit 255", dir.path());
381        tunnel.drain();
382        let said = tokio::time::timeout(Duration::from_secs(10), tunnel.closed()).await.expect("seen closing");
383        assert_eq!(said, "its ssh exited with code 255");
384    }
385
386    /// Regression (a real run through a jump host): the port was probed once, at once, before
387    /// `ssh` had signed in and listened, and the tunnel was given up while it opened.
388    #[cfg(unix)]
389    #[tokio::test]
390    async fn a_tunnel_is_waited_for_while_its_ssh_opens_it_and_given_up_once_it_ended() {
391        let dir = tempfile::tempdir().unwrap();
392        let mut opening = stand_in("sleep 30", dir.path());
393        let probes = std::sync::atomic::AtomicUsize::new(0);
394        let third = || -> crate::BoxFuture<'_, bool> {
395            let n = probes.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
396            Box::pin(async move { n >= 2 })
397        };
398        assert!(answers(&mut opening, third, Duration::from_secs(10)).await, "answering at the third probe");
399        let mut ended = stand_in("exit 255", dir.path());
400        tokio::time::sleep(Duration::from_millis(300)).await;
401        let never = || -> crate::BoxFuture<'_, bool> { Box::pin(async { false }) };
402        let started = std::time::Instant::now();
403        assert!(!answers(&mut ended, never, Duration::from_secs(10)).await);
404        assert!(started.elapsed() < Duration::from_secs(5), "given up once its ssh ended");
405    }
406}