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 container execution trait.
40pub trait ContainerExecObject: Send + Sync {
41    /// Execute a command inside a container through a boxed future.
42    fn exec_boxed<'a>(
43        &'a self,
44        container_id: &'a str,
45        script: &'a str,
46        working_dir: &'a str,
47        kill_rx: Receiver<()>,
48        stdin_rx: Receiver<Vec<u8>>,
49        stdin_blocked_notice: Option<Sender<String>>,
50    ) -> Pin<Box<dyn Future<Output = Result<ContainerExecOutcome, String>> + Send + 'a>>;
51}
52
53/// Backend-agnostic container executor handle.
54///
55/// This wraps any [`ContainerExec`] implementation into a cloneable concrete
56/// type that can be passed around without exposing runtime-specific concrete
57/// executor types.
58#[derive(Clone)]
59pub struct ContainerExecHandle {
60    inner: Arc<dyn ContainerExecObject>,
61}
62
63impl std::fmt::Debug for ContainerExecHandle {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        f.debug_struct("ContainerExecHandle")
66            .finish_non_exhaustive()
67    }
68}
69
70impl ContainerExecHandle {
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 ContainerExecHandle {
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/// Container runtime session metadata.
112#[derive(Clone)]
113pub struct ContainerShellRuntime {
114    exec: Arc<dyn ContainerExecObject>,
115    container_id: String,
116    ipc_host: String,
117}
118
119impl std::fmt::Debug for ContainerShellRuntime {
120    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121        f.debug_struct("ContainerShellRuntime")
122            .field("container_id", &self.container_id)
123            .field("ipc_host", &self.ipc_host)
124            .finish_non_exhaustive()
125    }
126}
127
128impl ContainerShellRuntime {
129    /// Creates a container shell runtime.
130    ///
131    /// # Panics
132    /// Panics if `container_id` or `ipc_host` is empty after trimming.
133    #[must_use]
134    pub fn new(
135        container_id: impl Into<String>,
136        ipc_host: impl Into<String>,
137        exec: ContainerExecHandle,
138    ) -> Self {
139        let container_id = container_id.into();
140        let ipc_host = ipc_host.into();
141        assert!(
142            !container_id.trim().is_empty(),
143            "container runtime requires a non-empty container_id"
144        );
145        assert!(
146            !ipc_host.trim().is_empty(),
147            "container runtime requires a non-empty ipc_host"
148        );
149        Self {
150            exec: exec.inner,
151            container_id,
152            ipc_host,
153        }
154    }
155
156    #[must_use]
157    /// Returns the container id.
158    pub fn container_id(&self) -> &str {
159        &self.container_id
160    }
161
162    #[must_use]
163    /// Returns the host name used for IPC callbacks from the container.
164    pub fn ipc_host(&self) -> &str {
165        &self.ipc_host
166    }
167
168    pub(crate) fn exec(&self) -> Arc<dyn ContainerExecObject> {
169        Arc::clone(&self.exec)
170    }
171}
172
173impl<T: ContainerExec> ContainerExecObject for T {
174    fn exec_boxed<'a>(
175        &'a self,
176        container_id: &'a str,
177        script: &'a str,
178        working_dir: &'a str,
179        kill_rx: Receiver<()>,
180        stdin_rx: Receiver<Vec<u8>>,
181        stdin_blocked_notice: Option<Sender<String>>,
182    ) -> Pin<Box<dyn Future<Output = Result<ContainerExecOutcome, String>> + Send + 'a>> {
183        Box::pin(self.exec(
184            container_id,
185            script,
186            working_dir,
187            kill_rx,
188            stdin_rx,
189            stdin_blocked_notice,
190        ))
191    }
192}
193
194/// Where a shell command is executed.
195#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
196#[serde(rename_all = "lowercase")]
197pub enum ShellBackend {
198    /// On this machine, inside the local sandbox.
199    Local,
200    /// Inside a container.
201    Container,
202    /// On a remote host over SSH.
203    Ssh,
204}
205
206/// A named SSH destination the agent may run commands on.
207#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
208pub struct SshServer {
209    /// Short name the agent uses to select this server.
210    pub name: String,
211    /// SSH target, as passed to `ssh` (for example `user@host`).
212    pub target: String,
213}
214
215impl SshServer {
216    /// The name used to address this server.
217    #[must_use]
218    pub fn id(&self) -> &str {
219        &self.name
220    }
221}
222
223/// How the sandbox runtime is available on a remote host.
224#[derive(Debug, Clone)]
225pub enum SshRuntimeProfile {
226    /// The `heel` sandbox binary is installed at the given path.
227    Heel {
228        /// Absolute path to the `heel` binary on the remote host.
229        binary: String,
230    },
231}
232
233/// Which shell backends are usable in the current deployment.
234///
235/// Reported to the model so it does not offer a backend that is not configured.
236#[derive(Debug, Clone, Serialize)]
237pub struct ShellRuntimeAvailability {
238    /// Whether local execution is available. Always true in practice.
239    pub local: bool,
240    /// Whether a container runtime has been wired up.
241    pub container: bool,
242    /// Whether any SSH servers are registered.
243    pub ssh: bool,
244}
245
246impl Default for ShellRuntimeAvailability {
247    fn default() -> Self {
248        Self {
249            local: true,
250            container: false,
251            ssh: false,
252        }
253    }
254}
255
256/// Approves remote actions before the sandbox performs them.
257///
258/// Connecting to a host and installing software on it are both decisions a user
259/// should make, so they are routed through this trait rather than assumed.
260pub trait SshSessionAuthorizer: Send + Sync {
261    /// Asks whether the agent may open an SSH connection to `target`.
262    fn authorize_connect(
263        &self,
264        target: &str,
265    ) -> Pin<Box<dyn Future<Output = Result<bool, String>> + Send + '_>>;
266
267    /// Asks whether the agent may install the `heel` runtime on `target`.
268    ///
269    /// `details` describes the remote host so the user can judge the request.
270    fn authorize_heel_install(
271        &self,
272        target: &str,
273        details: &str,
274    ) -> Pin<Box<dyn Future<Output = Result<bool, String>> + Send + '_>>;
275}
276
277/// Tracks which shell backends are configured and how to reach them.
278///
279/// Cloning shares the same underlying state, so registering a container or SSH
280/// server is visible to every holder.
281#[derive(Clone)]
282pub struct ShellSessionRegistry {
283    availability: ShellRuntimeAvailability,
284    ssh_servers: Vec<SshServer>,
285    ssh_authorizer: Option<Arc<dyn SshSessionAuthorizer>>,
286    container_runtime: Option<ContainerShellRuntime>,
287}
288
289impl std::fmt::Debug for ShellSessionRegistry {
290    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
291        f.debug_struct("ShellSessionRegistry")
292            .finish_non_exhaustive()
293    }
294}
295
296impl ShellSessionRegistry {
297    /// Creates a registry advertising the given backends.
298    #[must_use]
299    pub fn new(availability: ShellRuntimeAvailability) -> Self {
300        Self {
301            availability,
302            ssh_servers: Vec::new(),
303            ssh_authorizer: None,
304            container_runtime: None,
305        }
306    }
307
308    /// Replaces runtime availability.
309    #[must_use]
310    pub const fn with_availability(mut self, availability: ShellRuntimeAvailability) -> Self {
311        self.availability = availability;
312        self
313    }
314
315    /// The currently advertised backends.
316    #[must_use]
317    pub fn with_ssh_authorizer(mut self, authorizer: Arc<dyn SshSessionAuthorizer>) -> Self {
318        self.ssh_authorizer = Some(authorizer);
319        self
320    }
321
322    /// Sets the container runtime.
323    #[must_use]
324    pub fn with_container_runtime(mut self, runtime: ContainerShellRuntime) -> Self {
325        self.container_runtime = Some(runtime);
326        self
327    }
328
329    #[must_use]
330    /// Returns runtime availability.
331    pub fn availability(&self) -> ShellRuntimeAvailability {
332        self.availability.clone()
333    }
334
335    /// Sets SSH server definitions.
336    ///
337    /// # Errors
338    /// Returns an error when a server entry has an empty id/target or duplicates another id.
339    pub fn with_ssh_servers(mut self, servers: Vec<SshServer>) -> Result<Self, String> {
340        let mut seen = HashSet::new();
341        let mut deduped = Vec::new();
342        for server in servers {
343            let id = server.id().trim().to_string();
344            let target = server.target.trim().to_string();
345            if id.is_empty() || target.is_empty() {
346                return Err("ssh server entries require non-empty name and target".to_string());
347            }
348            if !seen.insert(id.clone()) {
349                return Err(format!("duplicate ssh server id: {id}"));
350            }
351            deduped.push(SshServer { name: id, target });
352        }
353
354        self.ssh_servers = deduped;
355        Ok(self)
356    }
357
358    /// Every registered SSH server.
359    #[must_use]
360    /// Lists configured SSH servers.
361    pub fn list_ssh_servers(&self) -> Vec<SshServer> {
362        self.ssh_servers.clone()
363    }
364
365    pub(crate) const fn container_runtime(&self) -> Option<&ContainerShellRuntime> {
366        self.container_runtime.as_ref()
367    }
368
369    /// Returns the default SSH server.
370    ///
371    /// # Errors
372    /// Returns an error when no SSH server is configured or more than one server requires disambiguation.
373    pub fn default_ssh_server(&self) -> Result<SshServer, String> {
374        match self.ssh_servers.as_slice() {
375            [] => Err("no ssh servers are configured".to_string()),
376            [server] => Ok(server.clone()),
377            _ => Err(
378                "ssh_server_id is required because multiple ssh servers are configured".to_string(),
379            ),
380        }
381    }
382
383    /// Looks up a registered server by name.
384    ///
385    /// # Errors
386    ///
387    /// Returns an error if `server_id` is blank, names no registered server, or
388    /// the server lock was poisoned.
389    pub fn resolve_ssh_server(&self, server_id: &str) -> Result<SshServer, String> {
390        let wanted = server_id.trim();
391        if wanted.is_empty() {
392            return Err("ssh_server_id is required for ssh mode".to_string());
393        }
394        self.ssh_servers
395            .iter()
396            .find(|s| s.id() == wanted)
397            .cloned()
398            .ok_or_else(|| format!("unknown ssh_server_id: {wanted}"))
399    }
400
401    /// Picks the backend to use for a command that did not name one.
402    ///
403    /// Prefers a container when one is configured, since it isolates better
404    /// than running on the host.
405    ///
406    /// # Errors
407    ///
408    /// Returns an error if neither a container nor local execution is available.
409    pub fn resolve_local_backend(&self) -> Result<ShellBackend, String> {
410        let availability = self.availability();
411        if availability.container {
412            return Ok(ShellBackend::Container);
413        }
414        if availability.local {
415            return Ok(ShellBackend::Local);
416        }
417        Err("no local backend available".to_string())
418    }
419
420    /// Confirms the SSH backend is configured.
421    ///
422    /// # Errors
423    ///
424    /// Returns an error if no SSH servers are registered.
425    pub fn ensure_ssh_available(&self) -> Result<(), String> {
426        if self.availability().ssh {
427            Ok(())
428        } else {
429            Err("ssh backend is not available".to_string())
430        }
431    }
432
433    #[must_use]
434    /// Returns the SSH authorizer when configured.
435    pub fn ssh_authorizer(&self) -> Option<Arc<dyn SshSessionAuthorizer>> {
436        self.ssh_authorizer.clone()
437    }
438}
439
440/// Prepares a remote host to run sandboxed commands.
441///
442/// Confirms the connection is authorized, probes for the `heel` runtime, and —
443/// with the user's approval — installs it if it is missing.
444///
445/// # Errors
446///
447/// Returns an error if the authorizer denies the connection, the SSH probe
448/// fails, or `heel` is absent and either installation was declined or did not
449/// succeed.
450pub async fn bootstrap_ssh_runtime(
451    target: &str,
452    authorizer: &Option<Arc<dyn SshSessionAuthorizer>>,
453) -> Result<SshRuntimeProfile, anyhow::Error> {
454    if let Some(auth) = authorizer {
455        let allowed = auth
456            .authorize_connect(target)
457            .await
458            .map_err(anyhow::Error::msg)?;
459        if !allowed {
460            return Err(anyhow::anyhow!("user denied ssh connection authorization"));
461        }
462    }
463
464    let remote = detect_remote(target).await?;
465    if remote.heel_found {
466        return Ok(SshRuntimeProfile::Heel {
467            binary: remote.heel_path,
468        });
469    }
470
471    if let Some(auth) = authorizer {
472        let details = format!(
473            "Remote {} ({}) does not have heel installed.",
474            remote.os, remote.arch
475        );
476        let approve_install = auth
477            .authorize_heel_install(target, &details)
478            .await
479            .map_err(anyhow::Error::msg)?;
480        if approve_install && install_heel(target, &remote).await? {
481            let verified = detect_remote(target).await?;
482            if verified.heel_found {
483                return Ok(SshRuntimeProfile::Heel {
484                    binary: verified.heel_path,
485                });
486            }
487        }
488    }
489
490    Err(anyhow::anyhow!(
491        "remote heel runtime unavailable; ssh mode requires heel on the remote host"
492    ))
493}
494
495struct RemoteInfo {
496    os: String,
497    arch: String,
498    heel_found: bool,
499    heel_path: String,
500}
501
502async fn detect_remote(target: &str) -> Result<RemoteInfo, anyhow::Error> {
503    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";
504    let output = async_process::Command::new("ssh")
505        .arg("-o")
506        .arg("BatchMode=yes")
507        .arg("-o")
508        .arg("ConnectTimeout=10")
509        .arg(target)
510        .arg(probe)
511        .stdin(async_process::Stdio::null())
512        .output()
513        .await
514        .map_err(|e| anyhow::anyhow!("ssh probe failed: {e}"))?;
515
516    if !output.status.success() {
517        return Err(anyhow::anyhow!(
518            "ssh probe failed: {}",
519            String::from_utf8_lossy(&output.stderr)
520        ));
521    }
522
523    parse_remote_probe_output(&output.stdout)
524}
525
526fn parse_remote_probe_output(stdout: &[u8]) -> Result<RemoteInfo, anyhow::Error> {
527    let lines = String::from_utf8_lossy(stdout)
528        .lines()
529        .map(|s| s.trim().to_string())
530        .collect::<Vec<_>>();
531    if lines.len() < 3 {
532        return Err(anyhow::anyhow!("ssh probe returned unexpected output"));
533    }
534
535    let heel_line = lines[2].clone();
536    let heel_found = heel_line != "__NO_HEEL__";
537    if !heel_found {
538        return Ok(RemoteInfo {
539            os: lines[0].clone(),
540            arch: lines[1].clone(),
541            heel_found,
542            heel_path: String::new(),
543        });
544    }
545
546    Ok(RemoteInfo {
547        os: lines[0].clone(),
548        arch: lines[1].clone(),
549        heel_found,
550        heel_path: heel_line,
551    })
552}
553
554async fn install_heel(target: &str, remote: &RemoteInfo) -> Result<bool, anyhow::Error> {
555    let local_os = std::env::consts::OS;
556    let remote_os = remote.os.to_lowercase();
557    let os_match = (local_os == "macos" && remote_os.contains("darwin"))
558        || (local_os == "linux" && remote_os.contains("linux"));
559    if !os_match {
560        return Ok(false);
561    }
562
563    let local_arch = std::env::consts::ARCH;
564    if normalize_arch(local_arch) != normalize_arch(&remote.arch) {
565        return Ok(false);
566    }
567
568    let local_heel = find_local_heel().await?;
569    if local_heel.is_empty() {
570        return Ok(false);
571    }
572
573    let mkdir_status = async_process::Command::new("ssh")
574        .arg("-o")
575        .arg("BatchMode=yes")
576        .arg("-o")
577        .arg("ConnectTimeout=10")
578        .arg(target)
579        .arg("mkdir -p ~/.local/bin")
580        .stdin(async_process::Stdio::null())
581        .status()
582        .await
583        .map_err(|e| anyhow::anyhow!("ssh mkdir failed: {e}"))?;
584    if !mkdir_status.success() {
585        return Ok(false);
586    }
587
588    let dest = format!("{target}:~/.local/bin/heel");
589    let scp_status = async_process::Command::new("scp")
590        .arg("-o")
591        .arg("BatchMode=yes")
592        .arg("-o")
593        .arg("ConnectTimeout=10")
594        .arg(&local_heel)
595        .arg(&dest)
596        .stdin(async_process::Stdio::null())
597        .status()
598        .await
599        .map_err(|e| anyhow::anyhow!("scp heel failed: {e}"))?;
600    if !scp_status.success() {
601        return Ok(false);
602    }
603
604    let verify_status = async_process::Command::new("ssh")
605        .arg("-o")
606        .arg("BatchMode=yes")
607        .arg("-o")
608        .arg("ConnectTimeout=10")
609        .arg(target)
610        .arg("chmod +x ~/.local/bin/heel && ~/.local/bin/heel --version")
611        .stdin(async_process::Stdio::null())
612        .status()
613        .await
614        .map_err(|e| anyhow::anyhow!("verify heel failed: {e}"))?;
615
616    Ok(verify_status.success())
617}
618
619async fn find_local_heel() -> Result<String, anyhow::Error> {
620    let out = async_process::Command::new("sh")
621        .arg("-c")
622        .arg("command -v heel || true")
623        .stdin(async_process::Stdio::null())
624        .output()
625        .await
626        .map_err(|e| anyhow::anyhow!("failed to locate local heel: {e}"))?;
627    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
628}
629
630fn normalize_arch(raw: &str) -> &str {
631    match raw {
632        "x86_64" | "amd64" => "x86_64",
633        "aarch64" | "arm64" => "arm64",
634        other => other,
635    }
636}
637
638#[cfg(test)]
639mod tests {
640    use super::{
641        ShellRuntimeAvailability, ShellSessionRegistry, SshServer, parse_remote_probe_output,
642    };
643
644    #[test]
645    fn parse_remote_probe_detects_local_bin_heel_path() {
646        let stdout = b"Linux\nx86_64\n/home/test/.local/bin/heel\n";
647        let remote = parse_remote_probe_output(stdout).expect("probe output should parse");
648        assert_eq!(remote.os, "Linux");
649        assert_eq!(remote.arch, "x86_64");
650        assert!(remote.heel_found);
651        assert_eq!(remote.heel_path, "/home/test/.local/bin/heel");
652    }
653
654    #[test]
655    fn parse_remote_probe_handles_missing_heel() {
656        let stdout = b"Linux\naarch64\n__NO_HEEL__\n";
657        let remote = parse_remote_probe_output(stdout).expect("probe output should parse");
658        assert!(!remote.heel_found);
659        assert!(remote.heel_path.is_empty());
660    }
661
662    #[test]
663    fn default_ssh_server_uses_single_configured_target() {
664        let registry = ShellSessionRegistry::new(ShellRuntimeAvailability {
665            local: false,
666            container: false,
667            ssh: true,
668        })
669        .with_ssh_servers(vec![SshServer {
670            name: "prod".to_string(),
671            target: "root@example.com".to_string(),
672        }])
673        .expect("ssh server should configure");
674
675        let server = registry
676            .default_ssh_server()
677            .expect("single ssh server should become default");
678        assert_eq!(server.id(), "prod");
679        assert_eq!(server.target, "root@example.com");
680    }
681
682    #[test]
683    fn default_ssh_server_requires_disambiguation_when_multiple_exist() {
684        let registry = ShellSessionRegistry::new(ShellRuntimeAvailability {
685            local: false,
686            container: false,
687            ssh: true,
688        })
689        .with_ssh_servers(vec![
690            SshServer {
691                name: "prod".to_string(),
692                target: "root@example.com".to_string(),
693            },
694            SshServer {
695                name: "staging".to_string(),
696                target: "root@staging.example.com".to_string(),
697            },
698        ])
699        .expect("ssh servers should configure");
700
701        let error = registry
702            .default_ssh_server()
703            .expect_err("multiple ssh servers must require explicit selection");
704        assert!(
705            error.contains("ssh_server_id is required"),
706            "unexpected error: {error}"
707        );
708    }
709}