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