1use std::any::Any;
4use std::path::{Path, PathBuf};
5
6use executor_core::Executor;
7use heel::{
8 Access, Audited, Grant, IpcRouter, NetworkPolicy, ResolvedPath, SandboxConfig, SecurityConfig,
9 StdioConfig,
10};
11
12use super::child::{ChildExit, Descendants, KillHandle, SandboxedChild, Streams, exit_watch};
13use super::domain::DomainGate;
14use super::stdio::{read_chunks, write_chunks};
15use super::{
16 Backend, LaunchInfo, Pipe, Sandbox, SpawnCommand, SpawnError, SpawnGrant, SpawnSpec, Stdio,
17};
18#[cfg(target_os = "linux")]
19use crate::process_tree::JobProcess;
20use crate::process_tree::{JobMarker, JobTree};
21use crate::stdin_watch::{FeedCounter, LocalStdinProbe, StdinWatchSignal};
22use crate::terminal::{LocalChild, LocalStdinWatch, wait_for_local_process_exit};
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum TreeLifetime {
28 Foreground,
30 Background,
32}
33
34pub struct LocalSpawn {
37 pub(crate) child: LocalChild,
38 pub(crate) tree: JobTree,
39 pub(crate) sandbox: Box<dyn Any + Send>,
41}
42
43pub fn resolved(path: &Path) -> heel::Result<ResolvedPath> {
47 ResolvedPath::new(std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()))
48}
49
50pub async fn linked_worktree_grants(
58 writable: &[PathBuf],
59 readable: &[PathBuf],
60 git_dir: crate::GitDirAccess,
61) -> heel::Result<Vec<Grant>> {
62 let mut grants = Vec::new();
63 for (path, access) in writable
64 .iter()
65 .map(|path| (path, git_dir.writable_worktree_access()))
66 .chain(readable.iter().map(|path| (path, Access::READ)))
67 {
68 if let Some(common) = crate::subagent::confirmed_common_dir(path).await {
69 grants.push(Grant::new(resolved(&common)?, access));
70 }
71 }
72 Ok(grants)
73}
74
75#[cfg(not(windows))]
78fn read_denylist(denied: &[PathBuf]) -> heel::ReadDenylist {
79 denied
80 .iter()
81 .fold(heel::ReadDenylist::credentials(), |denylist, path| {
82 denylist.deny(path)
83 })
84}
85
86const fn stdio_config(pipe: Pipe) -> StdioConfig {
87 match pipe {
88 Pipe::Null => StdioConfig::Null,
89 Pipe::Piped => StdioConfig::Piped,
90 }
91}
92
93struct Launch {
95 program: String,
96 args: Vec<String>,
97 env: Vec<(String, String)>,
98 cwd: Option<PathBuf>,
99 stdio: Stdio,
100 lifetime: TreeLifetime,
101 marker: JobMarker,
102}
103
104impl Sandbox {
105 fn heel_binary(&self) -> Result<&heel::HeelBinary, SpawnError> {
106 match &self.inner.backend {
107 Backend::Host { heel } => Ok(heel),
108 Backend::Container { .. } | Backend::Ssh { .. } => Err(SpawnError::Setup(
109 "a local spawn needs the host backend".into(),
110 )),
111 }
112 }
113
114 fn canonical_working_dir(&self) -> PathBuf {
118 std::fs::canonicalize(&self.inner.working_dir)
119 .unwrap_or_else(|_| self.inner.working_dir.clone())
120 }
121
122 fn host_environment(
125 &self,
126 spec_env: Vec<(String, String)>,
127 info: &LaunchInfo,
128 ) -> Result<Vec<(String, String)>, SpawnError> {
129 let mut env = self.inner.environment.clone();
130 if let Some(source) = &self.inner.env_source {
131 env.extend(source.env(info));
132 }
133 for (name, path) in &self.inner.space_environment {
134 let value = path.to_str().ok_or_else(|| {
135 SpawnError::Setup(format!(
136 "{} is not UTF-8, so the variable {name} cannot name it",
137 path.display()
138 ))
139 })?;
140 env.push((name.clone(), value.to_owned()));
141 }
142 env.extend(spec_env);
143 Ok(env)
144 }
145
146 async fn confined_grants(
153 &self,
154 snapshot: &super::GrantSnapshot,
155 extra: Vec<Grant>,
156 ) -> Result<Vec<Grant>, SpawnError> {
157 let setup = |error: heel::Error| SpawnError::Setup(error.to_string());
158 let mut grants = self.inner.fixed_grants.clone();
159 for (path, access) in snapshot
160 .writable
161 .iter()
162 .map(|path| (path, Access::WRITE | Access::EXEC))
163 .chain(snapshot.readable.iter().map(|path| (path, Access::READ)))
164 {
165 if matches!(path.try_exists(), Ok(false)) {
168 continue;
169 }
170 grants.push(Grant::new(resolved(path).map_err(setup)?, access));
171 }
172 grants.extend(
173 linked_worktree_grants(&snapshot.writable, &snapshot.readable, snapshot.git_dir)
174 .await
175 .map_err(setup)?,
176 );
177 grants.extend(extra);
178 Ok(grants)
179 }
180
181 fn confined_config<N: NetworkPolicy>(
182 &self,
183 policy: N,
184 grants: Vec<Grant>,
185 snapshot: &super::GrantSnapshot,
186 heel: heel::HeelBinary,
187 ipc: Option<IpcRouter>,
188 ) -> SandboxConfig<N> {
189 let builder = SandboxConfig::builder().network(policy);
190 #[cfg(not(windows))]
195 let builder = {
196 let builder = match &self.inner.write_denylist {
197 Some(denylist) => builder.write_denylist(denylist.clone()),
198 None => builder,
199 };
200 builder
201 .filesystem_strict(false)
202 .read_denylist(read_denylist(&snapshot.read_denied))
203 };
204 #[cfg(windows)]
205 let _ = snapshot;
206 let builder = builder
207 .working_dir(self.canonical_working_dir())
208 .grants(grants)
209 .heel_binary(heel)
210 .security(SecurityConfig::interactive())
211 .executable_working_dir(true)
214 .priority(self.inner.priority);
215 #[cfg(target_os = "linux")]
216 let builder = builder.supervised_spawn(true);
217 match ipc {
219 Some(router) => builder.ipc(router).build(),
220 None => builder.build(),
221 }
222 }
223
224 fn unconfined_config(
225 &self,
226 heel: heel::HeelBinary,
227 ipc: Option<IpcRouter>,
228 ) -> SandboxConfig<heel::HostAccess> {
229 let builder = SandboxConfig::builder()
233 .working_dir(self.canonical_working_dir())
234 .host_access()
235 .heel_binary(heel)
236 .executable_working_dir(true)
237 .priority(self.inner.priority);
238 #[cfg(target_os = "linux")]
239 let builder = builder.supervised_spawn(true);
240 match ipc {
241 Some(router) => builder.ipc(router).build(),
242 None => builder.build(),
243 }
244 }
245
246 pub(crate) async fn spawn_local(&self, spec: SpawnSpec) -> Result<LocalSpawn, SpawnError> {
249 let heel = self.heel_binary()?.clone();
250 let SpawnSpec {
251 command,
252 env,
253 cwd,
254 stdio,
255 grants: extra_grants,
256 ipc,
257 lifetime,
258 info,
259 } = spec;
260 let SpawnCommand::Program { program, args } = command else {
263 return Err(SpawnError::Unsupported {
264 backend: "host",
265 what: "a script",
266 });
267 };
268 let extra_grants = extra_grants
269 .into_iter()
270 .map(|grant| match grant {
271 SpawnGrant::Host(grant) => Ok(grant),
272 SpawnGrant::Container { .. } => Err(SpawnError::Unsupported {
273 backend: "host",
274 what: "a grant on a container path",
275 }),
276 })
277 .collect::<Result<Vec<_>, _>>()?;
278 let marker = JobMarker::new();
279 let mut env = self.host_environment(env, &info)?;
280 env.push(marker.entry());
281 let launch = Launch {
282 program,
283 args,
284 env,
285 cwd,
286 stdio,
287 lifetime,
288 marker,
289 };
290 if self.inner.unconfined {
291 let config = self.unconfined_config(heel, ipc);
292 return self.launch(config, launch).await;
293 }
294 let snapshot = self.inner.grants.snapshot();
295 let grants = self.confined_grants(&snapshot, extra_grants).await?;
296 let gate = DomainGate {
297 lists: self.inner.network.clone(),
298 approver: self.inner.approver.clone(),
299 agent: self.inner.agent.clone(),
300 };
301 if let Some(log) = self.inner.audit.clone() {
302 let config =
303 self.confined_config(Audited::new(gate, log), grants, &snapshot, heel, ipc);
304 self.launch(config, launch).await
305 } else {
306 let config = self.confined_config(gate, grants, &snapshot, heel, ipc);
307 self.launch(config, launch).await
308 }
309 }
310
311 async fn launch<N: NetworkPolicy + 'static>(
312 &self,
313 config: SandboxConfig<N>,
314 launch: Launch,
315 ) -> Result<LocalSpawn, SpawnError> {
316 let sandbox = heel::Sandbox::with_config_and_executor(config, self.inner.executor.clone())
317 .await
318 .map_err(|error| SpawnError::Setup(error.to_string()))?;
319 let Launch {
320 program,
321 args,
322 env,
323 cwd,
324 stdio,
325 lifetime,
326 marker,
327 } = launch;
328 let mut command = sandbox.command(program);
329 if let Some(cwd) = cwd {
330 command = command.current_dir(cwd);
331 }
332 let command = command
333 .args(args)
334 .envs(env)
335 .stdin(stdio_config(stdio.stdin))
336 .stdout(stdio_config(stdio.stdout))
337 .stderr(stdio_config(stdio.stderr));
338 let start = |error: heel::Error| SpawnError::Start(error.to_string());
339
340 #[cfg(target_os = "linux")]
345 {
346 let _ = marker;
347 let reap_timeout = crate::terminal::SUPERVISED_REAP_TIMEOUT;
348 let child = match lifetime {
349 TreeLifetime::Foreground => LocalChild::Foreground(
350 command
351 .spawn_supervised(heel::supervisor::Foreground { reap_timeout })
352 .await
353 .map_err(start)?,
354 ),
355 TreeLifetime::Background => LocalChild::Background(
356 command
357 .spawn_supervised(heel::supervisor::Background { reap_timeout })
358 .await
359 .map_err(start)?,
360 ),
361 };
362 let tree = JobTree::supervised(child.tree_control());
363 Ok(LocalSpawn {
364 child,
365 tree,
366 sandbox: Box::new(sandbox),
367 })
368 }
369
370 #[cfg(not(target_os = "linux"))]
373 {
374 let _ = lifetime;
375 let child = command.spawn().await.map_err(start)?;
376 let tree = JobTree::spawn(
377 &self.inner.executor,
378 self.inner.scanner.clone(),
379 child.id(),
380 &marker,
381 );
382 Ok(LocalSpawn {
383 child: LocalChild::Plain(child),
384 tree,
385 sandbox: Box::new(sandbox),
386 })
387 }
388 }
389
390 pub(super) async fn spawn_host(&self, spec: SpawnSpec) -> Result<SandboxedChild, SpawnError> {
391 let stdio = spec.stdio;
392 let lifetime = spec.lifetime;
393 let LocalSpawn {
394 mut child,
395 tree,
396 sandbox,
397 } = self.spawn_local(spec).await?;
398 let id = child.id();
399
400 let mut streams = Streams::default();
401 let mut stdin_watch = None;
402 if stdio.stdin == Pipe::Piped
403 && let Some(stdin) = child.take_stdin()
404 {
405 let feed = FeedCounter::default();
406 let (signal_tx, signal_rx) = async_channel::unbounded();
407 match LocalStdinProbe::new(id, &stdin) {
408 Ok(probe) => {
409 stdin_watch = Some(LocalStdinWatch::new(probe, feed.clone(), signal_tx));
410 }
411 Err(error) => {
413 let _ = signal_tx.try_send(StdinWatchSignal::Failed(error.to_string()));
414 }
415 }
416 streams.stdin_blocked = Some(signal_rx);
417 streams.stdin = Some(write_chunks(stdin, feed));
418 }
419 if stdio.stdout == Pipe::Piped
420 && let Some(stdout) = child.take_stdout()
421 {
422 streams.stdout = Some(pump(stdout));
423 }
424 if stdio.stderr == Pipe::Piped
425 && let Some(stderr) = child.take_stderr()
426 {
427 streams.stderr = Some(pump(stderr));
428 }
429
430 let (setter, watch) = exit_watch();
431 let watched = tree.clone();
432 self.inner
433 .executor
434 .spawn(async move {
435 let _sandbox = sandbox;
437 let (exit, descendants) =
438 wait_for_exit(&mut child, &watched, lifetime, stdin_watch).await;
439 setter.finish(exit, descendants);
440 })
441 .detach();
442 Ok(SandboxedChild::new(
443 id,
444 streams,
445 KillHandle::Tree(tree),
446 watch,
447 ))
448 }
449}
450
451fn pump(file: std::fs::File) -> async_channel::Receiver<Vec<u8>> {
453 let (tx, rx) = async_channel::unbounded();
454 read_chunks(file, move |chunk| {
455 if let Some(chunk) = chunk {
456 let _ = tx.send_blocking(chunk);
457 }
458 });
459 rx
460}
461
462async fn wait_for_exit(
468 child: &mut LocalChild,
469 tree: &JobTree,
470 lifetime: TreeLifetime,
471 stdin_watch: Option<LocalStdinWatch>,
472) -> (ChildExit, Descendants) {
473 let exited = match wait_for_local_process_exit(child, stdin_watch).await {
474 Ok(exited) => exited,
475 Err(error) => {
476 tree.finish().await;
477 return (
478 ChildExit::Failed(error.to_string()),
479 Descendants::Unobserved,
480 );
481 }
482 };
483 let mut killed = Vec::new();
484 let ended = match lifetime {
485 TreeLifetime::Foreground => tree
486 .kill_descendants()
487 .await
488 .map(|processes| killed = processes),
489 TreeLifetime::Background => tree.wait_descendants_exit().await,
490 };
491 tree.finish().await;
493 let status = match exited {
494 Some(status) => Ok(status),
495 None => child
496 .wait_reported()
497 .await
498 .map(|(status, report)| {
499 #[cfg(target_os = "linux")]
501 if let Some(report) = report {
502 killed.extend(report.killed.into_iter().map(|process| JobProcess {
503 pid: process.pid,
504 name: process.name,
505 }));
506 }
507 #[cfg(not(target_os = "linux"))]
508 let _ = report;
509 status
510 })
511 .map_err(|error| error.to_string()),
512 };
513 let descendants = if cfg!(windows) || ended.is_err() {
516 Descendants::Unobserved
517 } else {
518 Descendants::Killed(killed)
519 };
520 let exit = match (ended, status) {
521 (Ok(()), Ok(status)) => ChildExit::Exited(status),
522 (Err(error), _) => ChildExit::Failed(error.to_string()),
523 (Ok(()), Err(error)) => ChildExit::Failed(error),
524 };
525 (exit, descendants)
526}