Skip to main content

aither_sandbox/
shell_session.rs

1use std::{future::Future, pin::Pin, sync::Arc};
2
3use async_channel::{Receiver, Sender};
4
5use askama::Template as _;
6
7use crate::ssh::{PrepareSsh, SshEnvironments, SshServer, SshServerError};
8use crate::stdin_watch::StdinWatchSignal;
9use crate::{ContainerPath, HostRoute};
10
11/// How long the processes a container command leaves running when its
12/// top-level shell exits may live.
13#[derive(Debug, Clone)]
14pub enum ExecLifetime {
15    /// None: they are killed with the shell and reported in
16    /// [`ContainerExecOutcome::Completed`]'s `killed`. Its stdin is not
17    /// watched.
18    Foreground,
19    /// All of them: the execution ends with its last process. Its stdin is
20    /// watched: implementations send one [`StdinWatchSignal::Blocked`] each
21    /// time a process of the command's tree starts waiting to read the stdin
22    /// pipe with nothing buffered — and send again only after the command was
23    /// fed and blocks anew — or a single [`StdinWatchSignal::Failed`] when the
24    /// watch cannot run at all.
25    Background {
26        /// Where the stdin watch reports.
27        stdin_blocked: Sender<StdinWatchSignal>,
28    },
29}
30
31/// Outcome of a container execution request.
32#[derive(Debug)]
33pub enum ContainerExecOutcome {
34    /// The command ran to completion.
35    Completed {
36        /// Its exit status and output.
37        output: std::process::Output,
38        /// The processes it left running that an [`ExecLifetime::Foreground`]
39        /// execution killed; empty for any other.
40        killed: Vec<crate::JobProcess>,
41    },
42    /// The command was terminated before it finished.
43    Killed,
44}
45
46/// Trait for executing commands inside a container.
47///
48/// Implementations provide the bridge between aither-sandbox and a specific
49/// container runtime (e.g., Docker via bollard). The framework defines this trait;
50/// the application (may) provides the implementation.
51pub trait ContainerExec: Send + Sync {
52    /// Execute a terminal command payload inside the container, returning stdout/stderr and exit code.
53    ///
54    /// `stdin_rx` is the command's stdin; a closed channel is EOF. When
55    /// `stdin_blocked` is given, implementations send one
56    /// [`StdinWatchSignal::Blocked`] each time a process of the command's
57    /// tree starts waiting to read the stdin pipe with nothing buffered —
58    /// and send again only after the command was fed and blocks anew — or a
59    /// single [`StdinWatchSignal::Failed`] when the watch cannot run at all.
60    fn exec(
61        &self,
62        container_id: &str,
63        script: &str,
64        working_dir: &str,
65        kill_rx: Receiver<()>,
66        stdin_rx: Receiver<Vec<u8>>,
67        lifetime: ExecLifetime,
68    ) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send;
69
70    /// Executes a command like [`Self::exec`], handing its stdout on chunk by
71    /// chunk through `stdout` as it arrives instead of collecting it.
72    ///
73    /// The returned outcome carries the exit status and stderr; its stdout is
74    /// empty. `stdout` is bounded, so a consumer that stops reading holds the
75    /// command back. The command is killed, as when `kill_rx` fires, once
76    /// `kill_rx` fires or closes, or once `stdout` has no receiver left.
77    /// `lifetime` is [`Self::exec`]'s.
78    #[allow(clippy::too_many_arguments)]
79    fn exec_streamed(
80        &self,
81        container_id: &str,
82        script: &str,
83        working_dir: &str,
84        kill_rx: Receiver<()>,
85        stdin_rx: Receiver<Vec<u8>>,
86        stdout: Sender<Vec<u8>>,
87        lifetime: ExecLifetime,
88    ) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send;
89}
90
91/// Object-safe twin of [`ContainerExec`], used only through
92/// [`AnyContainerExec`].
93pub trait ContainerExecImpl: Send + Sync {
94    /// Execute a command inside a container through a boxed future.
95    fn exec_boxed<'a>(
96        &'a self,
97        container_id: &'a str,
98        script: &'a str,
99        working_dir: &'a str,
100        kill_rx: Receiver<()>,
101        stdin_rx: Receiver<Vec<u8>>,
102        lifetime: ExecLifetime,
103    ) -> Pin<Box<dyn Future<Output = Result<ContainerExecOutcome, String>> + Send + 'a>>;
104
105    /// Execute a command inside a container, streaming its stdout, through a
106    /// boxed future.
107    #[allow(clippy::too_many_arguments)]
108    fn exec_streamed_boxed<'a>(
109        &'a self,
110        container_id: &'a str,
111        script: &'a str,
112        working_dir: &'a str,
113        kill_rx: Receiver<()>,
114        stdin_rx: Receiver<Vec<u8>>,
115        stdout: Sender<Vec<u8>>,
116        lifetime: ExecLifetime,
117    ) -> Pin<Box<dyn Future<Output = Result<ContainerExecOutcome, String>> + Send + 'a>>;
118}
119
120/// Backend-agnostic container executor handle.
121///
122/// This wraps any [`ContainerExec`] implementation into a cloneable concrete
123/// type that can be passed around without exposing runtime-specific concrete
124/// executor types.
125#[derive(Clone)]
126pub struct AnyContainerExec {
127    inner: Arc<dyn ContainerExecImpl>,
128}
129
130impl std::fmt::Debug for AnyContainerExec {
131    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132        f.debug_struct("AnyContainerExec").finish_non_exhaustive()
133    }
134}
135
136impl AnyContainerExec {
137    /// Creates a new handle from a concrete container executor implementation.
138    #[must_use]
139    pub fn new<T>(inner: Arc<T>) -> Self
140    where
141        T: ContainerExec + 'static,
142    {
143        Self { inner }
144    }
145}
146
147impl ContainerExec for AnyContainerExec {
148    fn exec(
149        &self,
150        container_id: &str,
151        script: &str,
152        working_dir: &str,
153        kill_rx: Receiver<()>,
154        stdin_rx: Receiver<Vec<u8>>,
155        lifetime: ExecLifetime,
156    ) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send {
157        let inner = Arc::clone(&self.inner);
158        let container_id = container_id.to_string();
159        let script = script.to_string();
160        let working_dir = working_dir.to_string();
161
162        async move {
163            inner
164                .exec_boxed(
165                    &container_id,
166                    &script,
167                    &working_dir,
168                    kill_rx,
169                    stdin_rx,
170                    lifetime,
171                )
172                .await
173        }
174    }
175
176    fn exec_streamed(
177        &self,
178        container_id: &str,
179        script: &str,
180        working_dir: &str,
181        kill_rx: Receiver<()>,
182        stdin_rx: Receiver<Vec<u8>>,
183        stdout: Sender<Vec<u8>>,
184        lifetime: ExecLifetime,
185    ) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send {
186        let inner = Arc::clone(&self.inner);
187        let container_id = container_id.to_string();
188        let script = script.to_string();
189        let working_dir = working_dir.to_string();
190
191        async move {
192            inner
193                .exec_streamed_boxed(
194                    &container_id,
195                    &script,
196                    &working_dir,
197                    kill_rx,
198                    stdin_rx,
199                    stdout,
200                    lifetime,
201                )
202                .await
203        }
204    }
205}
206
207/// Container runtime session metadata.
208#[derive(Clone)]
209pub struct ContainerShellRuntime {
210    exec: Arc<dyn ContainerExecImpl>,
211    container_id: String,
212    host_route: HostRoute,
213    /// The host directory the container mounts as its workspace, declared by
214    /// whoever mounts it.
215    workspace_mount: Option<crate::MountRoot>,
216}
217
218impl std::fmt::Debug for ContainerShellRuntime {
219    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220        f.debug_struct("ContainerShellRuntime")
221            .field("container_id", &self.container_id)
222            .field("host_route", &self.host_route)
223            .field("workspace_mount", &self.workspace_mount)
224            .finish_non_exhaustive()
225    }
226}
227
228impl ContainerShellRuntime {
229    /// Creates a container shell runtime.
230    ///
231    /// # Panics
232    /// Panics if `container_id` is empty after trimming.
233    #[must_use]
234    pub fn new(
235        container_id: impl Into<String>,
236        host_route: HostRoute,
237        exec: AnyContainerExec,
238    ) -> Self {
239        let container_id = container_id.into();
240        assert!(
241            !container_id.trim().is_empty(),
242            "container runtime requires a non-empty container_id"
243        );
244        Self {
245            exec: exec.inner,
246            container_id,
247            host_route,
248            workspace_mount: None,
249        }
250    }
251
252    /// Declares the host directory the container mounts as its workspace and
253    /// where it appears inside. A subagent's commands are confined in the
254    /// container through it, so a container session without it cannot launch
255    /// subagents.
256    #[must_use]
257    pub fn with_workspace_mount(mut self, mount: crate::MountRoot) -> Self {
258        self.workspace_mount = Some(mount);
259        self
260    }
261
262    /// The workspace mount, when declared.
263    #[must_use]
264    pub const fn workspace_mount(&self) -> Option<&crate::MountRoot> {
265        self.workspace_mount.as_ref()
266    }
267
268    #[must_use]
269    /// Returns the container id.
270    pub fn container_id(&self) -> &str {
271        &self.container_id
272    }
273
274    /// Returns where the host is reachable from inside the container.
275    #[must_use]
276    pub const fn host_route(&self) -> &HostRoute {
277        &self.host_route
278    }
279
280    pub(crate) fn exec(&self) -> Arc<dyn ContainerExecImpl> {
281        Arc::clone(&self.exec)
282    }
283
284    /// A reader of the container's own state: what a harness that watches
285    /// the container's memory and disk asks it.
286    #[must_use]
287    pub fn probe(&self) -> ContainerProbe {
288        ContainerProbe::from_parts(self.exec(), self.container_id.clone())
289    }
290}
291
292/// Why a probe of a container failed.
293#[derive(Debug, thiserror::Error)]
294pub enum ContainerProbeError {
295    /// The container could not run the script.
296    #[error("the container could not run the probe: {0}")]
297    Exec(String),
298    /// The script ran and failed.
299    #[error("the probe exited with {status}: {stderr}")]
300    Failed {
301        /// The exit status it returned.
302        status: std::process::ExitStatus,
303        /// What it wrote to its standard error.
304        stderr: String,
305    },
306    /// The container killed the probe before it finished.
307    #[error("the container killed the probe")]
308    Killed,
309    /// The script answered bytes that are not text.
310    #[error("the probe answered bytes that are not UTF-8")]
311    NotText,
312    /// The script answered text that is not what it was asked for.
313    #[error("the probe answered `{0}`, which is not understood")]
314    Unreadable(String),
315}
316
317/// The free bytes `df -Pk` reports: the `Available` column, in KiB, of its
318/// last line.
319fn free_bytes_from_df(output: &str) -> Option<u64> {
320    let kib: u64 = output
321        .lines()
322        .last()?
323        .split_whitespace()
324        .nth(3)?
325        .parse()
326        .ok()?;
327    kib.checked_mul(1024)
328}
329
330/// Runs short read-only scripts inside a container and returns what they
331/// print, through the same exec path commands use.
332#[derive(Clone)]
333pub struct ContainerProbe {
334    exec: Arc<dyn ContainerExecImpl>,
335    container_id: String,
336    /// The directory the agent works in inside the container.
337    home: ContainerPath,
338}
339
340/// `df` over the filesystem holding a path, in POSIX format.
341#[derive(askama::Template)]
342#[template(path = "container_disk_free.sh", escape = "none")]
343struct DiskFreeScript<'a> {
344    /// The path, quoted for the shell.
345    path: std::borrow::Cow<'a, str>,
346}
347
348impl std::fmt::Debug for ContainerProbe {
349    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
350        f.debug_struct("ContainerProbe")
351            .field("container_id", &self.container_id)
352            .finish_non_exhaustive()
353    }
354}
355
356impl ContainerProbe {
357    /// A probe of container `container_id` through `exec`.
358    ///
359    /// The agent's home directory in the container is the one commands run
360    /// in until [`Self::with_home`] says otherwise.
361    #[must_use]
362    pub fn new(exec: &AnyContainerExec, container_id: impl Into<String>) -> Self {
363        Self::from_parts(Arc::clone(&exec.inner), container_id.into())
364    }
365
366    fn from_parts(exec: Arc<dyn ContainerExecImpl>, container_id: String) -> Self {
367        Self {
368            exec,
369            container_id,
370            home: ContainerPath::new(crate::terminal::CONTAINER_EXEC_WORKING_DIR)
371                .expect("the container working directory is absolute"),
372        }
373    }
374
375    /// Names the directory the agent works in inside the container.
376    #[must_use]
377    pub fn with_home(mut self, home: ContainerPath) -> Self {
378        self.home = home;
379        self
380    }
381
382    /// The directory the agent works in inside the container.
383    #[must_use]
384    pub const fn home(&self) -> &ContainerPath {
385        &self.home
386    }
387
388    /// The bytes free to the container's processes on the filesystem that
389    /// holds the agent's home directory, as that filesystem reports them:
390    /// bounded by its own size limit when the container has one.
391    ///
392    /// # Errors
393    ///
394    /// Fails when the container cannot run `df` or answers something else.
395    ///
396    /// # Panics
397    ///
398    /// Panics when the built-in probe template does not render.
399    pub async fn free_bytes(&self) -> Result<u64, ContainerProbeError> {
400        let script = DiskFreeScript {
401            path: shell_words::quote(self.home.as_str()),
402        }
403        .render()
404        .expect("the disk probe template renders");
405        let output = self.read(&script).await?;
406        free_bytes_from_df(&output).ok_or(ContainerProbeError::Unreadable(output))
407    }
408
409    /// Runs `script` in the container's root directory and returns its
410    /// standard output.
411    ///
412    /// # Errors
413    ///
414    /// Fails when the container cannot run the script, the script exits
415    /// non-zero or its output is not text.
416    pub async fn read(&self, script: &str) -> Result<String, ContainerProbeError> {
417        // Dropping the kill sender would kill the exec, so it lives to the
418        // end of the call; the dropped stdin sender is the EOF the script
419        // reads.
420        let (_kill, kill_rx) = async_channel::bounded::<()>(1);
421        let (stdin, stdin_rx) = async_channel::unbounded::<Vec<u8>>();
422        drop(stdin);
423        let outcome = self
424            .exec
425            .exec_boxed(
426                &self.container_id,
427                script,
428                "/",
429                kill_rx,
430                stdin_rx,
431                ExecLifetime::Foreground,
432            )
433            .await
434            .map_err(ContainerProbeError::Exec)?;
435        match outcome {
436            ContainerExecOutcome::Completed { output, .. } if output.status.success() => {
437                String::from_utf8(output.stdout).map_err(|_| ContainerProbeError::NotText)
438            }
439            ContainerExecOutcome::Completed { output, .. } => Err(ContainerProbeError::Failed {
440                status: output.status,
441                stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(),
442            }),
443            ContainerExecOutcome::Killed => Err(ContainerProbeError::Killed),
444        }
445    }
446}
447
448impl<T: ContainerExec> ContainerExecImpl for T {
449    fn exec_boxed<'a>(
450        &'a self,
451        container_id: &'a str,
452        script: &'a str,
453        working_dir: &'a str,
454        kill_rx: Receiver<()>,
455        stdin_rx: Receiver<Vec<u8>>,
456        lifetime: ExecLifetime,
457    ) -> Pin<Box<dyn Future<Output = Result<ContainerExecOutcome, String>> + Send + 'a>> {
458        Box::pin(self.exec(
459            container_id,
460            script,
461            working_dir,
462            kill_rx,
463            stdin_rx,
464            lifetime,
465        ))
466    }
467
468    fn exec_streamed_boxed<'a>(
469        &'a self,
470        container_id: &'a str,
471        script: &'a str,
472        working_dir: &'a str,
473        kill_rx: Receiver<()>,
474        stdin_rx: Receiver<Vec<u8>>,
475        stdout: Sender<Vec<u8>>,
476        lifetime: ExecLifetime,
477    ) -> Pin<Box<dyn Future<Output = Result<ContainerExecOutcome, String>> + Send + 'a>> {
478        Box::pin(self.exec_streamed(
479            container_id,
480            script,
481            working_dir,
482            kill_rx,
483            stdin_rx,
484            stdout,
485            lifetime,
486        ))
487    }
488}
489
490/// The SSH servers a shell's commands may run on, as the embedder prepared
491/// them.
492///
493/// The home environment is the shell's [`Sandbox`](crate::Sandbox): its
494/// backend says where commands with no `location` run.
495///
496/// Cloning shares the SSH server set: a server added or removed through one
497/// holder is seen by every other, the terminals of subagents included.
498#[derive(Clone, Default)]
499pub struct ShellSessionRegistry {
500    ssh: SshEnvironments,
501}
502
503impl std::fmt::Debug for ShellSessionRegistry {
504    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
505        f.debug_struct("ShellSessionRegistry")
506            .finish_non_exhaustive()
507    }
508}
509
510impl ShellSessionRegistry {
511    /// Adds `server` to the set commands may run on, for every holder of this
512    /// registry. Its name and target are trimmed.
513    ///
514    /// The server is not contacted: `prepare` runs when the first command
515    /// names it, see [`PrepareSsh`]. A [`PreparedSsh`](crate::PreparedSsh)
516    /// is a preparation already done.
517    ///
518    /// # Errors
519    /// Rejects a blank name or target and a name another server has.
520    pub fn add_ssh_server(
521        &self,
522        server: SshServer,
523        prepare: impl PrepareSsh,
524    ) -> Result<(), SshServerError> {
525        self.ssh.add(server, prepare)
526    }
527
528    /// Removes the server named `name`, returning it; `None` when no server
529    /// has that name. Commands already running there keep running; the next
530    /// command naming it fails.
531    #[must_use = "the removed server, or `None` when no server has the name"]
532    pub fn remove_ssh_server(&self, name: &str) -> Option<SshServer> {
533        self.ssh.remove(name)
534    }
535
536    /// The SSH servers commands may run on now, in the order they were added.
537    #[must_use]
538    pub fn ssh_servers(&self) -> Vec<SshServer> {
539        self.ssh.list()
540    }
541
542    pub(crate) const fn ssh_environments(&self) -> &SshEnvironments {
543        &self.ssh
544    }
545
546    /// Reaches every server through `client` instead of the default one.
547    #[cfg(test)]
548    pub(crate) fn with_ssh_client(mut self, client: crate::ssh::SshClient) -> Self {
549        self.ssh = self.ssh.with_client(client);
550        self
551    }
552}
553
554#[cfg(all(test, unix))]
555mod disk_probe_tests {
556    use std::os::unix::process::ExitStatusExt as _;
557    use std::sync::Mutex;
558
559    use async_channel::{Receiver, Sender};
560
561    use super::*;
562
563    /// Answers `df` the way a container would, and records what it ran.
564    struct Df {
565        answer: &'static str,
566        exit: i32,
567        scripts: Mutex<Vec<String>>,
568    }
569
570    impl ContainerExec for Df {
571        fn exec(
572            &self,
573            _container_id: &str,
574            script: &str,
575            working_dir: &str,
576            _kill_rx: Receiver<()>,
577            _stdin_rx: Receiver<Vec<u8>>,
578            _lifetime: ExecLifetime,
579        ) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send {
580            self.scripts
581                .lock()
582                .unwrap()
583                .push(format!("{working_dir}: {script}"));
584            std::future::ready(Ok(ContainerExecOutcome::Completed {
585                output: std::process::Output {
586                    status: std::process::ExitStatus::from_raw(self.exit << 8),
587                    stdout: self.answer.as_bytes().to_vec(),
588                    stderr: b"df: no such directory".to_vec(),
589                },
590                killed: Vec::new(),
591            }))
592        }
593
594        fn exec_streamed(
595            &self,
596            _container_id: &str,
597            _script: &str,
598            _working_dir: &str,
599            _kill_rx: Receiver<()>,
600            _stdin_rx: Receiver<Vec<u8>>,
601            _stdout: Sender<Vec<u8>>,
602            _lifetime: ExecLifetime,
603        ) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send {
604            std::future::ready(Err("a probe is never streamed".to_string()))
605        }
606    }
607
608    fn probe(answer: &'static str, exit: i32) -> (Arc<Df>, ContainerProbe) {
609        let df = Arc::new(Df {
610            answer,
611            exit,
612            scripts: Mutex::new(Vec::new()),
613        });
614        let exec = AnyContainerExec::new(Arc::clone(&df));
615        (df, ContainerProbe::new(&exec, "box"))
616    }
617
618    const DF: &str = "Filesystem 1024-blocks Used Available Capacity Mounted on\noverlay 10485760 4194304 6291456 41% /workspace\n";
619
620    #[tokio::test]
621    async fn the_container_reports_the_free_space_of_its_home_filesystem() {
622        let (df, probe) = probe(DF, 0);
623        assert_eq!(probe.free_bytes().await.unwrap(), 6_291_456 * 1024);
624        let scripts = df.scripts.lock().unwrap();
625        assert_eq!(*scripts, ["/: df -Pk -- /workspace"]);
626    }
627
628    #[tokio::test]
629    async fn a_home_with_spaces_is_quoted_for_the_shell() {
630        let (df, probe) = probe(DF, 0);
631        let probe = probe.with_home(ContainerPath::new("/my work").unwrap());
632        probe.free_bytes().await.unwrap();
633        assert_eq!(*df.scripts.lock().unwrap(), ["/: df -Pk -- '/my work'"]);
634    }
635
636    #[tokio::test]
637    async fn a_df_that_fails_or_answers_something_else_is_an_error() {
638        let (_, failing) = probe("", 1);
639        assert!(matches!(
640            failing.free_bytes().await,
641            Err(ContainerProbeError::Failed { .. })
642        ));
643        let (_, odd) = probe("all clear\n", 0);
644        assert!(matches!(
645            odd.free_bytes().await,
646            Err(ContainerProbeError::Unreadable(_))
647        ));
648    }
649}
650
651#[cfg(test)]
652mod tests {
653    use super::{ShellSessionRegistry, SshServer};
654    use crate::{PreparedSsh, RemoteLaunch};
655
656    #[test]
657    fn every_clone_of_a_registry_shares_its_live_server_set() {
658        let registry = ShellSessionRegistry::default();
659        let subagent = registry.clone();
660        let prod = SshServer {
661            name: "prod".to_string(),
662            target: "root@example.com".to_string(),
663        };
664        registry
665            .add_ssh_server(
666                prod.clone(),
667                PreparedSsh::new(None, RemoteLaunch::new("/opt/tools/bin", "/bin/bash")),
668            )
669            .unwrap();
670        assert_eq!(subagent.ssh_servers(), std::slice::from_ref(&prod));
671        assert_eq!(subagent.remove_ssh_server("prod"), Some(prod));
672        assert_eq!(registry.ssh_servers(), []);
673    }
674}