Skip to main content

aither_sandbox/
shell_session.rs

1use std::{collections::HashSet, future::Future, pin::Pin, sync::Arc};
2
3use async_channel::{Receiver, Sender};
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6
7/// Outcome of a container execution request.
8#[derive(Debug)]
9pub enum ContainerExecOutcome {
10    /// The command ran to completion; carries its exit status and output.
11    Completed(std::process::Output),
12    /// The command was terminated before it finished.
13    Killed,
14}
15
16/// Trait for executing commands inside a container.
17///
18/// Implementations provide the bridge between aither-sandbox and a specific
19/// container runtime (e.g., Docker via bollard). The framework defines this trait;
20/// the application (may) provides the implementation.
21pub trait ContainerExec: Send + Sync {
22    /// Execute a terminal command payload inside the container, returning stdout/stderr and exit code.
23    ///
24    /// Implementations should send a human-readable message to
25    /// `stdin_blocked_notice` when they detect the process is blocked on stdin
26    /// (for example via `/proc/<pid>/syscall`), allowing callers to auto-promote
27    /// foreground execution into background mode.
28    fn exec(
29        &self,
30        container_id: &str,
31        script: &str,
32        working_dir: &str,
33        kill_rx: Receiver<()>,
34        stdin_rx: Receiver<Vec<u8>>,
35        stdin_blocked_notice: Option<Sender<String>>,
36    ) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send;
37}
38
39/// Object-safe twin of [`ContainerExec`], used only through
40/// [`AnyContainerExec`].
41pub trait ContainerExecImpl: Send + Sync {
42    /// Execute a command inside a container through a boxed future.
43    fn exec_boxed<'a>(
44        &'a self,
45        container_id: &'a str,
46        script: &'a str,
47        working_dir: &'a str,
48        kill_rx: Receiver<()>,
49        stdin_rx: Receiver<Vec<u8>>,
50        stdin_blocked_notice: Option<Sender<String>>,
51    ) -> Pin<Box<dyn Future<Output = Result<ContainerExecOutcome, String>> + Send + 'a>>;
52}
53
54/// Backend-agnostic container executor handle.
55///
56/// This wraps any [`ContainerExec`] implementation into a cloneable concrete
57/// type that can be passed around without exposing runtime-specific concrete
58/// executor types.
59#[derive(Clone)]
60pub struct AnyContainerExec {
61    inner: Arc<dyn ContainerExecImpl>,
62}
63
64impl std::fmt::Debug for AnyContainerExec {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        f.debug_struct("AnyContainerExec").finish_non_exhaustive()
67    }
68}
69
70impl AnyContainerExec {
71    /// Creates a new handle from a concrete container executor implementation.
72    #[must_use]
73    pub fn new<T>(inner: Arc<T>) -> Self
74    where
75        T: ContainerExec + 'static,
76    {
77        Self { inner }
78    }
79}
80
81impl ContainerExec for AnyContainerExec {
82    fn exec(
83        &self,
84        container_id: &str,
85        script: &str,
86        working_dir: &str,
87        kill_rx: Receiver<()>,
88        stdin_rx: Receiver<Vec<u8>>,
89        stdin_blocked_notice: Option<Sender<String>>,
90    ) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send {
91        let inner = Arc::clone(&self.inner);
92        let container_id = container_id.to_string();
93        let script = script.to_string();
94        let working_dir = working_dir.to_string();
95
96        async move {
97            inner
98                .exec_boxed(
99                    &container_id,
100                    &script,
101                    &working_dir,
102                    kill_rx,
103                    stdin_rx,
104                    stdin_blocked_notice,
105                )
106                .await
107        }
108    }
109}
110
111/// An address the container IPC bridge may listen on.
112///
113/// The bridge executes host IPC commands for whoever connects, so it is bound
114/// only to an address the container network alone reaches — never the
115/// unspecified (`0.0.0.0`, `::`) address, which would expose it on every
116/// interface including the LAN, nor a multicast address, which cannot serve a
117/// listener. Docker Desktop and `OrbStack` forward `host.docker.internal` to the
118/// host's loopback, so the bridge binds `127.0.0.1`; native Linux Docker
119/// routes the name to the container network's gateway the host owns (`docker0`
120/// or the docker `bridge` network gateway, e.g. `172.17.0.1`), so the bridge
121/// binds that address.
122#[derive(Clone, Copy, Debug, PartialEq, Eq)]
123pub struct BridgeAddress(std::net::IpAddr);
124
125/// Why an address cannot bind the container IPC bridge.
126#[derive(Debug, thiserror::Error)]
127pub enum BridgeAddressError {
128    /// The unspecified wildcard address would listen on every interface.
129    #[error("the unspecified address {0} would expose the container IPC bridge on every interface")]
130    Unspecified(std::net::IpAddr),
131    /// A multicast address cannot serve a listener.
132    #[error("the multicast address {0} cannot bind the container IPC bridge")]
133    Multicast(std::net::IpAddr),
134}
135
136impl TryFrom<std::net::IpAddr> for BridgeAddress {
137    type Error = BridgeAddressError;
138
139    fn try_from(address: std::net::IpAddr) -> Result<Self, Self::Error> {
140        if address.is_unspecified() {
141            return Err(BridgeAddressError::Unspecified(address));
142        }
143        if address.is_multicast() {
144            return Err(BridgeAddressError::Multicast(address));
145        }
146        Ok(Self(address))
147    }
148}
149
150impl BridgeAddress {
151    /// The address the bridge listens on.
152    #[must_use]
153    pub const fn ip(&self) -> std::net::IpAddr {
154        self.0
155    }
156}
157
158/// How a container reaches the host's IPC bridge.
159///
160/// `host` is the name the container dials (`host.docker.internal` on Docker —
161/// made resolvable through `--add-host=host.docker.internal:host-gateway` —
162/// `host.containers.internal` on Podman), and `bind` is the host address the
163/// bridge listens on: `127.0.0.1` on Docker Desktop and `OrbStack`, which
164/// forward the name to host loopback, or the container network's gateway
165/// address on native Linux Docker. The two belong to the same route, and only
166/// the caller — which knows the container runtime — can pair them correctly.
167#[derive(Clone, Debug)]
168pub struct ContainerIpcRoute {
169    host: String,
170    bind: BridgeAddress,
171}
172
173impl ContainerIpcRoute {
174    /// Creates the route a container uses to reach the host's IPC bridge.
175    ///
176    /// # Panics
177    /// Panics if `host` is empty after trimming.
178    #[must_use]
179    pub fn new(host: impl Into<String>, bind: BridgeAddress) -> Self {
180        let host = host.into();
181        assert!(
182            !host.trim().is_empty(),
183            "container IPC route requires a non-empty host"
184        );
185        Self { host, bind }
186    }
187
188    /// The name the container dials to reach the bridge.
189    #[must_use]
190    pub fn host(&self) -> &str {
191        &self.host
192    }
193
194    /// The host address the bridge listens on.
195    #[must_use]
196    pub const fn bind(&self) -> BridgeAddress {
197        self.bind
198    }
199}
200
201/// Container runtime session metadata.
202#[derive(Clone)]
203pub struct ContainerShellRuntime {
204    exec: Arc<dyn ContainerExecImpl>,
205    container_id: String,
206    ipc_route: ContainerIpcRoute,
207}
208
209impl std::fmt::Debug for ContainerShellRuntime {
210    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
211        f.debug_struct("ContainerShellRuntime")
212            .field("container_id", &self.container_id)
213            .field("ipc_route", &self.ipc_route)
214            .finish_non_exhaustive()
215    }
216}
217
218impl ContainerShellRuntime {
219    /// Creates a container shell runtime.
220    ///
221    /// # Panics
222    /// Panics if `container_id` is empty after trimming.
223    #[must_use]
224    pub fn new(
225        container_id: impl Into<String>,
226        ipc_route: ContainerIpcRoute,
227        exec: AnyContainerExec,
228    ) -> Self {
229        let container_id = container_id.into();
230        assert!(
231            !container_id.trim().is_empty(),
232            "container runtime requires a non-empty container_id"
233        );
234        Self {
235            exec: exec.inner,
236            container_id,
237            ipc_route,
238        }
239    }
240
241    #[must_use]
242    /// Returns the container id.
243    pub fn container_id(&self) -> &str {
244        &self.container_id
245    }
246
247    /// Returns the route the container uses to reach the host's IPC bridge.
248    #[must_use]
249    pub const fn ipc_route(&self) -> &ContainerIpcRoute {
250        &self.ipc_route
251    }
252
253    pub(crate) fn exec(&self) -> Arc<dyn ContainerExecImpl> {
254        Arc::clone(&self.exec)
255    }
256}
257
258impl<T: ContainerExec> ContainerExecImpl for T {
259    fn exec_boxed<'a>(
260        &'a self,
261        container_id: &'a str,
262        script: &'a str,
263        working_dir: &'a str,
264        kill_rx: Receiver<()>,
265        stdin_rx: Receiver<Vec<u8>>,
266        stdin_blocked_notice: Option<Sender<String>>,
267    ) -> Pin<Box<dyn Future<Output = Result<ContainerExecOutcome, String>> + Send + 'a>> {
268        Box::pin(self.exec(
269            container_id,
270            script,
271            working_dir,
272            kill_rx,
273            stdin_rx,
274            stdin_blocked_notice,
275        ))
276    }
277}
278
279/// Where a shell command is executed.
280#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
281#[serde(rename_all = "lowercase")]
282pub enum ShellBackend {
283    /// On this machine, inside the local sandbox.
284    Local,
285    /// Inside a container.
286    Container,
287    /// On a remote host over SSH.
288    Ssh,
289}
290
291/// A named SSH destination the agent may run commands on.
292#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
293pub struct SshServer {
294    /// Short name the agent uses to select this server.
295    pub name: String,
296    /// SSH target, as passed to `ssh` (for example `user@host`).
297    pub target: String,
298}
299
300impl SshServer {
301    /// The name used to address this server.
302    #[must_use]
303    pub fn id(&self) -> &str {
304        &self.name
305    }
306}
307
308/// How the sandbox runtime is available on a remote host.
309#[derive(Debug, Clone)]
310pub enum SshRuntimeProfile {
311    /// The `heel` sandbox binary is installed at the given path.
312    Heel {
313        /// Absolute path to the `heel` binary on the remote host.
314        binary: String,
315    },
316}
317
318/// Which shell backends are usable in the current deployment.
319///
320/// Reported to the model so it does not offer a backend that is not configured.
321#[derive(Debug, Clone, Serialize)]
322pub struct ShellRuntimeAvailability {
323    /// Whether local execution is available. Always true in practice.
324    pub local: bool,
325    /// Whether a container runtime has been wired up.
326    pub container: bool,
327    /// Whether any SSH servers are registered.
328    pub ssh: bool,
329}
330
331impl Default for ShellRuntimeAvailability {
332    fn default() -> Self {
333        Self {
334            local: true,
335            container: false,
336            ssh: false,
337        }
338    }
339}
340
341/// Approves remote actions before the sandbox performs them.
342///
343/// Connecting to a host and installing software on it are both decisions a user
344/// should make, so they are routed through this trait rather than assumed.
345pub trait SshSessionAuthorizer: Send + Sync {
346    /// Asks whether the agent may open an SSH connection to `target`.
347    fn authorize_connect(
348        &self,
349        target: &str,
350    ) -> impl Future<Output = Result<bool, SshAuthorizationError>> + Send;
351
352    /// Asks whether the harness may prepare runtime components on `target`.
353    ///
354    /// `details` describes the remote host and components so the user can judge the request.
355    fn authorize_runtime_install(
356        &self,
357        target: &str,
358        details: &str,
359    ) -> impl Future<Output = Result<bool, SshAuthorizationError>> + Send;
360}
361
362trait SshSessionAuthorizerImpl: Send + Sync {
363    fn connect<'a>(
364        &'a self,
365        target: &'a str,
366    ) -> Pin<Box<dyn Future<Output = Result<bool, SshAuthorizationError>> + Send + 'a>>;
367    fn install<'a>(
368        &'a self,
369        target: &'a str,
370        details: &'a str,
371    ) -> Pin<Box<dyn Future<Output = Result<bool, SshAuthorizationError>> + Send + 'a>>;
372}
373
374impl<T: SshSessionAuthorizer> SshSessionAuthorizerImpl for T {
375    fn connect<'a>(
376        &'a self,
377        target: &'a str,
378    ) -> Pin<Box<dyn Future<Output = Result<bool, SshAuthorizationError>> + Send + 'a>> {
379        Box::pin(self.authorize_connect(target))
380    }
381    fn install<'a>(
382        &'a self,
383        target: &'a str,
384        details: &'a str,
385    ) -> Pin<Box<dyn Future<Output = Result<bool, SshAuthorizationError>> + Send + 'a>> {
386        Box::pin(self.authorize_runtime_install(target, details))
387    }
388}
389
390/// Shared authorizer with boxing confined to the private implementation boundary.
391#[derive(Clone)]
392pub struct AnySshSessionAuthorizer {
393    inner: Arc<dyn SshSessionAuthorizerImpl>,
394}
395
396impl std::fmt::Debug for AnySshSessionAuthorizer {
397    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
398        formatter
399            .debug_struct("AnySshSessionAuthorizer")
400            .finish_non_exhaustive()
401    }
402}
403
404impl AnySshSessionAuthorizer {
405    /// Wraps a shared application authorizer.
406    #[must_use]
407    pub fn new<T: SshSessionAuthorizer + 'static>(authorizer: Arc<T>) -> Self {
408        Self { inner: authorizer }
409    }
410}
411
412impl SshSessionAuthorizer for AnySshSessionAuthorizer {
413    async fn authorize_connect(&self, target: &str) -> Result<bool, SshAuthorizationError> {
414        self.inner.connect(target).await
415    }
416    async fn authorize_runtime_install(
417        &self,
418        target: &str,
419        details: &str,
420    ) -> Result<bool, SshAuthorizationError> {
421        self.inner.install(target, details).await
422    }
423}
424
425/// Failure to obtain an application-level SSH authorization decision.
426#[derive(Debug, thiserror::Error)]
427pub enum SshAuthorizationError {
428    /// The application's permission prompt failed.
429    #[error("SSH permission prompt failed: {0}")]
430    Prompt(String),
431}
432
433/// Tracks which shell backends are configured and how to reach them.
434///
435/// Cloning shares the same underlying state, so registering a container or SSH
436/// server is visible to every holder.
437#[derive(Clone)]
438pub struct ShellSessionRegistry {
439    availability: ShellRuntimeAvailability,
440    ssh_servers: Vec<SshServer>,
441    ssh_authorizer: Option<AnySshSessionAuthorizer>,
442    container_runtime: Option<ContainerShellRuntime>,
443    pub(crate) prepared_tools: Option<crate::tool_environment::PreparedToolEnvironments>,
444}
445
446impl std::fmt::Debug for ShellSessionRegistry {
447    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
448        f.debug_struct("ShellSessionRegistry")
449            .finish_non_exhaustive()
450    }
451}
452
453impl ShellSessionRegistry {
454    /// Creates a registry advertising the given backends.
455    #[must_use]
456    pub const fn new(availability: ShellRuntimeAvailability) -> Self {
457        Self {
458            availability,
459            ssh_servers: Vec::new(),
460            ssh_authorizer: None,
461            container_runtime: None,
462            prepared_tools: None,
463        }
464    }
465
466    /// Replaces runtime availability.
467    #[must_use]
468    pub const fn with_availability(mut self, availability: ShellRuntimeAvailability) -> Self {
469        self.availability = availability;
470        self
471    }
472
473    /// The currently advertised backends.
474    #[must_use]
475    pub fn with_ssh_authorizer<T: SshSessionAuthorizer + 'static>(
476        mut self,
477        authorizer: Arc<T>,
478    ) -> Self {
479        self.ssh_authorizer = Some(AnySshSessionAuthorizer::new(authorizer));
480        self
481    }
482
483    /// Sets the container runtime.
484    #[must_use]
485    pub fn with_container_runtime(mut self, runtime: ContainerShellRuntime) -> Self {
486        self.container_runtime = Some(runtime);
487        self
488    }
489
490    #[must_use]
491    /// Returns runtime availability.
492    pub fn availability(&self) -> ShellRuntimeAvailability {
493        self.availability.clone()
494    }
495
496    /// Sets SSH server definitions.
497    ///
498    /// # Errors
499    /// Returns an error when a server entry has an empty id/target or duplicates another id.
500    pub fn with_ssh_servers(mut self, servers: Vec<SshServer>) -> Result<Self, String> {
501        let mut seen = HashSet::new();
502        let mut deduped = Vec::new();
503        for server in servers {
504            let id = server.id().trim().to_string();
505            let target = server.target.trim().to_string();
506            if id.is_empty() || target.is_empty() {
507                return Err("ssh server entries require non-empty name and target".to_string());
508            }
509            if !seen.insert(id.clone()) {
510                return Err(format!("duplicate ssh server id: {id}"));
511            }
512            deduped.push(SshServer { name: id, target });
513        }
514
515        self.ssh_servers = deduped;
516        Ok(self)
517    }
518
519    /// Every registered SSH server.
520    #[must_use]
521    /// Lists configured SSH servers.
522    pub fn list_ssh_servers(&self) -> Vec<SshServer> {
523        self.ssh_servers.clone()
524    }
525
526    pub(crate) fn ssh_servers(&self) -> &[SshServer] {
527        &self.ssh_servers
528    }
529
530    pub(crate) const fn container_runtime(&self) -> Option<&ContainerShellRuntime> {
531        self.container_runtime.as_ref()
532    }
533
534    /// Returns the default SSH server.
535    ///
536    /// # Errors
537    /// Returns an error when no SSH server is configured or more than one server requires disambiguation.
538    pub fn default_ssh_server(&self) -> Result<SshServer, String> {
539        match self.ssh_servers.as_slice() {
540            [] => Err("no ssh servers are configured".to_string()),
541            [server] => Ok(server.clone()),
542            _ => Err(
543                "ssh_server_id is required because multiple ssh servers are configured".to_string(),
544            ),
545        }
546    }
547
548    /// Looks up a registered server by name.
549    ///
550    /// # Errors
551    ///
552    /// Returns an error if `server_id` is blank, names no registered server, or
553    /// the server lock was poisoned.
554    pub fn resolve_ssh_server(&self, server_id: &str) -> Result<SshServer, String> {
555        let wanted = server_id.trim();
556        if wanted.is_empty() {
557            return Err("ssh_server_id is required for ssh mode".to_string());
558        }
559        self.ssh_servers
560            .iter()
561            .find(|s| s.id() == wanted)
562            .cloned()
563            .ok_or_else(|| format!("unknown ssh_server_id: {wanted}"))
564    }
565
566    /// Picks the backend to use for a command that did not name one.
567    ///
568    /// Prefers a container when one is configured, since it isolates better
569    /// than running on the host.
570    ///
571    /// # Errors
572    ///
573    /// Returns an error if neither a container nor local execution is available.
574    pub fn resolve_local_backend(&self) -> Result<ShellBackend, String> {
575        let availability = self.availability();
576        if availability.container {
577            return Ok(ShellBackend::Container);
578        }
579        if availability.local {
580            return Ok(ShellBackend::Local);
581        }
582        Err("no local backend available".to_string())
583    }
584
585    /// Confirms the SSH backend is configured.
586    ///
587    /// # Errors
588    ///
589    /// Returns an error if no SSH servers are registered.
590    pub fn ensure_ssh_available(&self) -> Result<(), String> {
591        if self.availability().ssh {
592            Ok(())
593        } else {
594            Err("ssh backend is not available".to_string())
595        }
596    }
597
598    #[must_use]
599    /// Returns the SSH authorizer when configured.
600    pub fn ssh_authorizer(&self) -> Option<AnySshSessionAuthorizer> {
601        self.ssh_authorizer.clone()
602    }
603}
604
605/// Prepares a remote host to run sandboxed commands.
606///
607/// Confirms the connection is authorized, probes for the `heel` runtime, and —
608/// with the user's approval — installs it if it is missing.
609///
610/// # Errors
611///
612/// Returns an error if the authorizer denies the connection, the SSH probe
613/// fails, or `heel` is absent and either installation was declined or did not
614/// succeed.
615pub async fn bootstrap_ssh_runtime(
616    target: &str,
617    authorizer: &Option<AnySshSessionAuthorizer>,
618) -> Result<SshRuntimeProfile, anyhow::Error> {
619    if let Some(auth) = authorizer {
620        let allowed = auth
621            .authorize_connect(target)
622            .await
623            .map_err(anyhow::Error::msg)?;
624        if !allowed {
625            return Err(anyhow::anyhow!("user denied ssh connection authorization"));
626        }
627    }
628
629    let remote = detect_remote(target).await?;
630    if remote.heel_found {
631        return Ok(SshRuntimeProfile::Heel {
632            binary: remote.heel_path,
633        });
634    }
635
636    if let Some(auth) = authorizer {
637        let details = format!(
638            "Remote {} ({}) does not have heel installed.",
639            remote.os, remote.arch
640        );
641        let approve_install = auth
642            .authorize_runtime_install(target, &details)
643            .await
644            .map_err(anyhow::Error::msg)?;
645        if approve_install && install_heel(target, &remote).await? {
646            let verified = detect_remote(target).await?;
647            if verified.heel_found {
648                return Ok(SshRuntimeProfile::Heel {
649                    binary: verified.heel_path,
650                });
651            }
652        }
653    }
654
655    Err(anyhow::anyhow!(
656        "remote heel runtime unavailable; ssh mode requires heel on the remote host"
657    ))
658}
659
660struct RemoteInfo {
661    os: String,
662    arch: String,
663    heel_found: bool,
664    heel_path: String,
665}
666
667async fn detect_remote(target: &str) -> Result<RemoteInfo, anyhow::Error> {
668    let probe = "uname -s; uname -m; if command -v heel >/dev/null 2>&1; then command -v heel; elif [ -x \"$HOME/.local/bin/heel\" ]; then printf '%s\\n' \"$HOME/.local/bin/heel\"; else echo __NO_HEEL__; fi";
669    let output = async_process::Command::new("ssh")
670        .arg("-o")
671        .arg("BatchMode=yes")
672        .arg("-o")
673        .arg("ConnectTimeout=10")
674        .arg(target)
675        .arg(probe)
676        .stdin(async_process::Stdio::null())
677        .output()
678        .await
679        .map_err(|e| anyhow::anyhow!("ssh probe failed: {e}"))?;
680
681    if !output.status.success() {
682        return Err(anyhow::anyhow!(
683            "ssh probe failed: {}",
684            String::from_utf8_lossy(&output.stderr)
685        ));
686    }
687
688    parse_remote_probe_output(&output.stdout)
689}
690
691fn parse_remote_probe_output(stdout: &[u8]) -> Result<RemoteInfo, anyhow::Error> {
692    let lines = String::from_utf8_lossy(stdout)
693        .lines()
694        .map(|s| s.trim().to_string())
695        .collect::<Vec<_>>();
696    if lines.len() < 3 {
697        return Err(anyhow::anyhow!("ssh probe returned unexpected output"));
698    }
699
700    let heel_line = lines[2].clone();
701    let heel_found = heel_line != "__NO_HEEL__";
702    if !heel_found {
703        return Ok(RemoteInfo {
704            os: lines[0].clone(),
705            arch: lines[1].clone(),
706            heel_found,
707            heel_path: String::new(),
708        });
709    }
710
711    Ok(RemoteInfo {
712        os: lines[0].clone(),
713        arch: lines[1].clone(),
714        heel_found,
715        heel_path: heel_line,
716    })
717}
718
719async fn install_heel(target: &str, remote: &RemoteInfo) -> Result<bool, anyhow::Error> {
720    let local_os = std::env::consts::OS;
721    let remote_os = remote.os.to_lowercase();
722    let os_match = (local_os == "macos" && remote_os.contains("darwin"))
723        || (local_os == "linux" && remote_os.contains("linux"));
724    if !os_match {
725        return Ok(false);
726    }
727
728    let local_arch = std::env::consts::ARCH;
729    if normalize_arch(local_arch) != normalize_arch(&remote.arch) {
730        return Ok(false);
731    }
732
733    let local_heel = find_local_heel().await?;
734    if local_heel.is_empty() {
735        return Ok(false);
736    }
737
738    let mkdir_status = async_process::Command::new("ssh")
739        .arg("-o")
740        .arg("BatchMode=yes")
741        .arg("-o")
742        .arg("ConnectTimeout=10")
743        .arg(target)
744        .arg("mkdir -p ~/.local/bin")
745        .stdin(async_process::Stdio::null())
746        .status()
747        .await
748        .map_err(|e| anyhow::anyhow!("ssh mkdir failed: {e}"))?;
749    if !mkdir_status.success() {
750        return Ok(false);
751    }
752
753    let dest = format!("{target}:~/.local/bin/heel");
754    let scp_status = async_process::Command::new("scp")
755        .arg("-o")
756        .arg("BatchMode=yes")
757        .arg("-o")
758        .arg("ConnectTimeout=10")
759        .arg(&local_heel)
760        .arg(&dest)
761        .stdin(async_process::Stdio::null())
762        .status()
763        .await
764        .map_err(|e| anyhow::anyhow!("scp heel failed: {e}"))?;
765    if !scp_status.success() {
766        return Ok(false);
767    }
768
769    let verify_status = async_process::Command::new("ssh")
770        .arg("-o")
771        .arg("BatchMode=yes")
772        .arg("-o")
773        .arg("ConnectTimeout=10")
774        .arg(target)
775        .arg("chmod +x ~/.local/bin/heel && ~/.local/bin/heel --version")
776        .stdin(async_process::Stdio::null())
777        .status()
778        .await
779        .map_err(|e| anyhow::anyhow!("verify heel failed: {e}"))?;
780
781    Ok(verify_status.success())
782}
783
784async fn find_local_heel() -> Result<String, anyhow::Error> {
785    let out = async_process::Command::new("sh")
786        .arg("-c")
787        .arg("command -v heel || true")
788        .stdin(async_process::Stdio::null())
789        .output()
790        .await
791        .map_err(|e| anyhow::anyhow!("failed to locate local heel: {e}"))?;
792    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
793}
794
795fn normalize_arch(raw: &str) -> &str {
796    match raw {
797        "x86_64" | "amd64" => "x86_64",
798        "aarch64" | "arm64" => "arm64",
799        other => other,
800    }
801}
802
803#[cfg(test)]
804mod tests {
805    use super::{
806        ShellRuntimeAvailability, ShellSessionRegistry, SshServer, parse_remote_probe_output,
807    };
808
809    #[test]
810    fn parse_remote_probe_detects_local_bin_heel_path() {
811        let stdout = b"Linux\nx86_64\n/home/test/.local/bin/heel\n";
812        let remote = parse_remote_probe_output(stdout).expect("probe output should parse");
813        assert_eq!(remote.os, "Linux");
814        assert_eq!(remote.arch, "x86_64");
815        assert!(remote.heel_found);
816        assert_eq!(remote.heel_path, "/home/test/.local/bin/heel");
817    }
818
819    #[test]
820    fn parse_remote_probe_handles_missing_heel() {
821        let stdout = b"Linux\naarch64\n__NO_HEEL__\n";
822        let remote = parse_remote_probe_output(stdout).expect("probe output should parse");
823        assert!(!remote.heel_found);
824        assert_eq!(remote.heel_path, "");
825    }
826
827    #[test]
828    fn default_ssh_server_uses_single_configured_target() {
829        let registry = ShellSessionRegistry::new(ShellRuntimeAvailability {
830            local: false,
831            container: false,
832            ssh: true,
833        })
834        .with_ssh_servers(vec![SshServer {
835            name: "prod".to_string(),
836            target: "root@example.com".to_string(),
837        }])
838        .expect("ssh server should configure");
839
840        let server = registry
841            .default_ssh_server()
842            .expect("single ssh server should become default");
843        assert_eq!(server.id(), "prod");
844        assert_eq!(server.target, "root@example.com");
845    }
846
847    #[test]
848    fn default_ssh_server_requires_disambiguation_when_multiple_exist() {
849        let registry = ShellSessionRegistry::new(ShellRuntimeAvailability {
850            local: false,
851            container: false,
852            ssh: true,
853        })
854        .with_ssh_servers(vec![
855            SshServer {
856                name: "prod".to_string(),
857                target: "root@example.com".to_string(),
858            },
859            SshServer {
860                name: "staging".to_string(),
861                target: "root@staging.example.com".to_string(),
862            },
863        ])
864        .expect("ssh servers should configure");
865
866        let error = registry
867            .default_ssh_server()
868            .expect_err("multiple ssh servers must require explicit selection");
869        assert!(
870            error.contains("ssh_server_id is required"),
871            "unexpected error: {error}"
872        );
873    }
874
875    #[test]
876    fn bridge_address_rejects_the_unspecified_and_multicast_addresses() {
877        use super::{BridgeAddress, BridgeAddressError};
878        use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
879
880        for address in [
881            IpAddr::V4(Ipv4Addr::UNSPECIFIED),
882            IpAddr::V6(Ipv6Addr::UNSPECIFIED),
883        ] {
884            assert!(
885                matches!(
886                    BridgeAddress::try_from(address),
887                    Err(BridgeAddressError::Unspecified(_))
888                ),
889                "{address} must be rejected as unspecified"
890            );
891        }
892        for address in [
893            IpAddr::V4(Ipv4Addr::new(224, 0, 0, 1)),
894            IpAddr::V6(Ipv6Addr::new(0xff02, 0, 0, 0, 0, 0, 0, 1)),
895        ] {
896            assert!(
897                matches!(
898                    BridgeAddress::try_from(address),
899                    Err(BridgeAddressError::Multicast(_))
900                ),
901                "{address} must be rejected as multicast"
902            );
903        }
904        for address in [
905            IpAddr::V4(Ipv4Addr::LOCALHOST),
906            IpAddr::V4(Ipv4Addr::new(172, 17, 0, 1)),
907        ] {
908            assert_eq!(
909                BridgeAddress::try_from(address)
910                    .expect("a concrete host address should be accepted")
911                    .ip(),
912                address
913            );
914        }
915    }
916}