Skip to main content

aidaemon_tools/
local_backend.rs

1//! The host's own filesystem and processes as an [`ExecutionBackend`].
2
3use std::ffi::OsStr;
4use std::path::{Path, PathBuf};
5use std::process::Stdio;
6use std::time::Duration;
7
8use async_trait::async_trait;
9use tokio::io::AsyncWriteExt;
10use tokio::process::Command;
11
12use crate::backend::{
13    BackendDirEntry, BackendFileType, BackendKind, BackendMetadata, BackendPath, CommandSpec,
14    ExecutionBackend, ExecutionRequest, ProcessHandle, SpawnedProcess, WriteMode,
15    normalize_local_lexically,
16};
17use crate::process_control::{configure_command_for_process_group, send_sigkill, send_sigterm};
18
19/// Build the executable search path used by local agent processes.
20///
21/// Service managers commonly start daemons with only the system directories in
22/// `PATH`, even when the owner installed development tools in user-local
23/// prefixes.  Keep one backend-owned search contract instead of teaching each
24/// tool about individual executables. Explicit per-request PATH values and
25/// removals still win at the spawn boundary.
26pub fn local_execution_search_path(home: &BackendPath) -> String {
27    let mut directories = Vec::<String>::new();
28    let mut push = |value: String| {
29        if !value.trim().is_empty() && !directories.iter().any(|existing| existing == &value) {
30            directories.push(value);
31        }
32    };
33
34    if let Some(path) = std::env::var_os("PATH") {
35        for directory in std::env::split_paths(&path) {
36            if directory.is_absolute() {
37                push(directory.to_string_lossy().into_owned());
38            }
39        }
40    }
41    for relative in [
42        ".local/bin",
43        ".cargo/bin",
44        ".npm-global/bin",
45        ".bun/bin",
46        ".deno/bin",
47        "go/bin",
48        "miniforge3/bin",
49        "anaconda3/bin",
50        "bin",
51    ] {
52        push(home.join(relative).to_string());
53    }
54    #[cfg(unix)]
55    for directory in [
56        "/opt/homebrew/bin",
57        "/opt/homebrew/sbin",
58        "/usr/local/bin",
59        "/usr/local/sbin",
60        "/usr/bin",
61        "/bin",
62        "/usr/sbin",
63        "/sbin",
64    ] {
65        push(directory.to_string());
66    }
67    std::env::join_paths(directories)
68        .unwrap_or_default()
69        .to_string_lossy()
70        .into_owned()
71}
72
73/// The local backend: the host filesystem, confined to a workspace unless
74/// told otherwise.
75pub struct LocalBackend {
76    id: String,
77    approval_scope: String,
78    workspace_root: BackendPath,
79    canonical_workspace_root: PathBuf,
80    home: BackendPath,
81    allow_outside_workspace: bool,
82    /// Host variables a command inherits. Everything else in the daemon's
83    /// environment (provider keys, the encryption key) stays out.
84    env_allowlist: Vec<String>,
85}
86
87/// Host variables a local command inherits by default: what shells, build
88/// tools and version managers need to find things, and nothing that carries
89/// a credential. A name ending in `*` is a prefix. `[execution]
90/// env_allowlist` adds names.
91pub const LOCAL_ENV_ALLOWLIST: &[&str] = &[
92    "HOME",
93    "USER",
94    "LOGNAME",
95    "SHELL",
96    "LANG",
97    "LANGUAGE",
98    "LC_*",
99    "TERM",
100    "COLORTERM",
101    "TZ",
102    "TMPDIR",
103    "TMP",
104    "TEMP",
105    "XDG_*",
106    "SSH_AUTH_SOCK",
107    "DISPLAY",
108    "WAYLAND_DISPLAY",
109    "DBUS_SESSION_BUS_ADDRESS",
110    "EDITOR",
111    "VISUAL",
112    "PAGER",
113    "CARGO_HOME",
114    "RUSTUP_HOME",
115    "GOPATH",
116    "GOROOT",
117    "JAVA_HOME",
118    "NVM_DIR",
119    "PYENV_ROOT",
120    "VIRTUAL_ENV",
121    "CONDA_PREFIX",
122    "HOMEBREW_PREFIX",
123    "HOMEBREW_CELLAR",
124    "HOMEBREW_REPOSITORY",
125    "__CF_USER_TEXT_ENCODING",
126    // Windows: what PowerShell and Windows programs need to start and find
127    // things (names there match whatever their case).
128    "SYSTEMROOT",
129    "SYSTEMDRIVE",
130    "COMSPEC",
131    "PATHEXT",
132    "WINDIR",
133    "USERPROFILE",
134    "USERNAME",
135    "USERDOMAIN",
136    "HOMEDRIVE",
137    "HOMEPATH",
138    "APPDATA",
139    "LOCALAPPDATA",
140    "PROGRAMDATA",
141    "PROGRAMFILES",
142    "PROGRAMFILES(X86)",
143    "PROGRAMW6432",
144    "COMMONPROGRAMFILES",
145    "COMMONPROGRAMFILES(X86)",
146    "COMMONPROGRAMW6432",
147    "ALLUSERSPROFILE",
148    "PUBLIC",
149    "PSMODULEPATH",
150    "OS",
151    "PROCESSOR_ARCHITECTURE",
152    "NUMBER_OF_PROCESSORS",
153    // Paths to the daemon's own config, env file and working directory
154    // (never their contents), for an `aidaemon` command run from a shell.
155    "AIDAEMON_RUNTIME_*",
156];
157
158fn env_name_allowed(allowlist: &[String], name: &str) -> bool {
159    // Windows variable names have no case: `windir` is `WINDIR`.
160    let same = |a: &str, b: &str| {
161        if cfg!(windows) {
162            a.eq_ignore_ascii_case(b)
163        } else {
164            a == b
165        }
166    };
167    allowlist.iter().any(|entry| match entry.strip_suffix('*') {
168        Some(prefix) => name
169            .get(..prefix.len())
170            .is_some_and(|start| same(start, prefix)),
171        None => same(entry, name),
172    })
173}
174
175fn default_env_allowlist() -> Vec<String> {
176    LOCAL_ENV_ALLOWLIST.iter().map(|s| s.to_string()).collect()
177}
178
179impl LocalBackend {
180    /// The current directory as workspace, with no confinement: for tests
181    /// that construct a tool directly.
182    pub fn current_unrestricted() -> Self {
183        let workspace = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
184        let canonical_workspace_root =
185            dunce::canonicalize(&workspace).unwrap_or_else(|_| workspace.clone());
186        let workspace_root =
187            BackendPath::new(canonical_workspace_root.to_string_lossy().into_owned());
188        let home = dirs::home_dir().unwrap_or_else(|| canonical_workspace_root.clone());
189        Self {
190            id: format!("local:{}", workspace_root.as_str()),
191            approval_scope: "local".to_string(),
192            workspace_root,
193            canonical_workspace_root,
194            home: BackendPath::new(home.to_string_lossy().into_owned()),
195            allow_outside_workspace: true,
196            env_allowlist: default_env_allowlist(),
197        }
198    }
199
200    /// Let commands also inherit these host variables (a trailing `*` is a
201    /// prefix), on top of [`LOCAL_ENV_ALLOWLIST`].
202    pub fn with_env_allowlist(
203        mut self,
204        names: impl IntoIterator<Item = impl Into<String>>,
205    ) -> Self {
206        self.env_allowlist.extend(names.into_iter().map(Into::into));
207        self
208    }
209
210    /// A backend rooted at `workspace_root` (`~` expanded; default: the
211    /// current directory, created if missing). Paths outside it are refused
212    /// unless `allow_outside_workspace`.
213    pub async fn new(
214        workspace_root: Option<&str>,
215        allow_outside_workspace: bool,
216    ) -> anyhow::Result<Self> {
217        let cwd = std::env::current_dir()?;
218        let workspace = workspace_root
219            .map(expand_local_path)
220            .transpose()?
221            .unwrap_or(cwd);
222        tokio::fs::create_dir_all(&workspace).await?;
223        let canonical_workspace_root = tokio::fs::canonicalize(&workspace)
224            .await
225            .map(|p| dunce::simplified(&p).to_path_buf())?;
226        let workspace_root =
227            BackendPath::new(canonical_workspace_root.to_string_lossy().into_owned());
228        let home = dirs::home_dir().unwrap_or_else(|| canonical_workspace_root.clone());
229        Ok(Self {
230            id: format!("local:{}", workspace_root.as_str()),
231            approval_scope: "local".to_string(),
232            workspace_root,
233            canonical_workspace_root,
234            home: BackendPath::new(home.to_string_lossy().into_owned()),
235            allow_outside_workspace,
236            env_allowlist: default_env_allowlist(),
237        })
238    }
239
240    fn host_path(&self, path: &BackendPath) -> PathBuf {
241        PathBuf::from(path.as_str())
242    }
243
244    async fn ensure_allowed(&self, path: &Path) -> anyhow::Result<()> {
245        if self.allow_outside_workspace {
246            return Ok(());
247        }
248        let canonical = canonicalize_existing_or_parent(path).await?;
249        anyhow::ensure!(
250            canonical.starts_with(&self.canonical_workspace_root),
251            "Path is outside execution workspace {}: {}",
252            self.workspace_root,
253            path.display()
254        );
255        Ok(())
256    }
257}
258
259#[async_trait]
260impl ExecutionBackend for LocalBackend {
261    fn kind(&self) -> BackendKind {
262        BackendKind::Local
263    }
264
265    fn id(&self) -> &str {
266        &self.id
267    }
268
269    fn approval_scope(&self) -> &str {
270        &self.approval_scope
271    }
272
273    fn workspace_root(&self) -> &BackendPath {
274        &self.workspace_root
275    }
276
277    fn home_hint(&self) -> &BackendPath {
278        &self.home
279    }
280
281    fn allows_outside_workspace(&self) -> bool {
282        self.allow_outside_workspace
283    }
284
285    async fn home_dir(&self) -> anyhow::Result<BackendPath> {
286        Ok(self.home.clone())
287    }
288
289    async fn resolve_path(&self, path: &str) -> anyhow::Result<BackendPath> {
290        let expanded = if path == "~" {
291            self.home.as_str().to_string()
292        } else if let Some(rest) = path.strip_prefix("~/") {
293            self.home.join(rest).as_str().to_string()
294        } else {
295            path.to_string()
296        };
297        let candidate = PathBuf::from(&expanded);
298        let joined = if candidate.is_absolute() {
299            candidate
300        } else {
301            self.host_path(&self.workspace_root).join(candidate)
302        };
303        let normalized = normalize_local_lexically(&joined)?;
304        self.ensure_allowed(&normalized).await?;
305        Ok(BackendPath::new(normalized.to_string_lossy().into_owned()))
306    }
307
308    async fn canonicalize(&self, path: &BackendPath) -> anyhow::Result<BackendPath> {
309        let host = self.host_path(path);
310        self.ensure_allowed(&host).await?;
311        let canonical = tokio::fs::canonicalize(host)
312            .await
313            .map(|p| dunce::simplified(&p).to_path_buf())?;
314        self.ensure_allowed(&canonical).await?;
315        Ok(BackendPath::new(canonical.to_string_lossy().into_owned()))
316    }
317
318    async fn metadata(&self, path: &BackendPath) -> anyhow::Result<BackendMetadata> {
319        let host = self.host_path(path);
320        self.ensure_allowed(&host).await?;
321        let metadata = tokio::fs::symlink_metadata(host).await?;
322        Ok(metadata_from_std(metadata))
323    }
324
325    async fn read(&self, path: &BackendPath) -> anyhow::Result<Vec<u8>> {
326        let host = self.host_path(path);
327        self.ensure_allowed(&host).await?;
328        Ok(tokio::fs::read(host).await?)
329    }
330
331    async fn write(
332        &self,
333        path: &BackendPath,
334        content: &[u8],
335        mode: WriteMode,
336        create_parents: bool,
337    ) -> anyhow::Result<()> {
338        let host = self.host_path(path);
339        self.ensure_allowed(&host).await?;
340        if create_parents && let Some(parent) = host.parent() {
341            tokio::fs::create_dir_all(parent).await?;
342        }
343        match mode {
344            WriteMode::Append => {
345                let mut file = tokio::fs::OpenOptions::new()
346                    .create(true)
347                    .append(true)
348                    .open(host)
349                    .await?;
350                file.write_all(content).await?;
351                file.flush().await?;
352            }
353            WriteMode::Overwrite => {
354                let temp = sibling_temp_path(&host, "write");
355                tokio::fs::write(&temp, content).await?;
356                tokio::fs::rename(temp, host).await?;
357            }
358        }
359        Ok(())
360    }
361
362    async fn create_dir_all(&self, path: &BackendPath) -> anyhow::Result<()> {
363        let host = self.host_path(path);
364        self.ensure_allowed(&host).await?;
365        tokio::fs::create_dir_all(host).await?;
366        Ok(())
367    }
368
369    async fn copy(&self, source: &BackendPath, destination: &BackendPath) -> anyhow::Result<()> {
370        let source = self.host_path(source);
371        let destination = self.host_path(destination);
372        self.ensure_allowed(&source).await?;
373        self.ensure_allowed(&destination).await?;
374        tokio::fs::copy(source, destination).await?;
375        Ok(())
376    }
377
378    #[allow(dead_code)]
379    async fn rename(&self, source: &BackendPath, destination: &BackendPath) -> anyhow::Result<()> {
380        let source = self.host_path(source);
381        let destination = self.host_path(destination);
382        self.ensure_allowed(&source).await?;
383        self.ensure_allowed(&destination).await?;
384        tokio::fs::rename(source, destination).await?;
385        Ok(())
386    }
387
388    #[allow(dead_code)]
389    async fn remove_file(&self, path: &BackendPath) -> anyhow::Result<()> {
390        let host = self.host_path(path);
391        self.ensure_allowed(&host).await?;
392        tokio::fs::remove_file(host).await?;
393        Ok(())
394    }
395
396    async fn remove_empty_dir(&self, path: &BackendPath) -> anyhow::Result<()> {
397        let host = self.host_path(path);
398        self.ensure_allowed(&host).await?;
399        tokio::fs::remove_dir(host).await?;
400        Ok(())
401    }
402
403    async fn read_dir(&self, path: &BackendPath) -> anyhow::Result<Vec<BackendDirEntry>> {
404        let host = self.host_path(path);
405        self.ensure_allowed(&host).await?;
406        let mut entries = tokio::fs::read_dir(host).await?;
407        let mut output = Vec::new();
408        while let Some(entry) = entries.next_entry().await? {
409            output.push(BackendDirEntry {
410                path: BackendPath::new(entry.path().to_string_lossy().into_owned()),
411                metadata: metadata_from_std(entry.metadata().await?),
412            });
413        }
414        Ok(output)
415    }
416
417    async fn spawn(&self, request: ExecutionRequest) -> anyhow::Result<SpawnedProcess> {
418        let cwd = request.cwd.as_ref().unwrap_or(&self.workspace_root).clone();
419        let cwd_host = self.host_path(&cwd);
420        self.ensure_allowed(&cwd_host).await?;
421
422        let explicit_path = request.env.contains_key("PATH");
423        let removes_path = request.env_remove.iter().any(|name| name == "PATH");
424
425        let mut command = match request.command {
426            CommandSpec::Shell(shell) => crate::platform_shell::shell_command(&shell),
427            CommandSpec::Argv { program, args } => {
428                let mut command = Command::new(program);
429                command.args(args);
430                command
431            }
432        };
433        command.env_clear();
434        command.envs(std::env::vars_os().filter(|(name, _)| {
435            name.to_str()
436                .is_some_and(|name| env_name_allowed(&self.env_allowlist, name))
437        }));
438        command
439            .current_dir(cwd_host)
440            .envs(request.env)
441            .stdin(if request.stdin.is_some() || request.keep_stdin {
442                Stdio::piped()
443            } else {
444                Stdio::null()
445            })
446            .stdout(Stdio::piped())
447            .stderr(Stdio::piped())
448            .kill_on_drop(true);
449        if !explicit_path && !removes_path {
450            command.env("PATH", local_execution_search_path(&self.home));
451        }
452        for name in request.env_remove {
453            command.env_remove(name);
454        }
455        configure_command_for_process_group(&mut command);
456        let mut child = command.spawn()?;
457        if request.keep_stdin {
458            // The caller writes for the process's life; what it gave up
459            // front goes first.
460            if let (Some(stdin), Some(pipe)) = (request.stdin, child.stdin.as_mut()) {
461                pipe.write_all(&stdin).await?;
462            }
463        } else if let (Some(stdin), Some(mut pipe)) = (request.stdin, child.stdin.take()) {
464            tokio::spawn(async move {
465                let _ = pipe.write_all(&stdin).await;
466            });
467        }
468        let pid = child.id().unwrap_or(0);
469        Ok(SpawnedProcess::new(
470            ProcessHandle::new(pid, Some(pid), None),
471            child,
472        ))
473    }
474
475    async fn terminate(&self, handle: &ProcessHandle, grace: Duration) -> anyhow::Result<()> {
476        let Some(pid) = handle.local_pid() else {
477            return Ok(());
478        };
479        if send_sigterm(pid) {
480            tokio::time::sleep(grace).await;
481        }
482        send_sigkill(pid);
483        Ok(())
484    }
485
486    async fn import_local_file(
487        &self,
488        local_path: &Path,
489        destination: &BackendPath,
490    ) -> anyhow::Result<BackendPath> {
491        if !self.allow_outside_workspace {
492            let bytes = tokio::fs::read(local_path).await?;
493            self.write(destination, &bytes, WriteMode::Overwrite, true)
494                .await?;
495            return Ok(destination.clone());
496        }
497        let path = BackendPath::new(local_path.to_string_lossy().into_owned());
498        self.ensure_allowed(local_path).await?;
499        Ok(path)
500    }
501
502    async fn export_local_file(
503        &self,
504        source: &BackendPath,
505        local_path: &Path,
506    ) -> anyhow::Result<()> {
507        let source = self.host_path(source);
508        self.ensure_allowed(&source).await?;
509        if source == local_path {
510            return Ok(());
511        }
512        if let Some(parent) = local_path.parent() {
513            tokio::fs::create_dir_all(parent).await?;
514        }
515        tokio::fs::copy(source, local_path).await?;
516        Ok(())
517    }
518}
519
520fn metadata_from_std(metadata: std::fs::Metadata) -> BackendMetadata {
521    let file_type = metadata.file_type();
522    BackendMetadata {
523        file_type: if file_type.is_symlink() {
524            BackendFileType::Symlink
525        } else if file_type.is_file() {
526            BackendFileType::File
527        } else if file_type.is_dir() {
528            BackendFileType::Directory
529        } else {
530            BackendFileType::Other
531        },
532        len: metadata.len(),
533        modified: metadata.modified().ok(),
534    }
535}
536
537/// The file `path` names after every symlink (a broken one to its target)
538/// and `..`, by the resolver the scope guard uses.
539async fn canonicalize_existing_or_parent(path: &Path) -> anyhow::Result<PathBuf> {
540    let absolute = if path.is_absolute() {
541        path.to_path_buf()
542    } else {
543        std::env::current_dir()?.join(path)
544    };
545    Ok(aidaemon_policies::resolve_path(&absolute)?)
546}
547
548fn sibling_temp_path(path: &Path, purpose: &str) -> PathBuf {
549    let suffix = uuid::Uuid::new_v4().simple().to_string();
550    let name = path
551        .file_name()
552        .and_then(OsStr::to_str)
553        .unwrap_or("aidaemon-file");
554    path.with_file_name(format!(".{name}.aidaemon-{purpose}-{suffix}"))
555}
556
557/// Expand `~` in a host path.
558pub fn expand_local_path(path: &str) -> anyhow::Result<PathBuf> {
559    Ok(PathBuf::from(shellexpand::tilde(path).to_string()))
560}