Skip to main content

adk_code/
container.rs

1//! Container code executor — persistent Docker-backed execution environment.
2//!
3//! [`DockerExecutor`] manages a persistent Docker container that survives across
4//! multiple [`execute`](CodeExecutor::execute) calls. Code is written to files
5//! inside the container's working directory and executed via `docker exec`,
6//! matching the lifecycle model of AutoGen's `DockerCommandLineCodeExecutor`.
7//!
8//! # Lifecycle
9//!
10//! ```text
11//! DockerExecutor::new(config)
12//!     │
13//!     ▼
14//!   start()  ──► creates & starts container, runs setup commands
15//!     │
16//!     ▼
17//!   execute() ──► writes code to file, exec's inside running container
18//!   execute() ──► reuses same container, accumulates workspace state
19//!   execute() ──► ...
20//!     │
21//!     ▼
22//!   stop()   ──► stops & removes container
23//! ```
24//!
25//! # Isolation Model
26//!
27//! The container's network mode, bind mounts, and environment are fixed by
28//! [`DockerConfig`] when it is created. Each request's [`SandboxPolicy`] is
29//! checked against them with [`DockerConfig::validate_sandbox_policy`], and a
30//! request stricter than the container is rejected before any code runs.
31//!
32//! | Capability | Enforced | Mechanism |
33//! |---|---|---|
34//! | Network policy | Yes | `NetworkPolicy::Disabled` requires a container created with network mode `none` |
35//! | Filesystem policy | Yes | Every bind mount must lie within the paths the policy grants |
36//! | Environment policy | Yes | Container variables must be on the allowlist; allowlisted host variables are passed to the exec |
37//! | Timeout | Yes | `tokio::time::timeout` on exec; the timed-out process is killed inside the container |
38//! | Privileges | Yes | All capabilities dropped, `no-new-privileges`, a process limit (each can be turned off) |
39//! | Output limits | Yes | Output past the request's byte limits is discarded as it streams |
40//! | Structured output | Yes | Last-line JSON extraction from stdout |
41//! | Persistent workspace | Yes | Container survives across executions |
42//! | Interactive sessions | No | Each execute is a separate exec |
43//!
44//! # Example
45//!
46//! ```rust,ignore
47//! # async fn example() -> Result<(), adk_code::ExecutionError> {
48//! use adk_code::{
49//!     CodeExecutor, DockerExecutor, DockerConfig,
50//!     ExecutionLanguage, ExecutionPayload, ExecutionRequest, SandboxPolicy,
51//! };
52//!
53//! let executor = DockerExecutor::new(DockerConfig::python())?;
54//! executor.start().await?;
55//!
56//! let result = executor.execute(ExecutionRequest {
57//!     language: ExecutionLanguage::Python,
58//!     payload: ExecutionPayload::Source {
59//!         code: "print('hello from persistent container')".to_string(),
60//!     },
61//!     argv: vec![],
62//!     stdin: None,
63//!     input: None,
64//!     sandbox: SandboxPolicy::strict_rust(),
65//!     identity: None,
66//! }).await?;
67//!
68//! // Container is still running — next execute reuses it
69//! executor.stop().await?;
70//! # Ok(())
71//! # }
72//! ```
73
74use std::path::{Component, Path, PathBuf};
75use std::process::Stdio;
76use std::time::Instant;
77
78use async_trait::async_trait;
79use tracing::{debug, info, warn};
80
81use crate::host_process;
82use crate::{
83    BackendCapabilities, CodeExecutor, EnvironmentPolicy, ExecutionError, ExecutionIsolation,
84    ExecutionLanguage, ExecutionPayload, ExecutionRequest, ExecutionResult, ExecutionStatus,
85    FilesystemPolicy, NetworkPolicy, SandboxPolicy, validate_request,
86};
87
88/// Configuration for the Docker executor.
89///
90/// # Example
91///
92/// ```rust
93/// use adk_code::DockerConfig;
94///
95/// let config = DockerConfig::python();
96/// assert_eq!(config.image, "python:3.12-slim");
97/// assert_eq!(config.work_dir, "/workspace");
98/// ```
99#[derive(Debug, Clone)]
100pub struct DockerConfig {
101    /// Container image to use.
102    pub image: String,
103    /// Working directory inside the container.
104    pub work_dir: String,
105    /// Setup commands to run after container creation (e.g., `pip install`).
106    pub setup_commands: Vec<String>,
107    /// Extra environment variables to set in the container.
108    pub environment: Vec<String>,
109    /// Bind mounts in `host:container[:ro]` format.
110    pub bind_mounts: Vec<String>,
111    /// Whether to disable network access.
112    pub network_disabled: bool,
113    /// Container name prefix (a random suffix is appended).
114    pub container_name_prefix: String,
115    /// Whether to auto-start on first execute if not already running.
116    pub auto_start: bool,
117    /// Whether to auto-stop and remove the container on drop.
118    pub auto_remove: bool,
119    /// Drop every Linux capability (`CapDrop: ["ALL"]`). Default: `true`.
120    ///
121    /// Setup commands that switch users, such as `apt-get`, need it turned off.
122    pub drop_capabilities: bool,
123    /// Forbid gaining privileges, such as through setuid binaries
124    /// (`SecurityOpt: ["no-new-privileges"]`). Default: `true`.
125    pub no_new_privileges: bool,
126    /// Most processes the container may run (`PidsLimit`), which stops a fork bomb;
127    /// `None` sets no limit. Default: [`DEFAULT_PIDS_LIMIT`].
128    pub pids_limit: Option<u32>,
129}
130
131impl DockerConfig {
132    /// Python 3.12 preset.
133    pub fn python() -> Self {
134        Self {
135            image: "python:3.12-slim".to_string(),
136            work_dir: "/workspace".to_string(),
137            setup_commands: vec![],
138            environment: vec![],
139            bind_mounts: vec![],
140            network_disabled: true,
141            container_name_prefix: "adk-python".to_string(),
142            auto_start: true,
143            auto_remove: true,
144            drop_capabilities: true,
145            no_new_privileges: true,
146            pids_limit: Some(DEFAULT_PIDS_LIMIT),
147        }
148    }
149
150    /// Node.js 20 preset.
151    pub fn node() -> Self {
152        Self {
153            image: "node:20-slim".to_string(),
154            work_dir: "/workspace".to_string(),
155            setup_commands: vec![],
156            environment: vec![],
157            bind_mounts: vec![],
158            network_disabled: true,
159            container_name_prefix: "adk-node".to_string(),
160            auto_start: true,
161            auto_remove: true,
162            drop_capabilities: true,
163            no_new_privileges: true,
164            pids_limit: Some(DEFAULT_PIDS_LIMIT),
165        }
166    }
167
168    /// Custom image preset.
169    pub fn custom(image: impl Into<String>) -> Self {
170        Self {
171            image: image.into(),
172            work_dir: "/workspace".to_string(),
173            setup_commands: vec![],
174            environment: vec![],
175            bind_mounts: vec![],
176            network_disabled: true,
177            container_name_prefix: "adk-custom".to_string(),
178            auto_start: true,
179            auto_remove: true,
180            drop_capabilities: true,
181            no_new_privileges: true,
182            pids_limit: Some(DEFAULT_PIDS_LIMIT),
183        }
184    }
185
186    /// Add a setup command to run after container creation.
187    pub fn setup_command(mut self, cmd: impl Into<String>) -> Self {
188        self.setup_commands.push(cmd.into());
189        self
190    }
191
192    /// Add a pip install command for Python dependencies.
193    pub fn pip_install(self, packages: &[&str]) -> Self {
194        self.setup_command(format!("pip install --quiet {}", packages.join(" ")))
195    }
196
197    /// Add an npm install command for Node.js dependencies.
198    pub fn npm_install(self, packages: &[&str]) -> Self {
199        self.setup_command(format!("npm install --silent {}", packages.join(" ")))
200    }
201
202    /// Enable network access (disabled by default).
203    pub fn with_network(mut self) -> Self {
204        self.network_disabled = false;
205        self
206    }
207
208    /// Add a bind mount.
209    pub fn bind_mount(mut self, mount: impl Into<String>) -> Self {
210        self.bind_mounts.push(mount.into());
211        self
212    }
213
214    /// Add an environment variable.
215    pub fn env(mut self, var: impl Into<String>) -> Self {
216        self.environment.push(var.into());
217        self
218    }
219
220    /// Checks that a container created from this configuration satisfies `policy`.
221    ///
222    /// A persistent container's network mode, bind mounts, and environment are
223    /// fixed when it is created, so a request cannot narrow them afterwards.
224    /// `DockerExecutor` calls this before every execution and rejects a request
225    /// whose policy is stricter than the container:
226    ///
227    /// | Policy | Satisfied when |
228    /// |---|---|
229    /// | `NetworkPolicy::Disabled` | `network_disabled` is `true` |
230    /// | `FilesystemPolicy::None` | there are no bind mounts |
231    /// | `FilesystemPolicy::WorkspaceReadOnly { root }` | every bind mount is read-only (`:ro`) and its host path lies under `root` |
232    /// | `FilesystemPolicy::WorkspaceReadWrite { root }` | every bind mount's host path lies under `root` |
233    /// | `FilesystemPolicy::Paths { read_only, read_write }` | every bind mount lies under a `read_write` path, or is read-only and lies under a `read_only` path |
234    /// | `EnvironmentPolicy::None` | `environment` is empty |
235    /// | `EnvironmentPolicy::AllowList(names)` | every `environment` entry's name is in `names` |
236    ///
237    /// Bind-mount host paths must be absolute and free of `..` components, so a
238    /// named volume never satisfies a filesystem policy. Variables defined by the
239    /// image itself (`PATH`, `LANG`) come from the image, not the host, and are
240    /// not checked.
241    ///
242    /// # Errors
243    ///
244    /// Returns [`ExecutionError::UnsupportedPolicy`] naming the first setting
245    /// that exceeds the policy.
246    ///
247    /// # Example
248    ///
249    /// ```rust
250    /// use adk_code::{DockerConfig, NetworkPolicy, SandboxPolicy};
251    ///
252    /// let strict = SandboxPolicy::strict_rust();
253    /// assert!(DockerConfig::python().validate_sandbox_policy(&strict).is_ok());
254    ///
255    /// // A networked container cannot honour a request that disables the network.
256    /// let networked = DockerConfig::python().with_network();
257    /// assert!(networked.validate_sandbox_policy(&strict).is_err());
258    ///
259    /// let allows_network = SandboxPolicy { network: NetworkPolicy::Enabled, ..strict };
260    /// assert!(networked.validate_sandbox_policy(&allows_network).is_ok());
261    /// ```
262    pub fn validate_sandbox_policy(&self, policy: &SandboxPolicy) -> Result<(), ExecutionError> {
263        if matches!(policy.network, NetworkPolicy::Disabled) && !self.network_disabled {
264            return Err(ExecutionError::UnsupportedPolicy(
265                "the policy disables network access, but the container was created with network \
266                 access; drop `with_network()` from the DockerConfig or use \
267                 `NetworkPolicy::Enabled`"
268                    .to_string(),
269            ));
270        }
271
272        for mount in &self.bind_mounts {
273            // `host:container[:options]`; a Windows drive letter adds a colon to the host part.
274            let parts: Vec<&str> = mount.split(':').collect();
275            let has_drive_letter = parts.len() > 2
276                && parts[0].len() == 1
277                && parts[0].chars().all(|c| c.is_ascii_alphabetic());
278            let (host, rest) = if has_drive_letter {
279                (&mount[..parts[0].len() + 1 + parts[1].len()], &parts[2..])
280            } else {
281                (parts[0], &parts[1..])
282            };
283            let read_only = rest
284                .get(1)
285                .is_some_and(|options| options.split(',').any(|o| o == "ro" || o == "readonly"));
286
287            // `has_root` rather than `is_absolute`: on Windows a Linux-container mount such as
288            // `/srv/data` is rooted but not absolute, and containment only needs the path to be
289            // anchored and free of `..` for `starts_with` against the policy root to hold.
290            let host = Path::new(host);
291            let confined = host.has_root()
292                && !host.components().any(|component| matches!(component, Component::ParentDir));
293            let under = |root: &PathBuf| confined && host.starts_with(root);
294
295            let permitted = match &policy.filesystem {
296                FilesystemPolicy::None => false,
297                FilesystemPolicy::WorkspaceReadOnly { root } => read_only && under(root),
298                FilesystemPolicy::WorkspaceReadWrite { root } => under(root),
299                FilesystemPolicy::Paths { read_only: read_only_paths, read_write } => {
300                    read_write.iter().any(under) || (read_only && read_only_paths.iter().any(under))
301                }
302            };
303            if !permitted {
304                return Err(ExecutionError::UnsupportedPolicy(format!(
305                    "bind mount `{mount}` exceeds the filesystem policy {:?}; remove the mount \
306                     or grant its host path in the policy",
307                    policy.filesystem
308                )));
309            }
310        }
311
312        for entry in &self.environment {
313            let name = entry.split_once('=').map_or(entry.as_str(), |(name, _)| name);
314            let allowed = match &policy.environment {
315                EnvironmentPolicy::None => false,
316                EnvironmentPolicy::AllowList(names) => names.iter().any(|allowed| allowed == name),
317            };
318            if !allowed {
319                return Err(ExecutionError::UnsupportedPolicy(format!(
320                    "container environment variable `{name}` is not allowed by the environment \
321                     policy; remove it from the DockerConfig or add it to \
322                     `EnvironmentPolicy::AllowList`"
323                )));
324            }
325        }
326
327        Ok(())
328    }
329}
330
331impl Default for DockerConfig {
332    fn default() -> Self {
333        Self::python()
334    }
335}
336
337// ── Docker SDK implementation (behind `docker` feature) ────────────────
338
339#[cfg(feature = "docker")]
340mod docker_impl {
341    use super::*;
342    use bollard::Docker;
343    use bollard::container::{
344        Config, CreateContainerOptions, RemoveContainerOptions, StartContainerOptions,
345    };
346    use bollard::exec::{CreateExecOptions, StartExecResults};
347    use futures::StreamExt;
348    use rand::Rng;
349    use tokio::sync::RwLock;
350
351    /// Output kept from the executor's own commands (file writes, setup).
352    const SETUP_OUTPUT_LIMITS: (usize, usize) = (64 * 1024, 64 * 1024);
353
354    /// State of the managed container.
355    #[derive(Debug)]
356    struct ContainerState {
357        /// Docker container ID.
358        id: String,
359        /// Whether the container is currently running.
360        running: bool,
361        /// Counter for generating unique filenames.
362        file_counter: u64,
363    }
364
365    /// Persistent Docker-backed code execution environment.
366    ///
367    /// Creates a container once via [`start`](CodeExecutor::start), keeps it running,
368    /// and executes code via `docker exec` inside the running container. This matches
369    /// the lifecycle model of AutoGen's `DockerCommandLineCodeExecutor`.
370    ///
371    /// # Sandbox Policy
372    ///
373    /// The container's network mode, bind mounts, and environment come from
374    /// [`DockerConfig`] and cannot change per request. [`execute`](CodeExecutor::execute)
375    /// rejects with [`ExecutionError::UnsupportedPolicy`] any request whose policy
376    /// the container does not satisfy; see [`DockerConfig::validate_sandbox_policy`].
377    /// Variables named by an [`EnvironmentPolicy::AllowList`] are passed from the
378    /// host to that request's exec.
379    ///
380    /// # Cleanup
381    ///
382    /// Call [`cleanup()`](Self::cleanup) explicitly before dropping to ensure
383    /// reliable container removal. The [`Drop`] implementation is best-effort
384    /// and requires a tokio runtime to be available.
385    ///
386    /// # Example
387    ///
388    /// ```rust,no_run
389    /// # async fn example() -> Result<(), adk_code::ExecutionError> {
390    /// use adk_code::{CodeExecutor, DockerExecutor, DockerConfig};
391    ///
392    /// let executor = DockerExecutor::new(DockerConfig::python())?;
393    /// executor.start().await?;
394    /// assert!(executor.is_running().await);
395    ///
396    /// // Prefer explicit cleanup over relying on Drop
397    /// executor.cleanup().await?;
398    /// # Ok(())
399    /// # }
400    /// ```
401    pub struct DockerExecutor {
402        config: DockerConfig,
403        docker: Docker,
404        state: RwLock<Option<ContainerState>>,
405    }
406
407    impl std::fmt::Debug for DockerExecutor {
408        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
409            f.debug_struct("DockerExecutor").field("config", &self.config).finish()
410        }
411    }
412
413    impl DockerExecutor {
414        /// Create a new Docker executor with the given configuration.
415        ///
416        /// This does NOT start the container — call [`start`](CodeExecutor::start)
417        /// or set `auto_start: true` (the default) to have it start on first execute.
418        /// # Errors
419        ///
420        /// Returns [`ExecutionError::InternalError`] if the Docker daemon is
421        /// unreachable (not installed, not running, or socket permission denied).
422        pub fn new(config: DockerConfig) -> std::result::Result<Self, ExecutionError> {
423            let docker = Docker::connect_with_local_defaults().map_err(|e| {
424                ExecutionError::InternalError(format!(
425                    "failed to connect to Docker daemon: {e}. Is Docker installed and running?"
426                ))
427            })?;
428            Ok(Self { config, docker, state: RwLock::new(None) })
429        }
430
431        /// Create with a custom Docker connection.
432        pub fn with_docker(config: DockerConfig, docker: Docker) -> Self {
433            Self { config, docker, state: RwLock::new(None) }
434        }
435
436        /// Explicitly stop and remove the Docker container.
437        ///
438        /// Prefer calling this method before dropping the executor to ensure
439        /// reliable cleanup. The [`Drop`] implementation is best-effort and may
440        /// not work if no tokio runtime is available.
441        pub async fn cleanup(&self) -> Result<(), ExecutionError> {
442            let mut state = self.state.write().await;
443            if let Some(s) = state.take() {
444                info!(container_id = %s.id, "cleaning up container");
445                self.docker
446                    .remove_container(
447                        &s.id,
448                        Some(RemoveContainerOptions { force: true, ..Default::default() }),
449                    )
450                    .await
451                    .map_err(|e| {
452                        ExecutionError::ExecutionFailed(format!("failed to remove container: {e}"))
453                    })?;
454            }
455            Ok(())
456        }
457
458        /// The container's network, mounts and privilege limits.
459        fn host_config(&self) -> bollard::models::HostConfig {
460            let config = &self.config;
461            bollard::models::HostConfig {
462                network_mode: config.network_disabled.then(|| "none".to_string()),
463                binds: (!config.bind_mounts.is_empty()).then(|| config.bind_mounts.clone()),
464                cap_drop: config.drop_capabilities.then(|| vec!["ALL".to_string()]),
465                security_opt: config
466                    .no_new_privileges
467                    .then(|| vec!["no-new-privileges".to_string()]),
468                pids_limit: config.pids_limit.map(i64::from),
469                ..Default::default()
470            }
471        }
472
473        /// Generate a unique container name.
474        fn container_name(&self) -> String {
475            let suffix: u32 = rand::rng().random_range(100_000..999_999);
476            format!("{}-{suffix}", self.config.container_name_prefix)
477        }
478
479        /// Get the file extension for a language.
480        fn file_extension(lang: &ExecutionLanguage) -> &'static str {
481            match lang {
482                ExecutionLanguage::Python => "py",
483                ExecutionLanguage::JavaScript => "js",
484                ExecutionLanguage::Rust => "rs",
485                ExecutionLanguage::Command => "sh",
486                ExecutionLanguage::Wasm => "wasm",
487            }
488        }
489
490        /// Get the execution command for a language and filename.
491        fn exec_command(lang: &ExecutionLanguage, filename: &str) -> Vec<String> {
492            match lang {
493                ExecutionLanguage::Python => {
494                    vec!["python3".to_string(), filename.to_string()]
495                }
496                ExecutionLanguage::JavaScript => {
497                    vec!["node".to_string(), filename.to_string()]
498                }
499                ExecutionLanguage::Command => {
500                    vec!["sh".to_string(), filename.to_string()]
501                }
502                _ => vec![],
503            }
504        }
505
506        /// Write a file inside the running container.
507        async fn write_file(
508            &self,
509            container_id: &str,
510            path: &str,
511            content: &str,
512        ) -> Result<(), ExecutionError> {
513            // Use a heredoc-style approach to write file content safely.
514            // Base64 encode to avoid shell escaping issues.
515            let encoded = base64_encode(content.as_bytes());
516            let cmd = vec![
517                "sh".to_string(),
518                "-c".to_string(),
519                format!("echo '{encoded}' | base64 -d > {path}"),
520            ];
521            self.exec_in_container(container_id, &cmd, None, None, SETUP_OUTPUT_LIMITS).await?;
522            Ok(())
523        }
524
525        /// Execute a command inside the running container and capture output.
526        ///
527        /// `env` entries (`KEY=VALUE`) are added to the container's own environment
528        /// for this exec only. Output past `limits` (stdout, stderr bytes) is discarded
529        /// while the stream is drained. When `timeout` passes, the process is killed
530        /// inside the container: ending the exec stream alone leaves it running.
531        async fn exec_in_container(
532            &self,
533            container_id: &str,
534            cmd: &[String],
535            env: Option<Vec<String>>,
536            timeout: Option<std::time::Duration>,
537            limits: (usize, usize),
538        ) -> Result<ExecOutput, ExecutionError> {
539            let pid_file =
540                timeout.map(|_| format!("/tmp/.adk-exec-{}.pid", super::container_name("pid")));
541            let cmd = match &pid_file {
542                Some(pid_file) => with_pid_file(pid_file, cmd),
543                None => cmd.to_vec(),
544            };
545            let exec_output = self.run_exec(container_id, cmd, env, limits);
546
547            match (timeout, pid_file) {
548                (Some(dur), Some(pid_file)) => match tokio::time::timeout(dur, exec_output).await {
549                    Ok(result) => result,
550                    Err(_) => {
551                        self.kill_exec(container_id, &pid_file).await;
552                        Err(ExecutionError::Timeout(dur.as_millis() as u64))
553                    }
554                },
555                _ => exec_output.await,
556            }
557        }
558
559        /// Runs one exec to completion and captures its output within `limits`.
560        async fn run_exec(
561            &self,
562            container_id: &str,
563            cmd: Vec<String>,
564            env: Option<Vec<String>>,
565            limits: (usize, usize),
566        ) -> Result<ExecOutput, ExecutionError> {
567            let exec = self
568                .docker
569                .create_exec(
570                    container_id,
571                    CreateExecOptions {
572                        cmd: Some(cmd),
573                        env,
574                        attach_stdout: Some(true),
575                        attach_stderr: Some(true),
576                        working_dir: Some(self.config.work_dir.clone()),
577                        ..Default::default()
578                    },
579                )
580                .await
581                .map_err(|e| {
582                    ExecutionError::ExecutionFailed(format!("failed to create exec: {e}"))
583                })?;
584
585            {
586                match self.docker.start_exec(&exec.id, None).await {
587                    Ok(StartExecResults::Attached { mut output, .. }) => {
588                        let mut captured = ExecOutput::default();
589
590                        while let Some(chunk) = output.next().await {
591                            match chunk {
592                                Ok(bollard::container::LogOutput::StdOut { message }) => {
593                                    push_bounded(
594                                        &mut captured.stdout,
595                                        &mut captured.stdout_truncated,
596                                        &message,
597                                        limits.0,
598                                    );
599                                }
600                                Ok(bollard::container::LogOutput::StdErr { message }) => {
601                                    push_bounded(
602                                        &mut captured.stderr,
603                                        &mut captured.stderr_truncated,
604                                        &message,
605                                        limits.1,
606                                    );
607                                }
608                                Ok(_) => {}
609                                Err(e) => {
610                                    return Err(ExecutionError::ExecutionFailed(format!(
611                                        "exec stream error: {e}"
612                                    )));
613                                }
614                            }
615                        }
616
617                        // Get exit code.
618                        let inspect = self.docker.inspect_exec(&exec.id).await.map_err(|e| {
619                            ExecutionError::ExecutionFailed(format!("failed to inspect exec: {e}"))
620                        })?;
621                        captured.exit_code = inspect.exit_code;
622
623                        Ok(captured)
624                    }
625                    Ok(StartExecResults::Detached) => Ok(ExecOutput::default()),
626                    Err(e) => {
627                        Err(ExecutionError::ExecutionFailed(format!("failed to start exec: {e}")))
628                    }
629                }
630            }
631        }
632
633        /// Kills the process group, or failing that the process, recorded in `pid_file`.
634        async fn kill_exec(&self, container_id: &str, pid_file: &str) {
635            let kill = vec![
636                "sh".to_string(),
637                "-c".to_string(),
638                r#"pid=$(cat "$0") && { kill -KILL -- "-$pid" 2>/dev/null || kill -KILL "$pid"; }"#
639                    .to_string(),
640                pid_file.to_string(),
641            ];
642            let killed = tokio::time::timeout(
643                super::KILL_TIMEOUT,
644                self.run_exec(container_id, kill, None, (0, 4096)),
645            )
646            .await;
647            match killed {
648                Ok(Ok(output)) if output.exit_code == Some(0) => {}
649                Ok(Ok(output)) => warn!(
650                    container_id = %container_id,
651                    exit_code = ?output.exit_code,
652                    stderr = %output.stderr,
653                    "killing the timed-out exec failed"
654                ),
655                Ok(Err(error)) => {
656                    warn!(container_id = %container_id, %error, "killing the timed-out exec failed")
657                }
658                Err(_) => {
659                    warn!(container_id = %container_id, "killing the timed-out exec did not finish")
660                }
661            }
662        }
663    }
664
665    /// What one exec printed, within the request's limits.
666    #[derive(Debug, Default)]
667    struct ExecOutput {
668        stdout: String,
669        stderr: String,
670        exit_code: Option<i64>,
671        stdout_truncated: bool,
672        stderr_truncated: bool,
673    }
674
675    /// `cmd` run through a shell that first writes its PID to `pid_file`; `exec` keeps
676    /// the PID for `cmd` itself.
677    fn with_pid_file(pid_file: &str, cmd: &[String]) -> Vec<String> {
678        let mut wrapped = vec![
679            "sh".to_string(),
680            "-c".to_string(),
681            r#"echo $$ > "$0" && exec "$@""#.to_string(),
682            pid_file.to_string(),
683        ];
684        wrapped.extend(cmd.iter().cloned());
685        wrapped
686    }
687
688    /// Appends `chunk` to `buffer` without taking it past `limit` bytes.
689    fn push_bounded(buffer: &mut String, truncated: &mut bool, chunk: &[u8], limit: usize) {
690        if *truncated {
691            return;
692        }
693        let text = String::from_utf8_lossy(chunk);
694        let room = limit.saturating_sub(buffer.len());
695        if text.len() <= room {
696            buffer.push_str(&text);
697        } else {
698            buffer.push_str(&text[..text.floor_char_boundary(room)]);
699            *truncated = true;
700        }
701    }
702
703    #[async_trait]
704    impl CodeExecutor for DockerExecutor {
705        fn name(&self) -> &str {
706            "docker"
707        }
708
709        fn capabilities(&self) -> BackendCapabilities {
710            BackendCapabilities {
711                isolation: ExecutionIsolation::ContainerPersistent,
712                enforce_network_policy: true,
713                enforce_filesystem_policy: true,
714                enforce_environment_policy: true,
715                enforce_timeout: true,
716                supports_structured_output: true,
717                supports_process_execution: true,
718                supports_persistent_workspace: true,
719                supports_interactive_sessions: false,
720            }
721        }
722
723        fn supports_language(&self, lang: &ExecutionLanguage) -> bool {
724            matches!(
725                lang,
726                ExecutionLanguage::Python
727                    | ExecutionLanguage::JavaScript
728                    | ExecutionLanguage::Command
729            )
730        }
731
732        async fn start(&self) -> Result<(), ExecutionError> {
733            let mut state = self.state.write().await;
734            if state.as_ref().is_some_and(|s| s.running) {
735                return Ok(());
736            }
737
738            let name = self.container_name();
739            info!(image = %self.config.image, container = %name, "creating container");
740
741            let host_config = self.host_config();
742
743            let env = if self.config.environment.is_empty() {
744                None
745            } else {
746                Some(self.config.environment.clone())
747            };
748
749            let container_config = Config {
750                image: Some(self.config.image.clone()),
751                working_dir: Some(self.config.work_dir.clone()),
752                env,
753                host_config: Some(host_config),
754                // Keep container alive with a long sleep.
755                cmd: Some(vec!["sleep".to_string(), "infinity".to_string()]),
756                tty: Some(false),
757                ..Default::default()
758            };
759
760            let create_opts = CreateContainerOptions { name: name.clone(), ..Default::default() };
761
762            let response =
763                self.docker.create_container(Some(create_opts), container_config).await.map_err(
764                    |e| ExecutionError::ExecutionFailed(format!("failed to create container: {e}")),
765                )?;
766
767            let container_id = response.id;
768            debug!(container_id = %container_id, "container created");
769
770            // Start the container.
771            self.docker
772                .start_container(&container_id, None::<StartContainerOptions<String>>)
773                .await
774                .map_err(|e| {
775                    ExecutionError::ExecutionFailed(format!("failed to start container: {e}"))
776                })?;
777
778            info!(container_id = %container_id, "container started");
779
780            // Create workspace directory.
781            let mkdir_cmd =
782                vec!["mkdir".to_string(), "-p".to_string(), self.config.work_dir.clone()];
783            let _ = self
784                .exec_in_container(&container_id, &mkdir_cmd, None, None, SETUP_OUTPUT_LIMITS)
785                .await;
786
787            // Run setup commands.
788            for setup_cmd in &self.config.setup_commands {
789                info!(cmd = %setup_cmd, "running setup command");
790                let cmd = vec!["sh".to_string(), "-c".to_string(), setup_cmd.clone()];
791                let ExecOutput { stderr, exit_code, .. } = self
792                    .exec_in_container(&container_id, &cmd, None, None, SETUP_OUTPUT_LIMITS)
793                    .await?;
794
795                if exit_code != Some(0) {
796                    warn!(
797                        exit_code = ?exit_code,
798                        stderr = %stderr,
799                        "setup command failed"
800                    );
801                    // Clean up on setup failure.
802                    let _ = self
803                        .docker
804                        .remove_container(
805                            &container_id,
806                            Some(RemoveContainerOptions { force: true, ..Default::default() }),
807                        )
808                        .await;
809                    return Err(ExecutionError::ExecutionFailed(format!(
810                        "setup command failed: {setup_cmd}\nstderr: {stderr}"
811                    )));
812                }
813            }
814
815            *state = Some(ContainerState { id: container_id, running: true, file_counter: 0 });
816
817            Ok(())
818        }
819
820        async fn stop(&self) -> Result<(), ExecutionError> {
821            let mut state = self.state.write().await;
822            if let Some(s) = state.take() {
823                info!(container_id = %s.id, "stopping container");
824                let _ = self
825                    .docker
826                    .remove_container(
827                        &s.id,
828                        Some(RemoveContainerOptions { force: true, ..Default::default() }),
829                    )
830                    .await;
831            }
832            Ok(())
833        }
834
835        async fn is_running(&self) -> bool {
836            self.state.read().await.as_ref().is_some_and(|s| s.running)
837        }
838
839        async fn execute(
840            &self,
841            request: ExecutionRequest,
842        ) -> Result<ExecutionResult, ExecutionError> {
843            let supported = [
844                ExecutionLanguage::Python,
845                ExecutionLanguage::JavaScript,
846                ExecutionLanguage::Command,
847            ];
848            validate_request(&self.capabilities(), &supported, &request)?;
849            self.config.validate_sandbox_policy(&request.sandbox)?;
850
851            let code = match &request.payload {
852                ExecutionPayload::Source { code } if code.trim().is_empty() => {
853                    return Err(ExecutionError::InvalidRequest("empty source code".to_string()));
854                }
855                ExecutionPayload::Source { code } => code.clone(),
856                ExecutionPayload::GuestModule { .. } => {
857                    return Err(ExecutionError::InvalidRequest(
858                        "DockerExecutor does not support guest modules".to_string(),
859                    ));
860                }
861            };
862
863            // Auto-start if configured and not running.
864            if self.config.auto_start && !self.is_running().await {
865                self.start().await?;
866            }
867
868            // Get container ID and increment file counter.
869            let (container_id, filename) = {
870                let mut state = self.state.write().await;
871                let s = state.as_mut().ok_or_else(|| {
872                    ExecutionError::ExecutionFailed(
873                        "container not started — call start() first".to_string(),
874                    )
875                })?;
876                s.file_counter += 1;
877                let ext = Self::file_extension(&request.language);
878                let filename = format!("{}/code_{}.{ext}", self.config.work_dir, s.file_counter);
879                (s.id.clone(), filename)
880            };
881
882            let start = Instant::now();
883
884            // Write code to file inside container.
885            self.write_file(&container_id, &filename, &code).await?;
886
887            // If there's structured input, write it as a JSON file.
888            if let Some(ref input) = request.input {
889                let input_json = serde_json::to_string(input).unwrap_or_default();
890                let input_path = format!("{}/input.json", self.config.work_dir);
891                self.write_file(&container_id, &input_path, &input_json).await?;
892            }
893
894            // Build execution command.
895            let exec_cmd = Self::exec_command(&request.language, &filename);
896            if exec_cmd.is_empty() {
897                return Err(ExecutionError::UnsupportedLanguage(format!("{}", request.language)));
898            }
899
900            debug!(
901                container_id = %container_id,
902                language = %request.language,
903                filename = %filename,
904                "executing code in container"
905            );
906
907            // Mirrors `docker run --env NAME`: allowlisted variables carry the host's values.
908            let exec_env = host_process::allowlisted_host_env(&request.sandbox.environment)
909                .into_iter()
910                .map(|(name, value)| format!("{name}={}", value.to_string_lossy()))
911                .collect::<Vec<_>>();
912
913            // Execute with timeout.
914            let ExecOutput { stdout, stderr, exit_code, stdout_truncated, stderr_truncated } = self
915                .exec_in_container(
916                    &container_id,
917                    &exec_cmd,
918                    Some(exec_env),
919                    Some(request.sandbox.timeout),
920                    (request.sandbox.max_stdout_bytes, request.sandbox.max_stderr_bytes),
921                )
922                .await?;
923
924            let duration_ms = start.elapsed().as_millis() as u64;
925
926            let (structured_output, display_stdout) = extract_structured_output(&stdout);
927
928            let status = match exit_code {
929                Some(0) => ExecutionStatus::Success,
930                _ => ExecutionStatus::Failed,
931            };
932
933            info!(
934                exit_code = ?exit_code,
935                duration_ms,
936                has_structured_output = structured_output.is_some(),
937                "container execution completed"
938            );
939
940            Ok(ExecutionResult {
941                status,
942                stdout: display_stdout,
943                stderr,
944                output: structured_output,
945                exit_code: exit_code.map(|c| c as i32),
946                stdout_truncated,
947                stderr_truncated,
948                duration_ms,
949                metadata: None,
950            })
951        }
952    }
953
954    impl Drop for DockerExecutor {
955        fn drop(&mut self) {
956            if self.config.auto_remove {
957                // Best-effort cleanup — we can't await in drop, so spawn a task
958                // only if a tokio runtime is available.
959                if let Some(state) = self.state.get_mut().take() {
960                    let docker = self.docker.clone();
961                    let container_id = state.id;
962                    match tokio::runtime::Handle::try_current() {
963                        Ok(handle) => {
964                            handle.spawn(async move {
965                                let _ = docker
966                                    .remove_container(
967                                        &container_id,
968                                        Some(RemoveContainerOptions {
969                                            force: true,
970                                            ..Default::default()
971                                        }),
972                                    )
973                                    .await;
974                            });
975                        }
976                        Err(_) => {
977                            tracing::warn!(
978                                container_id = %container_id,
979                                "no tokio runtime available during DockerExecutor drop, \
980                                 container may leak. Call cleanup() explicitly before dropping."
981                            );
982                        }
983                    }
984                }
985            }
986        }
987    }
988
989    /// Simple base64 encoder (no padding issues with shell).
990    fn base64_encode(data: &[u8]) -> String {
991        const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
992        let mut result = String::with_capacity(data.len().div_ceil(3) * 4);
993        for chunk in data.chunks(3) {
994            let b0 = chunk[0] as u32;
995            let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
996            let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
997            let triple = (b0 << 16) | (b1 << 8) | b2;
998            result.push(CHARS[((triple >> 18) & 0x3F) as usize] as char);
999            result.push(CHARS[((triple >> 12) & 0x3F) as usize] as char);
1000            if chunk.len() > 1 {
1001                result.push(CHARS[((triple >> 6) & 0x3F) as usize] as char);
1002            } else {
1003                result.push('=');
1004            }
1005            if chunk.len() > 2 {
1006                result.push(CHARS[(triple & 0x3F) as usize] as char);
1007            } else {
1008                result.push('=');
1009            }
1010        }
1011        result
1012    }
1013
1014    #[cfg(test)]
1015    mod tests {
1016        use super::*;
1017
1018        #[test]
1019        fn the_container_drops_privileges_and_limits_processes_unless_opted_out() {
1020            let docker = Docker::connect_with_local_defaults().expect("client");
1021            let hardened = DockerExecutor::with_docker(DockerConfig::python(), docker.clone());
1022            let host = hardened.host_config();
1023            assert_eq!(host.cap_drop, Some(vec!["ALL".to_string()]));
1024            assert_eq!(host.security_opt, Some(vec!["no-new-privileges".to_string()]));
1025            assert_eq!(host.pids_limit, Some(i64::from(DEFAULT_PIDS_LIMIT)));
1026            assert_eq!(host.network_mode.as_deref(), Some("none"));
1027
1028            let config = DockerConfig {
1029                drop_capabilities: false,
1030                no_new_privileges: false,
1031                pids_limit: None,
1032                ..DockerConfig::python()
1033            };
1034            let host = DockerExecutor::with_docker(config, docker).host_config();
1035            assert_eq!((host.cap_drop, host.security_opt, host.pids_limit), (None, None, None));
1036        }
1037
1038        #[test]
1039        fn exec_commands_record_their_pid_and_keep_it() {
1040            let cmd = with_pid_file("/tmp/x.pid", &["python3".to_string(), "a.py".to_string()]);
1041            assert_eq!(
1042                cmd,
1043                ["sh", "-c", r#"echo $$ > "$0" && exec "$@""#, "/tmp/x.pid", "python3", "a.py"]
1044            );
1045        }
1046
1047        #[test]
1048        fn output_past_the_limit_is_discarded_as_it_arrives() {
1049            let (mut buffer, mut truncated) = (String::new(), false);
1050            push_bounded(&mut buffer, &mut truncated, b"abc", 5);
1051            assert_eq!((buffer.as_str(), truncated), ("abc", false));
1052            push_bounded(&mut buffer, &mut truncated, "déf".as_bytes(), 5);
1053            // "é" would cross the limit, so the cut falls before it.
1054            assert_eq!((buffer.as_str(), truncated), ("abcd", true));
1055            push_bounded(&mut buffer, &mut truncated, b"more", 5);
1056            assert_eq!(buffer, "abcd");
1057        }
1058    }
1059}
1060
1061#[cfg(feature = "docker")]
1062pub use docker_impl::DockerExecutor;
1063
1064// ── CLI-based fallback (always available) ──────────────────────────────
1065
1066/// Configuration for the CLI-based container command executor.
1067///
1068/// This is the fallback executor that shells out to `docker run` for each
1069/// execution. For production use, prefer `DockerExecutor` (behind the
1070/// `docker` feature) which uses persistent containers.
1071///
1072/// # Example
1073///
1074/// ```rust
1075/// use adk_code::ContainerConfig;
1076///
1077/// let config = ContainerConfig::default();
1078/// assert_eq!(config.runtime, "docker");
1079/// ```
1080#[derive(Debug, Clone)]
1081pub struct ContainerConfig {
1082    /// Container runtime binary (e.g., `"docker"`, `"podman"`).
1083    pub runtime: String,
1084    /// Default container image when not overridden per-request.
1085    pub default_image: String,
1086    /// Extra flags passed to the container runtime `run` command.
1087    pub extra_flags: Vec<String>,
1088    /// Whether to automatically remove the container after execution.
1089    pub auto_remove: bool,
1090    /// Drop every Linux capability (`--cap-drop=ALL`). Default: `true`.
1091    pub drop_capabilities: bool,
1092    /// Forbid gaining privileges, such as through setuid binaries
1093    /// (`--security-opt=no-new-privileges`). Default: `true`.
1094    pub no_new_privileges: bool,
1095    /// Most processes the container may run (`--pids-limit`), which stops a fork bomb;
1096    /// `None` sets no limit. Default: [`DEFAULT_PIDS_LIMIT`].
1097    pub pids_limit: Option<u32>,
1098}
1099
1100/// Default process limit for containers the executors create.
1101pub const DEFAULT_PIDS_LIMIT: u32 = 256;
1102
1103impl Default for ContainerConfig {
1104    fn default() -> Self {
1105        Self {
1106            runtime: "docker".to_string(),
1107            default_image: "python:3.12-slim".to_string(),
1108            extra_flags: vec![],
1109            auto_remove: true,
1110            drop_capabilities: true,
1111            no_new_privileges: true,
1112            pids_limit: Some(DEFAULT_PIDS_LIMIT),
1113        }
1114    }
1115}
1116
1117/// CLI-based container executor that shells out to `docker run` per execution.
1118///
1119/// Each [`execute`](CodeExecutor::execute) call spawns a new ephemeral container.
1120/// This is simpler but less efficient than `DockerExecutor` which reuses a
1121/// persistent container.
1122///
1123/// Each container is named, so it can be stopped: when the request's timeout passes,
1124/// or the call is dropped, the executor runs `{runtime} kill {name}`, because ending
1125/// the `docker run` client process leaves the container running. Containers run with
1126/// every capability dropped, `no-new-privileges` and a process limit unless
1127/// [`ContainerConfig`] turns them off.
1128///
1129/// For production use, prefer `DockerExecutor` (behind the `docker` feature).
1130///
1131/// # Example
1132///
1133/// ```rust
1134/// use adk_code::{CodeExecutor, ContainerCommandExecutor, ContainerConfig, ExecutionIsolation};
1135///
1136/// let executor = ContainerCommandExecutor::default();
1137/// assert_eq!(executor.name(), "container-command");
1138/// assert_eq!(executor.capabilities().isolation, ExecutionIsolation::ContainerEphemeral);
1139/// ```
1140#[derive(Debug, Clone)]
1141pub struct ContainerCommandExecutor {
1142    config: ContainerConfig,
1143}
1144
1145impl ContainerCommandExecutor {
1146    /// Create a new container command executor with the given configuration.
1147    pub fn new(config: ContainerConfig) -> Self {
1148        Self { config }
1149    }
1150
1151    /// Build the container `run` command arguments for a given request.
1152    fn build_run_args(&self, request: &ExecutionRequest, name: &str) -> Vec<String> {
1153        let mut args = vec!["run".to_string()];
1154
1155        if self.config.auto_remove {
1156            args.push("--rm".to_string());
1157        }
1158
1159        args.push("-i".to_string());
1160        args.push("--name".to_string());
1161        args.push(name.to_string());
1162        if self.config.drop_capabilities {
1163            args.push("--cap-drop=ALL".to_string());
1164        }
1165        if self.config.no_new_privileges {
1166            args.push("--security-opt=no-new-privileges".to_string());
1167        }
1168        if let Some(limit) = self.config.pids_limit {
1169            args.push(format!("--pids-limit={limit}"));
1170        }
1171
1172        match request.sandbox.network {
1173            NetworkPolicy::Disabled => {
1174                args.push("--network=none".to_string());
1175            }
1176            NetworkPolicy::Enabled => {}
1177        }
1178
1179        match &request.sandbox.filesystem {
1180            FilesystemPolicy::None => {}
1181            FilesystemPolicy::WorkspaceReadOnly { root } => {
1182                args.push("-v".to_string());
1183                args.push(format!("{}:/workspace:ro", root.display()));
1184            }
1185            FilesystemPolicy::WorkspaceReadWrite { root } => {
1186                args.push("-v".to_string());
1187                args.push(format!("{}:/workspace:rw", root.display()));
1188            }
1189            FilesystemPolicy::Paths { read_only, read_write } => {
1190                for path in read_only {
1191                    args.push("-v".to_string());
1192                    args.push(format!("{}:{}:ro", path.display(), path.display()));
1193                }
1194                for path in read_write {
1195                    args.push("-v".to_string());
1196                    args.push(format!("{}:{}:rw", path.display(), path.display()));
1197                }
1198            }
1199        }
1200
1201        if let EnvironmentPolicy::AllowList(vars) = &request.sandbox.environment {
1202            for var in vars {
1203                args.push("--env".to_string());
1204                args.push(var.clone());
1205            }
1206        }
1207
1208        if let Some(ref wd) = request.sandbox.working_directory {
1209            args.push("-w".to_string());
1210            args.push(wd.display().to_string());
1211        }
1212
1213        args.extend(self.config.extra_flags.clone());
1214        args.push(self.config.default_image.clone());
1215
1216        let code = match &request.payload {
1217            ExecutionPayload::Source { code } => code.clone(),
1218            ExecutionPayload::GuestModule { .. } => String::new(),
1219        };
1220
1221        match request.language {
1222            ExecutionLanguage::Python => {
1223                args.push("python3".to_string());
1224                args.push("-c".to_string());
1225                args.push(code);
1226            }
1227            ExecutionLanguage::JavaScript => {
1228                args.push("node".to_string());
1229                args.push("-e".to_string());
1230                args.push(code);
1231            }
1232            ExecutionLanguage::Command => {
1233                args.push("sh".to_string());
1234                args.push("-c".to_string());
1235                args.push(code);
1236            }
1237            _ => {}
1238        }
1239
1240        args.extend(request.argv.clone());
1241        args
1242    }
1243}
1244
1245impl Default for ContainerCommandExecutor {
1246    fn default() -> Self {
1247        Self::new(ContainerConfig::default())
1248    }
1249}
1250
1251#[async_trait]
1252impl CodeExecutor for ContainerCommandExecutor {
1253    fn name(&self) -> &str {
1254        "container-command"
1255    }
1256
1257    fn capabilities(&self) -> BackendCapabilities {
1258        BackendCapabilities {
1259            isolation: ExecutionIsolation::ContainerEphemeral,
1260            enforce_network_policy: true,
1261            enforce_filesystem_policy: true,
1262            enforce_environment_policy: true,
1263            enforce_timeout: true,
1264            supports_structured_output: true,
1265            supports_process_execution: true,
1266            supports_persistent_workspace: false,
1267            supports_interactive_sessions: false,
1268        }
1269    }
1270
1271    fn supports_language(&self, lang: &ExecutionLanguage) -> bool {
1272        matches!(
1273            lang,
1274            ExecutionLanguage::Python | ExecutionLanguage::JavaScript | ExecutionLanguage::Command
1275        )
1276    }
1277
1278    async fn execute(&self, request: ExecutionRequest) -> Result<ExecutionResult, ExecutionError> {
1279        let supported =
1280            [ExecutionLanguage::Python, ExecutionLanguage::JavaScript, ExecutionLanguage::Command];
1281        validate_request(&self.capabilities(), &supported, &request)?;
1282
1283        match &request.payload {
1284            ExecutionPayload::Source { code } if code.trim().is_empty() => {
1285                return Err(ExecutionError::InvalidRequest("empty source code".to_string()));
1286            }
1287            ExecutionPayload::Source { .. } => {}
1288            ExecutionPayload::GuestModule { .. } => {
1289                return Err(ExecutionError::InvalidRequest(
1290                    "ContainerCommandExecutor does not support guest modules".to_string(),
1291                ));
1292            }
1293        }
1294
1295        let start = Instant::now();
1296        let name = container_name("adk-exec");
1297        let run_args = self.build_run_args(&request, &name);
1298
1299        debug!(
1300            runtime = %self.config.runtime,
1301            image = %self.config.default_image,
1302            language = %request.language,
1303            "starting container execution"
1304        );
1305
1306        // Structured input takes precedence over raw stdin.
1307        let stdin = match (&request.input, &request.stdin) {
1308            (Some(input), _) => Some(serde_json::to_vec(input).unwrap_or_default()),
1309            (None, Some(raw)) => Some(raw.clone()),
1310            (None, None) => None,
1311        };
1312
1313        let mut cmd = tokio::process::Command::new(&self.config.runtime);
1314        cmd.args(&run_args)
1315            .stdin(if stdin.is_some() { Stdio::piped() } else { Stdio::null() })
1316            .stdout(Stdio::piped())
1317            .stderr(Stdio::piped())
1318            .kill_on_drop(true);
1319
1320        let child = cmd.spawn().map_err(|e| {
1321            ExecutionError::ExecutionFailed(format!(
1322                "failed to spawn container runtime '{}': {e}",
1323                self.config.runtime
1324            ))
1325        })?;
1326        // Killing the `run` client process does not stop its container.
1327        let mut container = RunningContainer::new(&self.config.runtime, &name);
1328
1329        let completed = host_process::run_to_completion(
1330            child,
1331            stdin,
1332            request.sandbox.timeout,
1333            request.sandbox.max_stdout_bytes,
1334            request.sandbox.max_stderr_bytes,
1335        )
1336        .await
1337        .map_err(|e| {
1338            ExecutionError::ExecutionFailed(format!("failed to wait for container: {e}"))
1339        })?;
1340
1341        let Some(output) = completed else {
1342            warn!(container.name = %name, "container execution timed out; killing the container");
1343            container.kill().await;
1344            return Ok(ExecutionResult {
1345                status: ExecutionStatus::Timeout,
1346                stdout: String::new(),
1347                stderr: String::new(),
1348                output: None,
1349                exit_code: None,
1350                stdout_truncated: false,
1351                stderr_truncated: false,
1352                duration_ms: start.elapsed().as_millis() as u64,
1353                metadata: None,
1354            });
1355        };
1356
1357        container.finished();
1358        let duration_ms = start.elapsed().as_millis() as u64;
1359
1360        let raw_stdout = String::from_utf8_lossy(&output.stdout.bytes).into_owned();
1361        let raw_stderr = String::from_utf8_lossy(&output.stderr.bytes).into_owned();
1362
1363        let (stdout, stdout_truncated) =
1364            truncate_output(raw_stdout, request.sandbox.max_stdout_bytes);
1365        let (stderr, stderr_truncated) =
1366            truncate_output(raw_stderr, request.sandbox.max_stderr_bytes);
1367        let stdout_truncated = stdout_truncated || output.stdout.truncated;
1368        let stderr_truncated = stderr_truncated || output.stderr.truncated;
1369
1370        let (structured_output, display_stdout) = extract_structured_output(&stdout);
1371
1372        let status = if output.status.success() {
1373            ExecutionStatus::Success
1374        } else {
1375            ExecutionStatus::Failed
1376        };
1377
1378        info!(
1379            exit_code = output.status.code(),
1380            duration_ms,
1381            has_structured_output = structured_output.is_some(),
1382            "container execution completed"
1383        );
1384
1385        Ok(ExecutionResult {
1386            status,
1387            stdout: display_stdout,
1388            stderr,
1389            output: structured_output,
1390            exit_code: output.status.code(),
1391            stdout_truncated,
1392            stderr_truncated,
1393            duration_ms,
1394            metadata: None,
1395        })
1396    }
1397}
1398
1399// ── Shared helpers ─────────────────────────────────────────────────────
1400
1401/// How long the executors wait for `kill` to stop a container that outlived its timeout.
1402const KILL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
1403
1404/// A container name unique to this process: `{prefix}-{pid}-{nanos}-{counter}`.
1405fn container_name(prefix: &str) -> String {
1406    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1407    let nanos = std::time::SystemTime::now()
1408        .duration_since(std::time::UNIX_EPOCH)
1409        .map(|elapsed| elapsed.subsec_nanos())
1410        .unwrap_or_default();
1411    let counter = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1412    format!("{prefix}-{}-{nanos}-{counter}", std::process::id())
1413}
1414
1415/// A container started by `{runtime} run`, killed unless it is marked finished.
1416struct RunningContainer {
1417    runtime: String,
1418    name: String,
1419    running: bool,
1420}
1421
1422impl RunningContainer {
1423    fn new(runtime: &str, name: &str) -> Self {
1424        Self { runtime: runtime.to_string(), name: name.to_string(), running: true }
1425    }
1426
1427    /// The container exited on its own.
1428    fn finished(&mut self) {
1429        self.running = false;
1430    }
1431
1432    /// Runs `{runtime} kill {name}` and waits for it.
1433    async fn kill(&mut self) {
1434        self.running = false;
1435        let kill = tokio::process::Command::new(&self.runtime)
1436            .args(["kill", &self.name])
1437            .stdin(Stdio::null())
1438            .stdout(Stdio::null())
1439            .stderr(Stdio::null())
1440            .kill_on_drop(true)
1441            .status();
1442        match tokio::time::timeout(KILL_TIMEOUT, kill).await {
1443            Ok(Ok(status)) if status.success() => {}
1444            Ok(Ok(status)) => warn!(container.name = %self.name, ?status, "container kill failed"),
1445            Ok(Err(error)) => warn!(container.name = %self.name, %error, "container kill failed"),
1446            Err(_) => warn!(container.name = %self.name, "container kill did not finish"),
1447        }
1448    }
1449}
1450
1451impl Drop for RunningContainer {
1452    fn drop(&mut self) {
1453        // The call was dropped mid-run; the container would otherwise keep running.
1454        if self.running {
1455            let mut kill = std::process::Command::new(&self.runtime);
1456            kill.args(["kill", &self.name])
1457                .stdin(Stdio::null())
1458                .stdout(Stdio::null())
1459                .stderr(Stdio::null());
1460            // A thread, so the kill is reaped without blocking the dropping task.
1461            std::thread::spawn(move || {
1462                let _ = kill.status();
1463            });
1464        }
1465    }
1466}
1467
1468/// Truncate output to the given byte limit.
1469fn truncate_output(output: String, max_bytes: usize) -> (String, bool) {
1470    if output.len() <= max_bytes {
1471        (output, false)
1472    } else {
1473        let truncated = output
1474            .char_indices()
1475            .take_while(|(i, _)| *i < max_bytes)
1476            .map(|(_, c)| c)
1477            .collect::<String>();
1478        (truncated, true)
1479    }
1480}
1481
1482/// Extract structured JSON output from the last line of stdout.
1483fn extract_structured_output(stdout: &str) -> (Option<serde_json::Value>, String) {
1484    let trimmed = stdout.trim_end();
1485    if trimmed.is_empty() {
1486        return (None, String::new());
1487    }
1488
1489    if let Some(last_newline_pos) = trimmed.rfind('\n') {
1490        let last_line = &trimmed[last_newline_pos + 1..];
1491        let before = &trimmed[..last_newline_pos];
1492
1493        if let Ok(value) = serde_json::from_str::<serde_json::Value>(last_line) {
1494            return (Some(value), before.to_string());
1495        }
1496    } else if let Ok(value) = serde_json::from_str::<serde_json::Value>(trimmed) {
1497        return (Some(value), String::new());
1498    }
1499
1500    (None, stdout.to_string())
1501}
1502
1503#[cfg(test)]
1504mod tests {
1505    use super::*;
1506
1507    #[test]
1508    fn capabilities_are_container_ephemeral() {
1509        let executor = ContainerCommandExecutor::default();
1510        let caps = executor.capabilities();
1511        assert_eq!(caps.isolation, ExecutionIsolation::ContainerEphemeral);
1512        assert!(caps.enforce_network_policy);
1513        assert!(caps.enforce_filesystem_policy);
1514        assert!(caps.enforce_environment_policy);
1515        assert!(caps.enforce_timeout);
1516        assert!(caps.supports_structured_output);
1517        assert!(caps.supports_process_execution);
1518        assert!(!caps.supports_persistent_workspace);
1519        assert!(!caps.supports_interactive_sessions);
1520    }
1521
1522    #[test]
1523    fn supports_python_js_command() {
1524        let executor = ContainerCommandExecutor::default();
1525        assert!(executor.supports_language(&ExecutionLanguage::Python));
1526        assert!(executor.supports_language(&ExecutionLanguage::JavaScript));
1527        assert!(executor.supports_language(&ExecutionLanguage::Command));
1528        assert!(!executor.supports_language(&ExecutionLanguage::Rust));
1529        assert!(!executor.supports_language(&ExecutionLanguage::Wasm));
1530    }
1531
1532    #[test]
1533    fn default_config() {
1534        let config = ContainerConfig::default();
1535        assert_eq!(config.runtime, "docker");
1536        assert_eq!(config.default_image, "python:3.12-slim");
1537        assert!(config.extra_flags.is_empty());
1538        assert!(config.auto_remove);
1539    }
1540
1541    #[test]
1542    fn build_run_args_basic_python() {
1543        let executor = ContainerCommandExecutor::default();
1544        let request = ExecutionRequest {
1545            language: ExecutionLanguage::Python,
1546            payload: ExecutionPayload::Source { code: "print('hello')".to_string() },
1547            argv: vec![],
1548            stdin: None,
1549            input: None,
1550            sandbox: crate::SandboxPolicy::strict_rust(),
1551            identity: None,
1552        };
1553
1554        let args = executor.build_run_args(&request, "adk-exec-test");
1555        assert!(args.contains(&"run".to_string()));
1556        assert!(args.contains(&"--rm".to_string()));
1557        assert!(args.contains(&"-i".to_string()));
1558        assert!(args.contains(&"--network=none".to_string()));
1559        assert!(args.contains(&"python3".to_string()));
1560        assert!(args.contains(&"-c".to_string()));
1561        assert!(args.contains(&"print('hello')".to_string()));
1562    }
1563
1564    #[test]
1565    fn build_run_args_with_network_enabled() {
1566        let executor = ContainerCommandExecutor::default();
1567        let mut sandbox = crate::SandboxPolicy::strict_rust();
1568        sandbox.network = NetworkPolicy::Enabled;
1569
1570        let request = ExecutionRequest {
1571            language: ExecutionLanguage::Python,
1572            payload: ExecutionPayload::Source { code: "print('hello')".to_string() },
1573            argv: vec![],
1574            stdin: None,
1575            input: None,
1576            sandbox,
1577            identity: None,
1578        };
1579
1580        let args = executor.build_run_args(&request, "adk-exec-test");
1581        assert!(!args.contains(&"--network=none".to_string()));
1582    }
1583
1584    fn python_request(code: &str, timeout: std::time::Duration) -> ExecutionRequest {
1585        let mut sandbox = crate::SandboxPolicy::strict_rust();
1586        sandbox.timeout = timeout;
1587        ExecutionRequest {
1588            language: ExecutionLanguage::Python,
1589            payload: ExecutionPayload::Source { code: code.to_string() },
1590            argv: vec![],
1591            stdin: None,
1592            input: None,
1593            sandbox,
1594            identity: None,
1595        }
1596    }
1597
1598    #[test]
1599    fn build_run_args_names_and_hardens_the_container_unless_opted_out() {
1600        let request = python_request("print(1)", std::time::Duration::from_secs(5));
1601        let args = ContainerCommandExecutor::default().build_run_args(&request, "adk-exec-test");
1602        let name_at = args.iter().position(|arg| arg == "--name").expect("--name");
1603        assert_eq!(args[name_at + 1], "adk-exec-test");
1604        for flag in ["--cap-drop=ALL", "--security-opt=no-new-privileges", "--pids-limit=256"] {
1605            assert!(args.contains(&flag.to_string()), "{flag} missing from {args:?}");
1606        }
1607
1608        let open = ContainerCommandExecutor::new(ContainerConfig {
1609            drop_capabilities: false,
1610            no_new_privileges: false,
1611            pids_limit: None,
1612            ..ContainerConfig::default()
1613        });
1614        let args = open.build_run_args(&request, "adk-exec-test");
1615        assert!(!args.iter().any(|arg| arg.starts_with("--cap-drop")
1616            || arg.starts_with("--security-opt")
1617            || arg.starts_with("--pids-limit")));
1618    }
1619
1620    /// A stand-in container runtime that logs its arguments; `run` blocks like a
1621    /// container whose code never ends.
1622    #[cfg(unix)]
1623    fn logging_runtime(dir: &std::path::Path) -> (std::path::PathBuf, std::path::PathBuf) {
1624        use std::os::unix::fs::PermissionsExt;
1625        let log = dir.join("runtime.log");
1626        let runtime = dir.join("runtime");
1627        std::fs::write(
1628            &runtime,
1629            format!(
1630                "#!/bin/sh\necho \"$*\" >> '{}'\ncase \"$1\" in run) exec sleep 30 ;; esac\n",
1631                log.display()
1632            ),
1633        )
1634        .unwrap();
1635        std::fs::set_permissions(&runtime, std::fs::Permissions::from_mode(0o755)).unwrap();
1636        // The first run of a new executable can be delayed by the OS (macOS scans it).
1637        std::process::Command::new(&runtime).arg("warm-up").status().unwrap();
1638        (runtime, log)
1639    }
1640
1641    /// The name given to `run`, and whether a later invocation killed it.
1642    #[cfg(unix)]
1643    fn killed_container(log: &std::path::Path) -> (Option<String>, bool) {
1644        let lines: Vec<String> =
1645            std::fs::read_to_string(log).unwrap_or_default().lines().map(str::to_string).collect();
1646        let name = lines.iter().find(|line| line.starts_with("run ")).and_then(|line| {
1647            let words: Vec<&str> = line.split_whitespace().collect();
1648            words.windows(2).find(|pair| pair[0] == "--name").map(|pair| pair[1].to_string())
1649        });
1650        let killed = name
1651            .as_ref()
1652            .is_some_and(|name| lines.iter().any(|line| *line == format!("kill {name}")));
1653        (name, killed)
1654    }
1655
1656    #[cfg(unix)]
1657    #[tokio::test]
1658    async fn a_timed_out_container_is_killed_by_name() {
1659        let dir = tempfile::tempdir().unwrap();
1660        let (runtime, log) = logging_runtime(dir.path());
1661        let executor = ContainerCommandExecutor::new(ContainerConfig {
1662            runtime: runtime.display().to_string(),
1663            ..ContainerConfig::default()
1664        });
1665
1666        let result = executor
1667            .execute(python_request("while True: pass", std::time::Duration::from_millis(1500)))
1668            .await
1669            .unwrap();
1670
1671        assert_eq!(result.status, ExecutionStatus::Timeout);
1672        let (name, killed) = killed_container(&log);
1673        assert!(
1674            name.is_some() && killed,
1675            "{name:?} not killed: {:?}",
1676            std::fs::read_to_string(&log)
1677        );
1678    }
1679
1680    #[cfg(unix)]
1681    #[tokio::test]
1682    async fn a_dropped_execution_kills_its_container() {
1683        let dir = tempfile::tempdir().unwrap();
1684        let (runtime, log) = logging_runtime(dir.path());
1685        let executor = ContainerCommandExecutor::new(ContainerConfig {
1686            runtime: runtime.display().to_string(),
1687            ..ContainerConfig::default()
1688        });
1689
1690        let execution = tokio::spawn(async move {
1691            executor
1692                .execute(python_request("while True: pass", std::time::Duration::from_secs(30)))
1693                .await
1694        });
1695        let mut started = false;
1696        for _ in 0..250 {
1697            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
1698            started = killed_container(&log).0.is_some();
1699            if started {
1700                break;
1701            }
1702        }
1703        assert!(started, "the container never started: {:?}", std::fs::read_to_string(&log));
1704        execution.abort();
1705
1706        let mut killed = false;
1707        for _ in 0..250 {
1708            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
1709            killed = killed_container(&log).1;
1710            if killed {
1711                break;
1712            }
1713        }
1714        assert!(killed, "{:?}", std::fs::read_to_string(&log));
1715    }
1716
1717    #[test]
1718    fn docker_config_presets() {
1719        let py = DockerConfig::python();
1720        assert_eq!(py.image, "python:3.12-slim");
1721        assert!(py.network_disabled);
1722
1723        let node = DockerConfig::node();
1724        assert_eq!(node.image, "node:20-slim");
1725
1726        let custom = DockerConfig::custom("ubuntu:24.04");
1727        assert_eq!(custom.image, "ubuntu:24.04");
1728    }
1729
1730    fn policy(
1731        network: NetworkPolicy,
1732        filesystem: FilesystemPolicy,
1733        environment: EnvironmentPolicy,
1734    ) -> SandboxPolicy {
1735        SandboxPolicy { network, filesystem, environment, ..SandboxPolicy::strict_rust() }
1736    }
1737
1738    fn assert_rejected(config: &DockerConfig, policy: &SandboxPolicy, mentions: &str) {
1739        match config.validate_sandbox_policy(policy) {
1740            Err(ExecutionError::UnsupportedPolicy(message)) => {
1741                assert!(message.contains(mentions), "{message}");
1742            }
1743            other => panic!("expected UnsupportedPolicy mentioning `{mentions}`, got {other:?}"),
1744        }
1745    }
1746
1747    #[test]
1748    fn docker_policy_default_config_satisfies_strict_policy() {
1749        assert_eq!(
1750            DockerConfig::python().validate_sandbox_policy(&SandboxPolicy::strict_rust()),
1751            Ok(())
1752        );
1753    }
1754
1755    #[test]
1756    fn docker_policy_rejects_disabled_network_on_networked_container() {
1757        let config = DockerConfig::python().with_network();
1758        assert_rejected(&config, &SandboxPolicy::strict_rust(), "network");
1759
1760        let allows_network =
1761            policy(NetworkPolicy::Enabled, FilesystemPolicy::None, EnvironmentPolicy::None);
1762        assert_eq!(config.validate_sandbox_policy(&allows_network), Ok(()));
1763    }
1764
1765    #[test]
1766    fn docker_policy_allows_enabled_network_on_isolated_container() {
1767        let allows_network =
1768            policy(NetworkPolicy::Enabled, FilesystemPolicy::None, EnvironmentPolicy::None);
1769        assert_eq!(DockerConfig::python().validate_sandbox_policy(&allows_network), Ok(()));
1770    }
1771
1772    #[test]
1773    fn docker_policy_rejects_any_mount_without_filesystem_access() {
1774        let config = DockerConfig::python().bind_mount("/srv/data:/data:ro");
1775        assert_rejected(&config, &SandboxPolicy::strict_rust(), "/srv/data:/data:ro");
1776    }
1777
1778    #[test]
1779    fn docker_policy_read_only_workspace_requires_read_only_mounts_under_root() {
1780        let read_only = policy(
1781            NetworkPolicy::Disabled,
1782            FilesystemPolicy::WorkspaceReadOnly { root: PathBuf::from("/srv") },
1783            EnvironmentPolicy::None,
1784        );
1785
1786        let ro_under_root = DockerConfig::python().bind_mount("/srv/data:/data:ro");
1787        assert_eq!(ro_under_root.validate_sandbox_policy(&read_only), Ok(()));
1788
1789        let rw_under_root = DockerConfig::python().bind_mount("/srv/data:/data");
1790        assert_rejected(&rw_under_root, &read_only, "/srv/data:/data");
1791
1792        let ro_outside_root = DockerConfig::python().bind_mount("/home/user/.aws:/aws:ro");
1793        assert_rejected(&ro_outside_root, &read_only, "/home/user/.aws");
1794
1795        let escapes_root = DockerConfig::python().bind_mount("/srv/../etc:/etc-host:ro");
1796        assert_rejected(&escapes_root, &read_only, "/srv/../etc");
1797
1798        let sibling_prefix = DockerConfig::python().bind_mount("/srv-secrets:/s:ro");
1799        assert_rejected(&sibling_prefix, &read_only, "/srv-secrets");
1800
1801        let named_volume = DockerConfig::python().bind_mount("cache:/cache:ro");
1802        assert_rejected(&named_volume, &read_only, "cache:/cache:ro");
1803    }
1804
1805    #[test]
1806    fn docker_policy_read_write_workspace_accepts_any_mode_under_root() {
1807        let read_write = policy(
1808            NetworkPolicy::Disabled,
1809            FilesystemPolicy::WorkspaceReadWrite { root: PathBuf::from("/srv") },
1810            EnvironmentPolicy::None,
1811        );
1812        let config = DockerConfig::python()
1813            .bind_mount("/srv/data:/data")
1814            .bind_mount("/srv/models:/models:ro");
1815        assert_eq!(config.validate_sandbox_policy(&read_write), Ok(()));
1816    }
1817
1818    #[test]
1819    fn docker_policy_explicit_paths_match_mode() {
1820        let paths = policy(
1821            NetworkPolicy::Disabled,
1822            FilesystemPolicy::Paths {
1823                read_only: vec![PathBuf::from("/srv/models")],
1824                read_write: vec![PathBuf::from("/srv/out")],
1825            },
1826            EnvironmentPolicy::None,
1827        );
1828
1829        let config = DockerConfig::python()
1830            .bind_mount("/srv/models:/models:ro,z")
1831            .bind_mount("/srv/out:/out:rw");
1832        assert_eq!(config.validate_sandbox_policy(&paths), Ok(()));
1833
1834        let writable_read_only_path = DockerConfig::python().bind_mount("/srv/models:/models");
1835        assert_rejected(&writable_read_only_path, &paths, "/srv/models:/models");
1836    }
1837
1838    #[test]
1839    fn docker_policy_container_environment_must_be_allowlisted() {
1840        let config = DockerConfig::python().env("API_TOKEN=secret").env("MODE");
1841        assert_rejected(&config, &SandboxPolicy::strict_rust(), "API_TOKEN");
1842
1843        let only_mode = policy(
1844            NetworkPolicy::Disabled,
1845            FilesystemPolicy::None,
1846            EnvironmentPolicy::AllowList(vec!["MODE".to_string()]),
1847        );
1848        assert_rejected(&config, &only_mode, "API_TOKEN");
1849
1850        let both = policy(
1851            NetworkPolicy::Disabled,
1852            FilesystemPolicy::None,
1853            EnvironmentPolicy::AllowList(vec!["API_TOKEN".to_string(), "MODE".to_string()]),
1854        );
1855        assert_eq!(config.validate_sandbox_policy(&both), Ok(()));
1856    }
1857
1858    #[test]
1859    fn docker_config_builder_methods() {
1860        let config = DockerConfig::python()
1861            .pip_install(&["numpy", "pandas"])
1862            .with_network()
1863            .env("MY_VAR=hello")
1864            .bind_mount("/host/data:/data:ro");
1865
1866        assert!(!config.network_disabled);
1867        assert_eq!(config.setup_commands.len(), 1);
1868        assert!(config.setup_commands[0].contains("numpy"));
1869        assert_eq!(config.environment, vec!["MY_VAR=hello"]);
1870        assert_eq!(config.bind_mounts, vec!["/host/data:/data:ro"]);
1871    }
1872}