Skip to main content

aidaemon_tools/
execution.rs

1//! Workspace-bound execution backends: where agent-visible files and
2//! processes live. The local backend is [`LocalBackend`]; this module adds
3//! the SSH backend and, behind the `docker` feature, a persistent Docker
4//! container, plus the `[execution]` settings that pick one.
5//!
6//! A host's control plane (configuration, state, channels, keychain, UI
7//! automation) stays on the host. Agent-visible files and processes go
8//! through the backend so a tool can never read one filesystem and execute
9//! in another.
10
11use std::collections::{BTreeMap, BTreeSet};
12use std::path::Path;
13use std::process::Stdio;
14use std::sync::Arc;
15use std::time::{Duration, Instant, UNIX_EPOCH};
16
17use async_trait::async_trait;
18use serde::Deserialize;
19use sha2::{Digest, Sha256};
20use tokio::io::AsyncWriteExt;
21use tokio::process::Command;
22
23use crate::backend::{SharedExecutionBackend, normalize_posix_absolute};
24use crate::local_backend::{LocalBackend, expand_local_path};
25use crate::process_control::{
26    configure_command_for_process_group, send_sigkill, send_sigterm, terminate_process_tree,
27};
28use crate::{
29    BackendDirEntry, BackendFileType, BackendKind, BackendMetadata, BackendPath, ExecutionBackend,
30    ExecutionOutput, ExecutionRequest, ProcessHandle, SpawnedProcess, WriteMode, shell_quote,
31};
32
33/// Agent-visible execution workspace configuration.
34///
35/// Daemon control-plane state (configuration, SQLite, channel inbox transport,
36/// keychain access, and browser/computer-use sessions) always remains local.
37/// Only tools that inspect or mutate the agent's working environment use this
38/// backend.
39#[derive(Debug, Deserialize, Clone)]
40pub struct ExecutionConfig {
41    /// Selected backend: `local`, `docker`, or `ssh`.
42    #[serde(default = "default_execution_backend")]
43    pub backend: String,
44    /// Default working directory for relative agent-visible paths. For local
45    /// execution this defaults to the daemon working directory.
46    #[serde(default)]
47    pub workspace_root: Option<String>,
48    /// Allow path-based tools and explicit command working directories outside
49    /// `workspace_root`. This defaults to true only for the local backend to
50    /// preserve historical behavior. Shell commands retain the authority of
51    /// the selected OS account/container and are governed by terminal approval.
52    #[serde(default)]
53    pub allow_outside_workspace: Option<bool>,
54    /// Extra host variable names local commands inherit, on top of
55    /// [`crate::local_backend::LOCAL_ENV_ALLOWLIST`] (a trailing `*` is a
56    /// prefix). The daemon's other variables never reach a command.
57    #[serde(default)]
58    pub env_allowlist: Vec<String>,
59    #[cfg_attr(not(feature = "docker"), allow(dead_code))]
60    #[serde(default)]
61    pub docker: DockerExecutionConfig,
62    #[serde(default)]
63    pub ssh: SshExecutionConfig,
64}
65
66impl Default for ExecutionConfig {
67    fn default() -> Self {
68        Self {
69            backend: default_execution_backend(),
70            workspace_root: None,
71            allow_outside_workspace: None,
72            env_allowlist: Vec::new(),
73            docker: DockerExecutionConfig::default(),
74            ssh: SshExecutionConfig::default(),
75        }
76    }
77}
78
79impl ExecutionConfig {
80    pub fn normalized_backend(&self) -> anyhow::Result<String> {
81        let backend = self.backend.trim().to_ascii_lowercase();
82        match backend.as_str() {
83            "local" | "docker" | "ssh" => Ok(backend),
84            _ => anyhow::bail!(
85                "execution.backend must be one of: local, docker, ssh (got {:?})",
86                self.backend
87            ),
88        }
89    }
90
91    pub fn effective_allow_outside_workspace(&self) -> bool {
92        self.allow_outside_workspace
93            .unwrap_or_else(|| self.backend.trim().eq_ignore_ascii_case("local"))
94    }
95}
96
97fn default_execution_backend() -> String {
98    "local".to_string()
99}
100
101#[cfg_attr(not(feature = "docker"), allow(dead_code))]
102#[derive(Debug, Deserialize, Clone)]
103pub struct DockerExecutionConfig {
104    /// Persistent container name used for every tool call.
105    #[serde(default = "default_docker_container")]
106    pub container: String,
107    /// Image used when `create_if_missing` creates the persistent container.
108    #[serde(default = "default_docker_image")]
109    pub image: String,
110    /// Agent-visible workspace path inside the container.
111    #[serde(default = "default_remote_workspace_root")]
112    pub workspace_root: String,
113    /// Host directory bind-mounted at `workspace_root`. Relative paths resolve
114    /// next to config.toml. If omitted, the daemon working directory is used.
115    #[serde(default)]
116    pub host_workspace: Option<String>,
117    /// Create and start the persistent container when it does not exist.
118    #[serde(default = "default_true")]
119    pub create_if_missing: bool,
120    /// Docker network mode. Defaults to `none`; CLI agents that call cloud APIs
121    /// need an explicitly configured network such as `bridge`.
122    #[serde(default = "default_docker_network")]
123    pub network: String,
124    /// Optional Docker user (`uid:gid`, name, etc.) for `docker exec`.
125    #[serde(default)]
126    pub user: Option<String>,
127    /// Additional environment variable names copied from the daemon into
128    /// container executions. Values are never exposed in tool arguments.
129    #[serde(default)]
130    pub env_allowlist: Vec<String>,
131}
132
133impl Default for DockerExecutionConfig {
134    fn default() -> Self {
135        Self {
136            container: default_docker_container(),
137            image: default_docker_image(),
138            workspace_root: default_remote_workspace_root(),
139            host_workspace: None,
140            create_if_missing: true,
141            network: default_docker_network(),
142            user: None,
143            env_allowlist: Vec::new(),
144        }
145    }
146}
147
148fn default_docker_container() -> String {
149    "aidaemon-execution".to_string()
150}
151
152fn default_docker_image() -> String {
153    "ubuntu:24.04".to_string()
154}
155
156fn default_remote_workspace_root() -> String {
157    "/workspace".to_string()
158}
159
160fn default_docker_network() -> String {
161    "none".to_string()
162}
163
164#[derive(Debug, Deserialize, Clone)]
165pub struct SshExecutionConfig {
166    /// OpenSSH host or alias. Existing ~/.ssh/config, ssh-agent, ProxyJump,
167    /// known_hosts, and hardware-token settings are honored.
168    #[serde(default)]
169    pub host: String,
170    /// Persistent agent-visible directory on the SSH host.
171    #[serde(default = "default_ssh_workspace_root")]
172    pub workspace_root: String,
173    #[serde(default)]
174    pub port: Option<u16>,
175    /// Optional local identity file path. Prefer an OpenSSH alias/ssh-agent.
176    #[serde(default)]
177    pub identity_file: Option<String>,
178    /// Additional OpenSSH arguments, for example `["-J", "bastion"]`.
179    #[serde(default)]
180    pub extra_args: Vec<String>,
181    #[serde(default = "default_ssh_connect_timeout")]
182    pub connect_timeout_secs: u64,
183    /// Create workspace_root on startup when it is missing.
184    #[serde(default = "default_true")]
185    pub create_workspace: bool,
186    /// Environment variable names explicitly forwarded to remote executions.
187    #[serde(default)]
188    pub env_allowlist: Vec<String>,
189}
190
191impl Default for SshExecutionConfig {
192    fn default() -> Self {
193        Self {
194            host: String::new(),
195            workspace_root: default_ssh_workspace_root(),
196            port: None,
197            identity_file: None,
198            extra_args: Vec::new(),
199            connect_timeout_secs: default_ssh_connect_timeout(),
200            create_workspace: true,
201            env_allowlist: Vec::new(),
202        }
203    }
204}
205
206fn default_ssh_workspace_root() -> String {
207    "~/aidaemon-workspace".to_string()
208}
209
210fn default_ssh_connect_timeout() -> u64 {
211    10
212}
213
214fn default_true() -> bool {
215    true
216}
217
218/// The local backend `[execution]` describes.
219pub async fn local_backend(config: &ExecutionConfig) -> anyhow::Result<LocalBackend> {
220    Ok(LocalBackend::new(
221        config.workspace_root.as_deref(),
222        config.effective_allow_outside_workspace(),
223    )
224    .await?
225    .with_env_allowlist(config.env_allowlist.iter().cloned()))
226}
227
228pub async fn build_execution_backend(
229    config: &ExecutionConfig,
230    config_path: &Path,
231) -> anyhow::Result<SharedExecutionBackend> {
232    match config.normalized_backend()?.as_str() {
233        "local" => Ok(Arc::new(local_backend(config).await?)),
234        "ssh" => Ok(Arc::new(
235            SshBackend::new(
236                &config.ssh,
237                config.workspace_root.as_deref(),
238                config.effective_allow_outside_workspace(),
239            )
240            .await?,
241        )),
242        "docker" => {
243            #[cfg(feature = "docker")]
244            {
245                Ok(Arc::new(
246                    DockerBackend::new(
247                        &config.docker,
248                        config.workspace_root.as_deref(),
249                        config.effective_allow_outside_workspace(),
250                        config_path,
251                    )
252                    .await?,
253                ))
254            }
255            #[cfg(not(feature = "docker"))]
256            {
257                let _ = config_path;
258                anyhow::bail!(
259                    "execution.backend=\"docker\" requires aidaemon built with the \
260                     `execution-docker` feature (on by default; this build turned it off)"
261                )
262            }
263        }
264        _ => unreachable!("validated execution backend"),
265    }
266}
267
268#[derive(Clone)]
269enum RemoteTransport {
270    Ssh {
271        host: String,
272        args: Vec<String>,
273    },
274    #[cfg(feature = "docker")]
275    Docker {
276        container: String,
277        user: Option<String>,
278    },
279}
280
281#[derive(Clone)]
282struct RemoteBackendCore {
283    kind: BackendKind,
284    id: String,
285    approval_scope: String,
286    workspace_root: BackendPath,
287    canonical_workspace_root: String,
288    home: BackendPath,
289    allow_outside_workspace: bool,
290    env_allowlist: Vec<String>,
291    transport: RemoteTransport,
292}
293
294impl RemoteBackendCore {
295    async fn run_transport(
296        &self,
297        script: &str,
298        stdin: Option<Vec<u8>>,
299        timeout: Duration,
300    ) -> anyhow::Result<ExecutionOutput> {
301        let mut child = self.spawn_transport(script, stdin).await?;
302        let handle = child.handle().clone();
303        let stdout = child
304            .take_stdout()
305            .ok_or_else(|| anyhow::anyhow!("remote transport stdout unavailable"))?;
306        let stderr = child
307            .take_stderr()
308            .ok_or_else(|| anyhow::anyhow!("remote transport stderr unavailable"))?;
309        let mut process = child.into_child();
310        let started = Instant::now();
311        let stdout_task = tokio::spawn(async move {
312            let mut reader = stdout;
313            let mut bytes = Vec::new();
314            tokio::io::AsyncReadExt::read_to_end(&mut reader, &mut bytes).await?;
315            Ok::<_, std::io::Error>(bytes)
316        });
317        let stderr_task = tokio::spawn(async move {
318            let mut reader = stderr;
319            let mut bytes = Vec::new();
320            tokio::io::AsyncReadExt::read_to_end(&mut reader, &mut bytes).await?;
321            Ok::<_, std::io::Error>(bytes)
322        });
323        let (status, timed_out) = match tokio::time::timeout(timeout, process.wait()).await {
324            Ok(status) => (Some(status?), false),
325            Err(_) => {
326                if let Some(pid) = handle.local_pid() {
327                    terminate_process_tree(pid, &mut process, Duration::from_secs(1)).await;
328                }
329                (None, true)
330            }
331        };
332        Ok(ExecutionOutput {
333            exit_code: status.and_then(|status| status.code()).unwrap_or(-1),
334            stdout: stdout_task
335                .await
336                .ok()
337                .and_then(Result::ok)
338                .unwrap_or_default(),
339            stderr: stderr_task
340                .await
341                .ok()
342                .and_then(Result::ok)
343                .unwrap_or_default(),
344            duration_ms: started.elapsed().as_millis() as u64,
345            timed_out,
346        })
347    }
348
349    async fn spawn_transport(
350        &self,
351        script: &str,
352        stdin: Option<Vec<u8>>,
353    ) -> anyhow::Result<SpawnedProcess> {
354        let mut command = match &self.transport {
355            RemoteTransport::Ssh { host, args } => {
356                let mut command = Command::new("ssh");
357                // OpenSSH sends one remote command string rather than an argv
358                // vector, so quote the script as one literal `sh -c` argument.
359                command
360                    .args(args)
361                    .arg(host)
362                    .arg(format!("sh -c {}", shell_quote(script)));
363                command
364            }
365            #[cfg(feature = "docker")]
366            RemoteTransport::Docker { container, user } => {
367                let mut command = Command::new("docker");
368                command.arg("exec").arg("-i");
369                if let Some(user) = user {
370                    command.arg("--user").arg(user);
371                }
372                command.arg(container).arg("sh").arg("-c").arg(script);
373                command
374            }
375        };
376        command
377            .stdin(if stdin.is_some() {
378                Stdio::piped()
379            } else {
380                Stdio::null()
381            })
382            .stdout(Stdio::piped())
383            .stderr(Stdio::piped())
384            .kill_on_drop(true);
385        configure_command_for_process_group(&mut command);
386        let mut child = command.spawn()?;
387        if let (Some(stdin), Some(mut pipe)) = (stdin, child.stdin.take()) {
388            tokio::spawn(async move {
389                let _ = pipe.write_all(&stdin).await;
390            });
391        }
392        let pid = child.id().unwrap_or(0);
393        Ok(SpawnedProcess::new(
394            ProcessHandle::new(pid, Some(pid), None),
395            child,
396        ))
397    }
398
399    async fn checked_path(&self, path: &BackendPath) -> anyhow::Result<()> {
400        if self.allow_outside_workspace {
401            return Ok(());
402        }
403        let path = normalize_posix_absolute(path.as_str())?;
404        ensure_posix_descendant(&path, self.workspace_root.as_str())?;
405        let script = format!(
406            "p={}; root={}; \
407             if [ -L \"$p\" ]; then printf 'symlink target refused: %s' \"$p\" >&2; exit 126; fi; \
408             probe=\"$p\"; \
409             while [ ! -e \"$probe\" ] && [ ! -L \"$probe\" ]; do \
410               next=$(dirname -- \"$probe\"); [ \"$next\" = \"$probe\" ] && break; probe=\"$next\"; \
411             done; \
412             if [ -d \"$probe\" ]; then c=$(cd -P -- \"$probe\" && pwd); \
413             else d=$(dirname -- \"$probe\"); c=$(cd -P -- \"$d\" && printf '%s/%s' \"$PWD\" \"$(basename -- \"$probe\")\"); fi; \
414             case \"$c\" in \"$root\"|\"$root\"/*) exit 0;; *) printf '%s' \"$c\" >&2; exit 126;; esac",
415            shell_quote(&path),
416            shell_quote(&self.canonical_workspace_root),
417        );
418        let output = self
419            .run_transport(&script, None, Duration::from_secs(10))
420            .await?;
421        anyhow::ensure!(
422            output.exit_code == 0,
423            "Path escapes execution workspace {}: {} ({})",
424            self.workspace_root,
425            path,
426            output.stderr_lossy().trim()
427        );
428        Ok(())
429    }
430
431    async fn resolve_path(&self, path: &str) -> anyhow::Result<BackendPath> {
432        let expanded = if path == "~" {
433            self.home.as_str().to_string()
434        } else if let Some(rest) = path.strip_prefix("~/") {
435            format!("{}/{}", self.home.as_str().trim_end_matches('/'), rest)
436        } else if crate::BackendPath::is_absolute(path) {
437            path.to_string()
438        } else {
439            format!(
440                "{}/{}",
441                self.workspace_root.as_str().trim_end_matches('/'),
442                path
443            )
444        };
445        let normalized = normalize_posix_absolute(&expanded)?;
446        let result = BackendPath::new(normalized);
447        self.checked_path(&result).await?;
448        Ok(result)
449    }
450
451    async fn canonicalize(&self, path: &BackendPath) -> anyhow::Result<BackendPath> {
452        self.checked_path(path).await?;
453        let script = format!(
454            "p={}; if [ -d \"$p\" ]; then cd -P -- \"$p\" && pwd; \
455             else d=$(dirname -- \"$p\"); b=$(basename -- \"$p\"); cd -P -- \"$d\" && printf '%s/%s\\n' \"$PWD\" \"$b\"; fi",
456            shell_quote(path.as_str())
457        );
458        let output = self
459            .run_transport(&script, None, Duration::from_secs(10))
460            .await?;
461        remote_success("canonicalize", output).map(|text| BackendPath::new(text.trim()))
462    }
463
464    async fn metadata(&self, path: &BackendPath) -> anyhow::Result<BackendMetadata> {
465        self.checked_path(path).await?;
466        let script = format!(
467            "p={}; \
468             if [ -L \"$p\" ]; then t=l; elif [ -f \"$p\" ]; then t=f; \
469             elif [ -d \"$p\" ]; then t=d; elif [ -e \"$p\" ]; then t=o; else exit 44; fi; \
470             n=$(wc -c < \"$p\" 2>/dev/null || printf 0); \
471             m=$(stat -c %Y \"$p\" 2>/dev/null || stat -f %m \"$p\" 2>/dev/null || printf 0); \
472             printf '%s\\t%s\\t%s\\n' \"$t\" \"$n\" \"$m\"",
473            shell_quote(path.as_str())
474        );
475        let output = self
476            .run_transport(&script, None, Duration::from_secs(10))
477            .await?;
478        let text = remote_success("metadata", output)?;
479        parse_remote_metadata(text.trim())
480    }
481
482    async fn read(&self, path: &BackendPath) -> anyhow::Result<Vec<u8>> {
483        self.checked_path(path).await?;
484        let output = self
485            .run_transport(
486                &format!("cat -- {}", shell_quote(path.as_str())),
487                None,
488                Duration::from_secs(300),
489            )
490            .await?;
491        if output.exit_code != 0 {
492            anyhow::bail!("remote read failed: {}", output.stderr_lossy().trim());
493        }
494        Ok(output.stdout)
495    }
496
497    async fn write(
498        &self,
499        path: &BackendPath,
500        content: &[u8],
501        mode: WriteMode,
502        create_parents: bool,
503    ) -> anyhow::Result<()> {
504        self.checked_path(path).await?;
505        let parent = path
506            .parent()
507            .ok_or_else(|| anyhow::anyhow!("Cannot write path without parent: {path}"))?;
508        self.checked_path(&parent).await?;
509        let mkdir = if create_parents {
510            format!("mkdir -p -- {} && ", shell_quote(parent.as_str()))
511        } else {
512            String::new()
513        };
514        let script = match mode {
515            WriteMode::Append => {
516                format!("{mkdir}cat >> {}", shell_quote(path.as_str()))
517            }
518            WriteMode::Overwrite => {
519                let temp = format!("{}.aidaemon-write-{}", path.as_str(), uuid::Uuid::new_v4());
520                format!(
521                    "{mkdir}cat > {} && mv -f -- {} {}",
522                    shell_quote(&temp),
523                    shell_quote(&temp),
524                    shell_quote(path.as_str())
525                )
526            }
527        };
528        let output = self
529            .run_transport(&script, Some(content.to_vec()), Duration::from_secs(300))
530            .await?;
531        remote_success("write", output)?;
532        Ok(())
533    }
534
535    async fn create_dir_all(&self, path: &BackendPath) -> anyhow::Result<()> {
536        self.checked_path(path).await?;
537        let output = self
538            .run_transport(
539                &format!("mkdir -p -- {}", shell_quote(path.as_str())),
540                None,
541                Duration::from_secs(30),
542            )
543            .await?;
544        remote_success("create directory", output)?;
545        Ok(())
546    }
547
548    async fn copy(&self, source: &BackendPath, destination: &BackendPath) -> anyhow::Result<()> {
549        self.checked_path(source).await?;
550        self.checked_path(destination).await?;
551        let output = self
552            .run_transport(
553                &format!(
554                    "cp -p -- {} {}",
555                    shell_quote(source.as_str()),
556                    shell_quote(destination.as_str())
557                ),
558                None,
559                Duration::from_secs(60),
560            )
561            .await?;
562        remote_success("copy", output)?;
563        Ok(())
564    }
565
566    async fn rename(&self, source: &BackendPath, destination: &BackendPath) -> anyhow::Result<()> {
567        self.checked_path(source).await?;
568        self.checked_path(destination).await?;
569        let output = self
570            .run_transport(
571                &format!(
572                    "mv -f -- {} {}",
573                    shell_quote(source.as_str()),
574                    shell_quote(destination.as_str())
575                ),
576                None,
577                Duration::from_secs(60),
578            )
579            .await?;
580        remote_success("rename", output)?;
581        Ok(())
582    }
583
584    async fn remove_file(&self, path: &BackendPath) -> anyhow::Result<()> {
585        self.checked_path(path).await?;
586        let output = self
587            .run_transport(
588                &format!("rm -f -- {}", shell_quote(path.as_str())),
589                None,
590                Duration::from_secs(30),
591            )
592            .await?;
593        remote_success("remove file", output)?;
594        Ok(())
595    }
596
597    async fn remove_empty_dir(&self, path: &BackendPath) -> anyhow::Result<()> {
598        self.checked_path(path).await?;
599        let output = self
600            .run_transport(
601                &format!("rmdir -- {}", shell_quote(path.as_str())),
602                None,
603                Duration::from_secs(30),
604            )
605            .await?;
606        remote_success("remove empty directory", output)?;
607        Ok(())
608    }
609
610    async fn read_dir(&self, path: &BackendPath) -> anyhow::Result<Vec<BackendDirEntry>> {
611        self.checked_path(path).await?;
612        let output = self
613            .run_transport(
614                &format!(
615                    "find {} -mindepth 1 -maxdepth 1 -print0",
616                    shell_quote(path.as_str())
617                ),
618                None,
619                Duration::from_secs(30),
620            )
621            .await?;
622        if output.exit_code != 0 {
623            anyhow::bail!(
624                "remote directory listing failed: {}",
625                output.stderr_lossy().trim()
626            );
627        }
628        let mut entries = Vec::new();
629        for raw in output.stdout.split(|byte| *byte == 0) {
630            if raw.is_empty() {
631                continue;
632            }
633            let path = BackendPath::new(String::from_utf8_lossy(raw).into_owned());
634            entries.push(BackendDirEntry {
635                metadata: self.metadata(&path).await?,
636                path,
637            });
638        }
639        Ok(entries)
640    }
641
642    async fn spawn(&self, request: ExecutionRequest) -> anyhow::Result<SpawnedProcess> {
643        let cwd = request.cwd.as_ref().unwrap_or(&self.workspace_root).clone();
644        self.checked_path(&cwd).await?;
645        let token = uuid::Uuid::new_v4().simple().to_string();
646        let pid_file = format!("/tmp/aidaemon-exec-{token}.pid");
647        let mut request_env = request.env;
648        let removed_env = request
649            .env_remove
650            .into_iter()
651            .filter(|name| valid_env_name(name))
652            .collect::<BTreeSet<_>>();
653        for name in &removed_env {
654            request_env.remove(name);
655        }
656        let env = self.forwarded_environment(&request_env, &removed_env);
657        let unset = removed_env
658            .iter()
659            .map(|name| format!("unset {name}; "))
660            .collect::<String>();
661        let command = request.command.as_posix_shell();
662        let script = format!(
663            "cd -- {} || exit $?; {} \
664             if command -v setsid >/dev/null 2>&1; then \
665               {}setsid sh -c {} & child=$!; target=-$child; \
666             else {}sh -c {} & child=$!; target=$child; fi; \
667             printf '%s' \"$target\" > {}; \
668             wait \"$child\"; status=$?; rm -f -- {}; exit \"$status\"",
669            shell_quote(cwd.as_str()),
670            unset,
671            env,
672            shell_quote(&command),
673            env,
674            shell_quote(&command),
675            shell_quote(&pid_file),
676            shell_quote(&pid_file),
677        );
678        let mut spawned = self.spawn_transport(&script, request.stdin).await?;
679        spawned.set_remote_token(token);
680        Ok(spawned)
681    }
682
683    fn forwarded_environment(
684        &self,
685        request_env: &BTreeMap<String, String>,
686        removed_env: &BTreeSet<String>,
687    ) -> String {
688        let mut values = BTreeMap::new();
689        for name in &self.env_allowlist {
690            if !removed_env.contains(name)
691                && let Ok(value) = std::env::var(name)
692            {
693                values.insert(name.clone(), value);
694            }
695        }
696        values.extend(request_env.clone());
697        values
698            .into_iter()
699            .filter(|(name, _)| valid_env_name(name))
700            .map(|(name, value)| format!("{name}={} ", shell_quote(&value)))
701            .collect()
702    }
703
704    async fn terminate(&self, handle: &ProcessHandle, grace: Duration) -> anyhow::Result<()> {
705        if let Some(token) = handle.remote_token() {
706            let pid_file = format!("/tmp/aidaemon-exec-{token}.pid");
707            let term = format!(
708                "p={}; if [ -f \"$p\" ]; then target=$(cat \"$p\"); \
709                 kill -TERM -- \"$target\" 2>/dev/null || \
710                 kill -TERM \"$target\" 2>/dev/null || true; fi",
711                shell_quote(&pid_file)
712            );
713            let _ = self
714                .run_transport(&term, None, Duration::from_secs(5))
715                .await;
716            tokio::time::sleep(grace).await;
717            let kill = format!(
718                "p={}; if [ -f \"$p\" ]; then target=$(cat \"$p\"); \
719                 kill -KILL -- \"$target\" 2>/dev/null || \
720                 kill -KILL \"$target\" 2>/dev/null || true; rm -f \"$p\"; fi",
721                shell_quote(&pid_file)
722            );
723            let _ = self
724                .run_transport(&kill, None, Duration::from_secs(5))
725                .await;
726        }
727        if let Some(pid) = handle.local_pid() {
728            send_sigterm(pid);
729            send_sigkill(pid);
730        }
731        Ok(())
732    }
733}
734
735pub struct SshBackend {
736    core: RemoteBackendCore,
737}
738
739impl SshBackend {
740    async fn new(
741        config: &SshExecutionConfig,
742        workspace_override: Option<&str>,
743        allow_outside_workspace: bool,
744    ) -> anyhow::Result<Self> {
745        anyhow::ensure!(
746            !config.host.trim().is_empty(),
747            "execution.ssh.host is required when execution.backend=\"ssh\""
748        );
749        ensure_local_executable("ssh").await?;
750        let mut args = vec![
751            "-o".to_string(),
752            "BatchMode=yes".to_string(),
753            "-o".to_string(),
754            format!("ConnectTimeout={}", config.connect_timeout_secs.max(1)),
755        ];
756        if let Some(port) = config.port {
757            args.push("-p".to_string());
758            args.push(port.to_string());
759        }
760        if let Some(identity_file) = &config.identity_file {
761            args.push("-i".to_string());
762            args.push(
763                expand_local_path(identity_file)?
764                    .to_string_lossy()
765                    .into_owned(),
766            );
767        }
768        args.extend(config.extra_args.clone());
769
770        let provisional = RemoteBackendCore {
771            kind: BackendKind::Ssh,
772            id: format!("ssh:{}", config.host),
773            approval_scope: format!("ssh:{}", config.host),
774            workspace_root: BackendPath::new(workspace_override.unwrap_or(&config.workspace_root)),
775            canonical_workspace_root: String::new(),
776            home: BackendPath::new("/"),
777            allow_outside_workspace: true,
778            env_allowlist: config.env_allowlist.clone(),
779            transport: RemoteTransport::Ssh {
780                host: config.host.clone(),
781                args,
782            },
783        };
784        let home_output = provisional
785            .run_transport(
786                "printf '%s\\n' \"$HOME\"; \
787                 fingerprint=$(cat /etc/machine-id 2>/dev/null || \
788                   hostname 2>/dev/null || printf unknown); \
789                 set -- ${SSH_CONNECTION:-}; \
790                 printf '%s|%s:%s\\n' \"$fingerprint\" \"${3:-unknown}\" \"${4:-unknown}\"",
791                None,
792                Duration::from_secs(config.connect_timeout_secs.max(1) + 5),
793            )
794            .await?;
795        let identity_text = remote_success("SSH connectivity check", home_output)?;
796        let mut identity_lines = identity_text.lines();
797        let home = identity_lines.next().unwrap_or_default().trim().to_string();
798        let remote_fingerprint = identity_lines.next().unwrap_or("unknown").trim();
799        anyhow::ensure!(!home.is_empty(), "SSH host returned an empty HOME");
800        let fingerprint_hash = hex::encode(Sha256::digest(remote_fingerprint.as_bytes()));
801
802        let workspace = workspace_override.unwrap_or(&config.workspace_root);
803        let workspace = if workspace == "~" {
804            home.clone()
805        } else if let Some(rest) = workspace.strip_prefix("~/") {
806            format!("{}/{}", home.trim_end_matches('/'), rest)
807        } else {
808            workspace.to_string()
809        };
810        let workspace = normalize_posix_absolute(&workspace)?;
811        if config.create_workspace {
812            let output = provisional
813                .run_transport(
814                    &format!("mkdir -p -- {}", shell_quote(&workspace)),
815                    None,
816                    Duration::from_secs(30),
817                )
818                .await?;
819            remote_success("create SSH workspace", output)?;
820        }
821        let canonical = provisional
822            .run_transport(
823                &format!("cd -P -- {} && pwd", shell_quote(&workspace)),
824                None,
825                Duration::from_secs(30),
826            )
827            .await?;
828        let canonical = remote_success("resolve SSH workspace", canonical)?
829            .trim()
830            .to_string();
831        let target_identity = format!(
832            "ssh:{}:{}:{}:{}",
833            config.host,
834            config.port.unwrap_or(22),
835            &fingerprint_hash[..16],
836            canonical
837        );
838
839        Ok(Self {
840            core: RemoteBackendCore {
841                id: target_identity.clone(),
842                approval_scope: target_identity,
843                workspace_root: BackendPath::new(canonical.clone()),
844                canonical_workspace_root: canonical,
845                home: BackendPath::new(home),
846                allow_outside_workspace,
847                ..provisional
848            },
849        })
850    }
851}
852
853macro_rules! delegate_remote_backend {
854    ($backend:ty) => {
855        #[async_trait]
856        impl ExecutionBackend for $backend {
857            fn kind(&self) -> BackendKind {
858                self.core.kind
859            }
860            fn id(&self) -> &str {
861                &self.core.id
862            }
863            fn approval_scope(&self) -> &str {
864                &self.core.approval_scope
865            }
866            fn workspace_root(&self) -> &BackendPath {
867                &self.core.workspace_root
868            }
869            fn home_hint(&self) -> &BackendPath {
870                &self.core.home
871            }
872            fn allows_outside_workspace(&self) -> bool {
873                self.core.allow_outside_workspace
874            }
875            async fn home_dir(&self) -> anyhow::Result<BackendPath> {
876                Ok(self.core.home.clone())
877            }
878            async fn resolve_path(&self, path: &str) -> anyhow::Result<BackendPath> {
879                self.core.resolve_path(path).await
880            }
881            async fn canonicalize(&self, path: &BackendPath) -> anyhow::Result<BackendPath> {
882                self.core.canonicalize(path).await
883            }
884            async fn metadata(&self, path: &BackendPath) -> anyhow::Result<BackendMetadata> {
885                self.core.metadata(path).await
886            }
887            async fn read(&self, path: &BackendPath) -> anyhow::Result<Vec<u8>> {
888                self.core.read(path).await
889            }
890            async fn write(
891                &self,
892                path: &BackendPath,
893                content: &[u8],
894                mode: WriteMode,
895                create_parents: bool,
896            ) -> anyhow::Result<()> {
897                self.core.write(path, content, mode, create_parents).await
898            }
899            async fn create_dir_all(&self, path: &BackendPath) -> anyhow::Result<()> {
900                self.core.create_dir_all(path).await
901            }
902            async fn copy(
903                &self,
904                source: &BackendPath,
905                destination: &BackendPath,
906            ) -> anyhow::Result<()> {
907                self.core.copy(source, destination).await
908            }
909            async fn rename(
910                &self,
911                source: &BackendPath,
912                destination: &BackendPath,
913            ) -> anyhow::Result<()> {
914                self.core.rename(source, destination).await
915            }
916            async fn remove_file(&self, path: &BackendPath) -> anyhow::Result<()> {
917                self.core.remove_file(path).await
918            }
919            async fn remove_empty_dir(&self, path: &BackendPath) -> anyhow::Result<()> {
920                self.core.remove_empty_dir(path).await
921            }
922            async fn read_dir(&self, path: &BackendPath) -> anyhow::Result<Vec<BackendDirEntry>> {
923                self.core.read_dir(path).await
924            }
925            async fn spawn(&self, request: ExecutionRequest) -> anyhow::Result<SpawnedProcess> {
926                self.core.spawn(request).await
927            }
928            async fn terminate(
929                &self,
930                handle: &ProcessHandle,
931                grace: Duration,
932            ) -> anyhow::Result<()> {
933                self.core.terminate(handle, grace).await
934            }
935        }
936    };
937}
938
939delegate_remote_backend!(SshBackend);
940
941#[cfg(feature = "docker")]
942pub struct DockerBackend {
943    core: RemoteBackendCore,
944}
945
946#[cfg(feature = "docker")]
947impl DockerBackend {
948    async fn new(
949        config: &DockerExecutionConfig,
950        workspace_override: Option<&str>,
951        allow_outside_workspace: bool,
952        config_path: &Path,
953    ) -> anyhow::Result<Self> {
954        ensure_local_executable("docker").await?;
955        anyhow::ensure!(
956            !config.container.trim().is_empty(),
957            "execution.docker.container cannot be empty"
958        );
959        let inspect = local_command_output(
960            "docker",
961            &["inspect", "--type", "container", &config.container],
962            Duration::from_secs(15),
963        )
964        .await?;
965        if inspect.exit_code != 0 {
966            anyhow::ensure!(
967                config.create_if_missing,
968                "Docker execution container {:?} does not exist and create_if_missing=false",
969                config.container
970            );
971            let host_workspace = match &config.host_workspace {
972                Some(path) => {
973                    let expanded = expand_local_path(path)?;
974                    if expanded.is_absolute() {
975                        expanded
976                    } else {
977                        config_path
978                            .parent()
979                            .unwrap_or_else(|| Path::new("."))
980                            .join(expanded)
981                    }
982                }
983                None => std::env::current_dir()?,
984            };
985            tokio::fs::create_dir_all(&host_workspace).await?;
986            let host_workspace = tokio::fs::canonicalize(host_workspace)
987                .await
988                .map(|p| dunce::simplified(&p).to_path_buf())?;
989            let workspace = workspace_override.unwrap_or(&config.workspace_root);
990            let mut args = vec![
991                "create".to_string(),
992                "--name".to_string(),
993                config.container.clone(),
994                "--init".to_string(),
995                "--workdir".to_string(),
996                workspace.to_string(),
997                "--network".to_string(),
998                config.network.clone(),
999                "--cap-drop".to_string(),
1000                "ALL".to_string(),
1001                "--security-opt".to_string(),
1002                "no-new-privileges".to_string(),
1003                "--mount".to_string(),
1004                format!(
1005                    "type=bind,src={},dst={}",
1006                    host_workspace.display(),
1007                    workspace
1008                ),
1009            ];
1010            if let Some(user) = &config.user {
1011                args.push("--user".to_string());
1012                args.push(user.clone());
1013            }
1014            args.extend([
1015                config.image.clone(),
1016                "sh".to_string(),
1017                "-c".to_string(),
1018                "trap 'exit 0' TERM INT; while :; do sleep 3600; done".to_string(),
1019            ]);
1020            let refs = args.iter().map(String::as_str).collect::<Vec<_>>();
1021            let created = local_command_output("docker", &refs, Duration::from_secs(120)).await?;
1022            anyhow::ensure!(
1023                created.exit_code == 0,
1024                "Failed to create Docker execution container: {}",
1025                created.stderr_lossy().trim()
1026            );
1027        }
1028        let start = local_command_output(
1029            "docker",
1030            &["start", &config.container],
1031            Duration::from_secs(60),
1032        )
1033        .await?;
1034        anyhow::ensure!(
1035            start.exit_code == 0,
1036            "Failed to start Docker execution container: {}",
1037            start.stderr_lossy().trim()
1038        );
1039        let identity = local_command_output(
1040            "docker",
1041            &["inspect", "--format", "{{.Id}}", &config.container],
1042            Duration::from_secs(15),
1043        )
1044        .await?;
1045        anyhow::ensure!(
1046            identity.exit_code == 0,
1047            "Failed to identify Docker execution container: {}",
1048            identity.stderr_lossy().trim()
1049        );
1050        let container_id = identity.stdout_lossy().trim().to_string();
1051        anyhow::ensure!(
1052            !container_id.is_empty(),
1053            "Docker returned an empty container identity"
1054        );
1055
1056        let workspace =
1057            normalize_posix_absolute(workspace_override.unwrap_or(&config.workspace_root))?;
1058        let provisional = RemoteBackendCore {
1059            kind: BackendKind::Docker,
1060            id: format!("docker:{}", config.container),
1061            approval_scope: format!("docker:{}", config.container),
1062            workspace_root: BackendPath::new(workspace.clone()),
1063            canonical_workspace_root: workspace.clone(),
1064            home: BackendPath::new("/root"),
1065            allow_outside_workspace: true,
1066            env_allowlist: config.env_allowlist.clone(),
1067            transport: RemoteTransport::Docker {
1068                container: config.container.clone(),
1069                user: config.user.clone(),
1070            },
1071        };
1072        let ready = provisional
1073            .run_transport(
1074                &format!(
1075                    "mkdir -p -- {} && cd -P -- {} && pwd && printf '%s\\n' \"$HOME\"",
1076                    shell_quote(&workspace),
1077                    shell_quote(&workspace)
1078                ),
1079                None,
1080                Duration::from_secs(30),
1081            )
1082            .await?;
1083        let text = remote_success("initialize Docker execution workspace", ready)?;
1084        let mut lines = text.lines();
1085        let canonical = lines.next().unwrap_or(&workspace).trim().to_string();
1086        let home = lines
1087            .next()
1088            .map(str::trim)
1089            .filter(|home| !home.is_empty())
1090            .unwrap_or(&canonical)
1091            .to_string();
1092        let target_identity = format!("docker:{container_id}:{canonical}");
1093        Ok(Self {
1094            core: RemoteBackendCore {
1095                id: target_identity.clone(),
1096                approval_scope: target_identity,
1097                workspace_root: BackendPath::new(canonical.clone()),
1098                canonical_workspace_root: canonical,
1099                home: BackendPath::new(home),
1100                allow_outside_workspace,
1101                ..provisional
1102            },
1103        })
1104    }
1105}
1106
1107#[cfg(feature = "docker")]
1108delegate_remote_backend!(DockerBackend);
1109
1110fn parse_remote_metadata(value: &str) -> anyhow::Result<BackendMetadata> {
1111    let mut parts = value.split('\t');
1112    let kind = match parts.next() {
1113        Some("f") => BackendFileType::File,
1114        Some("d") => BackendFileType::Directory,
1115        Some("l") => BackendFileType::Symlink,
1116        Some("o") => BackendFileType::Other,
1117        _ => anyhow::bail!("remote backend returned invalid metadata: {value:?}"),
1118    };
1119    let len = parts
1120        .next()
1121        .unwrap_or("0")
1122        .trim()
1123        .parse::<u64>()
1124        .unwrap_or(0);
1125    let seconds = parts
1126        .next()
1127        .unwrap_or("0")
1128        .trim()
1129        .parse::<u64>()
1130        .unwrap_or(0);
1131    Ok(BackendMetadata {
1132        file_type: kind,
1133        len,
1134        modified: (seconds > 0).then(|| UNIX_EPOCH + Duration::from_secs(seconds)),
1135    })
1136}
1137
1138fn remote_success(operation: &str, output: ExecutionOutput) -> anyhow::Result<String> {
1139    if output.timed_out {
1140        return Err(crate::ToolTimedOut(format!(
1141            "Remote {operation} timed out after {}ms",
1142            output.duration_ms
1143        ))
1144        .into());
1145    }
1146    anyhow::ensure!(
1147        output.exit_code == 0,
1148        "Remote {operation} failed (exit {}): {}",
1149        output.exit_code,
1150        output.stderr_lossy().trim()
1151    );
1152    Ok(output.stdout_lossy())
1153}
1154
1155fn valid_env_name(name: &str) -> bool {
1156    let mut chars = name.chars();
1157    chars
1158        .next()
1159        .is_some_and(|first| first == '_' || first.is_ascii_alphabetic())
1160        && chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric())
1161}
1162
1163fn ensure_posix_descendant(path: &str, root: &str) -> anyhow::Result<()> {
1164    let root = root.trim_end_matches('/');
1165    anyhow::ensure!(
1166        path == root || path.starts_with(&format!("{root}/")),
1167        "Path is outside execution workspace {root}: {path}"
1168    );
1169    Ok(())
1170}
1171
1172async fn ensure_local_executable(executable: &str) -> anyhow::Result<()> {
1173    let output = local_command_output(
1174        "sh",
1175        &["-c", &format!("command -v {executable}")],
1176        Duration::from_secs(5),
1177    )
1178    .await?;
1179    anyhow::ensure!(
1180        output.exit_code == 0,
1181        "Required executable {:?} was not found on the daemon host",
1182        executable
1183    );
1184    Ok(())
1185}
1186
1187async fn local_command_output(
1188    program: &str,
1189    args: &[&str],
1190    timeout: Duration,
1191) -> anyhow::Result<ExecutionOutput> {
1192    let started = Instant::now();
1193    let mut command = Command::new(program);
1194    command
1195        .args(args)
1196        .stdout(Stdio::piped())
1197        .stderr(Stdio::piped())
1198        .kill_on_drop(true);
1199    configure_command_for_process_group(&mut command);
1200    let mut child = command.spawn()?;
1201    let pid = child.id().unwrap_or(0);
1202    let stdout = child
1203        .stdout
1204        .take()
1205        .ok_or_else(|| anyhow::anyhow!("stdout unavailable"))?;
1206    let stderr = child
1207        .stderr
1208        .take()
1209        .ok_or_else(|| anyhow::anyhow!("stderr unavailable"))?;
1210    let stdout_task = tokio::spawn(async move {
1211        let mut reader = stdout;
1212        let mut bytes = Vec::new();
1213        tokio::io::AsyncReadExt::read_to_end(&mut reader, &mut bytes).await?;
1214        Ok::<_, std::io::Error>(bytes)
1215    });
1216    let stderr_task = tokio::spawn(async move {
1217        let mut reader = stderr;
1218        let mut bytes = Vec::new();
1219        tokio::io::AsyncReadExt::read_to_end(&mut reader, &mut bytes).await?;
1220        Ok::<_, std::io::Error>(bytes)
1221    });
1222    let (status, timed_out) = match tokio::time::timeout(timeout, child.wait()).await {
1223        Ok(status) => (Some(status?), false),
1224        Err(_) => {
1225            terminate_process_tree(pid, &mut child, Duration::from_secs(1)).await;
1226            (None, true)
1227        }
1228    };
1229    Ok(ExecutionOutput {
1230        exit_code: status.and_then(|status| status.code()).unwrap_or(-1),
1231        stdout: stdout_task
1232            .await
1233            .ok()
1234            .and_then(Result::ok)
1235            .unwrap_or_default(),
1236        stderr: stderr_task
1237            .await
1238            .ok()
1239            .and_then(Result::ok)
1240            .unwrap_or_default(),
1241        duration_ms: started.elapsed().as_millis() as u64,
1242        timed_out,
1243    })
1244}
1245
1246#[cfg(test)]
1247mod tests {
1248    use super::*;
1249    use crate::LexicalPaths;
1250    use crate::backend::normalize_path_lexically;
1251    use std::path::PathBuf;
1252    use tempfile::TempDir;
1253
1254    #[test]
1255    fn local_backend_is_shared_as_the_one_trait() {
1256        let local: Arc<dyn ExecutionBackend> = Arc::new(LocalBackend::current_unrestricted());
1257        let shared: SharedExecutionBackend = local.clone();
1258        assert_eq!(shared.kind(), BackendKind::Local);
1259        assert_eq!(local.id(), shared.id());
1260    }
1261
1262    #[test]
1263    fn local_execution_path_includes_user_tool_roots() {
1264        let home = BackendPath::new("/synthetic/home");
1265        let path = crate::local_backend::local_execution_search_path(&home);
1266        let directories = std::env::split_paths(std::ffi::OsStr::new(&path)).collect::<Vec<_>>();
1267        assert!(directories.contains(&PathBuf::from("/synthetic/home/.cargo/bin")));
1268        assert!(directories.contains(&PathBuf::from("/synthetic/home/.local/bin")));
1269        assert!(directories.contains(&PathBuf::from("/usr/bin")));
1270    }
1271
1272    async fn backend_contract(backend: &dyn ExecutionBackend) -> anyhow::Result<()> {
1273        let path = backend.resolve_path("nested/value.txt").await?;
1274        backend
1275            .write(&path, b"from file api\n", WriteMode::Overwrite, true)
1276            .await?;
1277
1278        let output = backend
1279            .execute(
1280                ExecutionRequest::shell(
1281                    "cat nested/value.txt && printf 'from command\\n' >> nested/value.txt",
1282                ),
1283                Duration::from_secs(5),
1284            )
1285            .await?;
1286        anyhow::ensure!(output.exit_code == 0, "shell command failed");
1287        anyhow::ensure!(output.stdout_lossy() == "from file api\n");
1288        anyhow::ensure!(
1289            String::from_utf8(backend.read(&path).await?)? == "from file api\nfrom command\n"
1290        );
1291
1292        let mut argv = ExecutionRequest::argv(
1293            "sh",
1294            vec![
1295                "-c".to_string(),
1296                "printf '%s' \"$1\"".to_string(),
1297                "sh".to_string(),
1298                "literal value; $(not-executed) 'quoted'".to_string(),
1299            ],
1300        );
1301        argv.env.insert(
1302            "AIDAEMON_CONTRACT_ENV".to_string(),
1303            "visible value".to_string(),
1304        );
1305        argv.env.insert(
1306            "AIDAEMON_CONTRACT_REMOVED".to_string(),
1307            "must-not-leak".to_string(),
1308        );
1309        argv.env_remove
1310            .push("AIDAEMON_CONTRACT_REMOVED".to_string());
1311        let output = backend.execute(argv, Duration::from_secs(5)).await?;
1312        anyhow::ensure!(output.exit_code == 0, "argv command failed");
1313        anyhow::ensure!(
1314            output.stdout_lossy() == "literal value; $(not-executed) 'quoted'",
1315            "argv quoting changed the literal argument"
1316        );
1317
1318        let mut environment = ExecutionRequest::shell(
1319            "test \"$AIDAEMON_CONTRACT_ENV\" = 'visible value' && \
1320             test -z \"${AIDAEMON_CONTRACT_REMOVED+x}\"",
1321        );
1322        environment.env.insert(
1323            "AIDAEMON_CONTRACT_ENV".to_string(),
1324            "visible value".to_string(),
1325        );
1326        environment.env.insert(
1327            "AIDAEMON_CONTRACT_REMOVED".to_string(),
1328            "must-not-leak".to_string(),
1329        );
1330        environment
1331            .env_remove
1332            .push("AIDAEMON_CONTRACT_REMOVED".to_string());
1333        let output = backend.execute(environment, Duration::from_secs(5)).await?;
1334        anyhow::ensure!(output.exit_code == 0, "environment contract failed");
1335
1336        let nested = backend.resolve_path("nested").await?;
1337        let entries = backend.read_dir(&nested).await?;
1338        anyhow::ensure!(
1339            entries
1340                .iter()
1341                .any(|entry| entry.path.file_name() == Some("value.txt"))
1342        );
1343        anyhow::ensure!(backend.metadata(&path).await?.is_file());
1344
1345        let copy = backend.resolve_path("nested/copied.txt").await?;
1346        let renamed = backend.resolve_path("nested/renamed.txt").await?;
1347        backend.copy(&path, &copy).await?;
1348        backend.rename(&copy, &renamed).await?;
1349        anyhow::ensure!(backend.metadata(&renamed).await?.is_file());
1350        backend.remove_file(&renamed).await?;
1351        anyhow::ensure!(backend.metadata(&renamed).await.is_err());
1352
1353        let host_temp = TempDir::new()?;
1354        let host_source = host_temp.path().join("attachment.txt");
1355        tokio::fs::write(&host_source, b"attachment bytes").await?;
1356        let imported_destination = backend.resolve_path("inbox/attachment.txt").await?;
1357        let imported = backend
1358            .import_local_file(&host_source, &imported_destination)
1359            .await?;
1360        anyhow::ensure!(backend.read(&imported).await? == b"attachment bytes");
1361        let host_export = host_temp.path().join("exported.txt");
1362        backend.export_local_file(&imported, &host_export).await?;
1363        anyhow::ensure!(tokio::fs::read(host_export).await? == b"attachment bytes");
1364
1365        anyhow::ensure!(
1366            backend.resolve_path("../outside-workspace").await.is_err(),
1367            "confined backend accepted a workspace escape"
1368        );
1369        Ok(())
1370    }
1371
1372    #[tokio::test]
1373    async fn local_backend_round_trip_and_command_share_workspace() {
1374        let temp = TempDir::new().unwrap();
1375        let config = ExecutionConfig {
1376            workspace_root: Some(temp.path().to_string_lossy().into_owned()),
1377            allow_outside_workspace: Some(false),
1378            ..ExecutionConfig::default()
1379        };
1380        let backend = local_backend(&config).await.unwrap();
1381        backend_contract(&backend).await.unwrap();
1382    }
1383
1384    #[tokio::test]
1385    async fn local_backend_can_confine_workspace() {
1386        let temp = TempDir::new().unwrap();
1387        let config = ExecutionConfig {
1388            workspace_root: Some(temp.path().to_string_lossy().into_owned()),
1389            allow_outside_workspace: Some(false),
1390            ..ExecutionConfig::default()
1391        };
1392        let backend = local_backend(&config).await.unwrap();
1393        assert!(backend.resolve_path("ok.txt").await.is_ok());
1394        assert!(backend.resolve_path("/etc/passwd").await.is_err());
1395    }
1396
1397    /// A daemon secret in the process environment never reaches a command
1398    /// on the local backend; an allowlisted variable does, and so does one
1399    /// the request sets itself.
1400    #[tokio::test]
1401    async fn local_commands_do_not_inherit_daemon_secrets() {
1402        // SAFETY: names unique to this test; nothing else reads them.
1403        unsafe {
1404            std::env::set_var("AIDAEMON_SYNTHETIC_SECRET_KEY", "synthetic-secret-value");
1405            std::env::set_var("AIDAEMON_SYNTHETIC_ALLOWED", "synthetic-allowed-value");
1406        }
1407        let backend =
1408            LocalBackend::current_unrestricted().with_env_allowlist(["AIDAEMON_SYNTHETIC_ALLOWED"]);
1409        let mut request = ExecutionRequest::shell("env");
1410        request.env.insert(
1411            "AIDAEMON_REQUEST_VAR".to_string(),
1412            "set-by-request".to_string(),
1413        );
1414        let output = backend
1415            .execute(request, std::time::Duration::from_secs(10))
1416            .await
1417            .unwrap();
1418        let env = output.stdout_lossy();
1419        assert!(!env.contains("synthetic-secret-value"), "{env}");
1420        assert!(env.contains("AIDAEMON_SYNTHETIC_ALLOWED=synthetic-allowed-value"));
1421        assert!(env.contains("AIDAEMON_REQUEST_VAR=set-by-request"));
1422        assert!(env.contains("PATH="), "{env}");
1423        assert!(env.contains("HOME="), "{env}");
1424    }
1425
1426    #[test]
1427    fn lexical_paths_normalize_exactly_as_their_backend() {
1428        let backend = LocalBackend::current_unrestricted();
1429        let paths = LexicalPaths::of(&backend);
1430        for path in ["relative/file.txt", "~/notes.md", "~", "/tmp/a/../b"] {
1431            assert_eq!(
1432                paths.normalize(path).unwrap(),
1433                normalize_path_lexically(&backend, path).unwrap(),
1434                "{path}"
1435            );
1436        }
1437    }
1438
1439    #[test]
1440    fn posix_normalization_rejects_root_escape() {
1441        assert_eq!(
1442            normalize_posix_absolute("/workspace/a/../b").unwrap(),
1443            "/workspace/b"
1444        );
1445        assert!(normalize_posix_absolute("/../etc/passwd").is_err());
1446    }
1447
1448    #[test]
1449    fn shell_quoting_is_literal() {
1450        assert_eq!(shell_quote("a'b"), "'a'\"'\"'b'");
1451    }
1452
1453    #[test]
1454    fn backend_path_keeps_posix_separators_and_extensions() {
1455        let path = BackendPath::new("/workspace/nested");
1456        let file = path.join("value.test.txt");
1457        assert_eq!(file.as_str(), "/workspace/nested/value.test.txt");
1458        assert_eq!(file.parent().unwrap().as_str(), "/workspace/nested");
1459        assert_eq!(file.file_name(), Some("value.test.txt"));
1460        assert_eq!(file.extension(), Some("txt"));
1461        assert_eq!(
1462            file.with_extension("bak").as_str(),
1463            "/workspace/nested/value.test.bak"
1464        );
1465    }
1466
1467    #[test]
1468    fn ssh_default_workspace_is_user_writable() {
1469        assert_eq!(
1470            SshExecutionConfig::default().workspace_root,
1471            "~/aidaemon-workspace"
1472        );
1473    }
1474
1475    #[cfg(feature = "docker")]
1476    #[tokio::test]
1477    #[ignore = "requires a running Docker daemon; opt in with AIDAEMON_RUN_DOCKER_TEST=1"]
1478    async fn docker_backend_matches_execution_contract() {
1479        if std::env::var("AIDAEMON_RUN_DOCKER_TEST").as_deref() != Ok("1") {
1480            return;
1481        }
1482        let temp = TempDir::new().unwrap();
1483        let suffix = uuid::Uuid::new_v4().simple().to_string();
1484        let container = format!("aidaemon-contract-{}", &suffix[..12]);
1485        let config = DockerExecutionConfig {
1486            container: container.clone(),
1487            image: std::env::var("AIDAEMON_TEST_DOCKER_IMAGE")
1488                .unwrap_or_else(|_| "alpine:3.20".to_string()),
1489            host_workspace: Some(temp.path().to_string_lossy().into_owned()),
1490            ..DockerExecutionConfig::default()
1491        };
1492        let config_path = temp.path().join("config.toml");
1493
1494        let result = async {
1495            let backend = DockerBackend::new(&config, None, false, &config_path).await?;
1496            backend_contract(&backend).await
1497        }
1498        .await;
1499        let _ = local_command_output("docker", &["rm", "-f", &container], Duration::from_secs(30))
1500            .await;
1501        result.unwrap();
1502    }
1503
1504    #[tokio::test]
1505    #[ignore = "requires AIDAEMON_TEST_SSH_HOST pointing to an isolated test account"]
1506    async fn ssh_backend_matches_execution_contract() {
1507        let Ok(host) = std::env::var("AIDAEMON_TEST_SSH_HOST") else {
1508            return;
1509        };
1510        let suffix = uuid::Uuid::new_v4().simple().to_string();
1511        let workspace = format!("/tmp/aidaemon-contract-{}", &suffix[..12]);
1512        let config = SshExecutionConfig {
1513            host,
1514            workspace_root: workspace.clone(),
1515            port: std::env::var("AIDAEMON_TEST_SSH_PORT")
1516                .ok()
1517                .and_then(|port| port.parse().ok()),
1518            identity_file: std::env::var("AIDAEMON_TEST_SSH_IDENTITY_FILE").ok(),
1519            extra_args: std::env::var("AIDAEMON_TEST_SSH_EXTRA_ARGS")
1520                .ok()
1521                .and_then(|args| shell_words::split(&args).ok())
1522                .unwrap_or_default(),
1523            ..SshExecutionConfig::default()
1524        };
1525        let result = async {
1526            let backend = SshBackend::new(&config, None, false).await?;
1527            backend_contract(&backend).await?;
1528            let cleanup = backend
1529                .execute(
1530                    ExecutionRequest::shell(format!("rm -rf -- {}", shell_quote(&workspace))),
1531                    Duration::from_secs(30),
1532                )
1533                .await?;
1534            anyhow::ensure!(cleanup.exit_code == 0, "SSH test workspace cleanup failed");
1535            Ok::<_, anyhow::Error>(())
1536        }
1537        .await;
1538        result.unwrap();
1539    }
1540}