Skip to main content

orch/engine/runner/
sandbox.rs

1//! The OS sandbox around a task or review agent, when `workflow.sandbox` is `os`. The policy and
2//! why it is shaped this way are in docs/plans/2026-10-28-agent-sandboxes.md
3
4use super::agent::AgentInvocation;
5use crate::config;
6use crate::home;
7use sandbox_jail::{Access, Backend, Policy, Sandbox, known};
8use std::env;
9use std::error;
10use std::ffi::OsString;
11use std::fmt;
12use std::fmt::Display;
13use std::fmt::Formatter;
14use std::fs;
15use std::path::{Path, PathBuf};
16
17/// Top-level dirs of the home that stay read-only: what loads or runs later as the operator, the
18/// agents' own settings, and keys. Everything at the top of the home that is not a dir is read-only too
19const HOME_READ_ONLY: &[&str] = &[
20    ".config", ".claude", ".ssh", ".gnupg", "bin", "Library", ".local",
21];
22
23/// Writable parts of the read-only dirs above, for caches and agent state
24const HOME_WRITABLE: &[&str] = &[
25    "Library/Caches",
26    "Library/Logs",
27    ".local/share",
28    ".local/state",
29];
30
31/// Codex's settings and instructions, which sit beside the state it rewrites
32const AGENT_CONFIG: &[&str] = &[".codex/config.toml", ".codex/AGENTS.md", ".codex/rules"];
33
34/// Config inside writable home dirs that runs code on the operator's next build or shell, read-only
35/// even when missing. Cargo's `rustc-wrapper` and `runner`, gradle's init scripts, shell frameworks
36const HOME_EXEC_CONFIG: &[&str] = &[
37    ".cargo/config",
38    ".cargo/config.toml",
39    ".gradle/init.d",
40    ".gradle/init.gradle",
41    ".gradle/gradle.properties",
42    ".m2/settings.xml",
43    ".oh-my-zsh",
44    ".zprezto",
45];
46
47/// The tmux, ssh-agent and Docker sockets that would let an agent start a process outside
48const SCRATCH: &[&str] = &["/tmp", "/run", "/var/tmp"];
49
50/// macOS services an agent may look up: the basics, and securityd for its keychain login. Not
51/// LaunchServices, which `open` uses to start an app outside the sandbox
52const KEYCHAIN: &str = "com.apple.SecurityServer";
53
54/// The run's own temp dir, so no socket of the operator's apps in the shared one is in reach
55pub fn run_temp_dir(attempt_dir: &Path) -> PathBuf {
56    attempt_dir.join("tmp")
57}
58
59/// Whether the project runs its agents in the sandbox: `workflow.sandbox: os` in its `.orch.yml`
60/// or the global config. `false` or no setting leaves it off
61pub fn enabled(project_dir: &Path) -> bool {
62    config::get_for_project(project_dir, "workflow.sandbox").is_ok_and(|v| v.trim() == "os")
63}
64
65/// Like [`enabled`] from the global config alone, for a run whose project is unknown
66pub fn enabled_globally() -> bool {
67    config::get_global("workflow.sandbox").is_ok_and(|v| v.trim() == "os")
68}
69
70/**
71 * The program and arguments that go before the agent command, or why the sandbox cannot start.
72 * The worktree's `.git` file is the agent's to write, so the common dir comes from the main
73 * checkout and the branch from orch's records, and a git dir outside them refuses the run
74 **/
75pub async fn argv(inv: &AgentInvocation, temp: &Path) -> anyhow::Result<Vec<OsString>> {
76    build(inv, temp)
77        .await
78        .map_err(|e| anyhow::Error::new(SandboxFailed(format!("{e:#}"))))
79}
80
81/// The sandbox cannot start. It is the operator's setup, so it blocks the task and counts against no agent
82#[derive(Debug)]
83pub struct SandboxFailed(pub String);
84
85impl Display for SandboxFailed {
86    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
87        write!(f, "the OS sandbox cannot start: {}", self.0)
88    }
89}
90
91impl error::Error for SandboxFailed {}
92
93async fn build(inv: &AgentInvocation, temp: &Path) -> anyhow::Result<Vec<OsString>> {
94    let backend = Backend::detect()?;
95    let common_dir =
96        super::agent::resolve_git_dir_arg(&inv.main_project_dir, "--git-common-dir").await?;
97    let git_dir = super::agent::resolve_git_dir_arg(&inv.work_dir, "--git-dir").await?;
98
99    check_git_dirs(
100        &inv.work_dir,
101        &inv.main_project_dir,
102        git_dir.as_deref(),
103        common_dir.as_deref(),
104    )?;
105
106    let home = env::var_os("HOME")
107        .map(PathBuf::from)
108        .ok_or_else(|| anyhow::anyhow!("HOME is not set, so the sandbox cannot hide its keys"))?;
109    let mut projects: Vec<PathBuf> = config::get_projects_with_paths()
110        .unwrap_or_default()
111        .into_iter()
112        .map(|(_, dir)| dir)
113        .collect();
114    projects.push(inv.main_project_dir.clone());
115    let path_dirs = env::var_os("PATH")
116        .map(|p| env::split_paths(&p).collect())
117        .unwrap_or_default();
118
119    let run = Run {
120        work_dir: inv.work_dir.clone(),
121        git_dir,
122        common_dir,
123        own_ref: (!inv.branch.is_empty()).then(|| format!("refs/heads/{}", inv.branch)),
124        home,
125        orch_home: home::orch_home()?,
126        projects,
127        path_dirs,
128        temp: temp.to_path_buf(),
129        internal: inv.task_id.starts_with("internal:"),
130        seatbelt: backend == Backend::Seatbelt,
131    };
132    let sandbox = Sandbox::new(backend, policy(&run))?;
133    Ok(sandbox.argv().to_vec())
134}
135
136/**
137 * Refuses a worktree whose git dir the agent could have pointed elsewhere. Only the main checkout
138 * has the common dir as its git dir. A linked worktree's git dir is in `<common>/worktrees`, and
139 * its `gitdir` file, which the agent cannot write, points back at this worktree
140 **/
141fn check_git_dirs(
142    work_dir: &Path,
143    main_project_dir: &Path,
144    git_dir: Option<&Path>,
145    common_dir: Option<&Path>,
146) -> anyhow::Result<()> {
147    let real = |p: &Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
148
149    match (git_dir, common_dir) {
150        (Some(git), Some(common)) if git == common => anyhow::ensure!(
151            real(work_dir) == real(main_project_dir),
152            "the worktree {} uses the repository's own git dir {}",
153            work_dir.display(),
154            common.display()
155        ),
156        (Some(git), Some(common)) => {
157            anyhow::ensure!(
158                git.starts_with(common.join("worktrees")),
159                "the worktree's git dir {} is outside its repository {}",
160                git.display(),
161                common.display()
162            );
163            let back = fs::read_to_string(git.join("gitdir")).unwrap_or_default();
164            anyhow::ensure!(
165                real(Path::new(back.trim())) == real(&work_dir.join(".git")),
166                "the git dir {} belongs to another worktree",
167                git.display()
168            );
169        }
170        (None, Some(common)) => anyhow::bail!(
171            "the worktree {} has no git dir in {}",
172            work_dir.display(),
173            common.display()
174        ),
175        _ => {}
176    }
177
178    Ok(())
179}
180
181/// What the policy of one run depends on
182struct Run {
183    work_dir: PathBuf,
184    git_dir: Option<PathBuf>,
185    common_dir: Option<PathBuf>,
186    /// The task's branch, `refs/heads/<branch>`, from orch's records
187    own_ref: Option<String>,
188    home: PathBuf,
189    orch_home: PathBuf,
190    projects: Vec<PathBuf>,
191    path_dirs: Vec<PathBuf>,
192    /// The run's own temp dir, where the agent may also connect to a socket
193    temp: PathBuf,
194    internal: bool,
195    seatbelt: bool,
196}
197
198impl Run {
199    fn git_dirs(&self) -> impl Iterator<Item = &PathBuf> {
200        self.git_dir.iter().chain(&self.common_dir)
201    }
202}
203
204fn policy(run: &Run) -> Policy {
205    let mut p = Policy::default();
206    p.writable.push(run.work_dir.clone());
207    p.writable.extend(run.git_dirs().cloned());
208    p.writable.extend(home_writable(&run.home));
209    p.writable.push(run.temp.clone());
210
211    if run.seatbelt {
212        p.writable.push("/private/tmp".into());
213        p.mach_services = Access::Only(
214            known::BASIC_MACH_SERVICES
215                .iter()
216                .chain(&[KEYCHAIN])
217                .map(ToString::to_string)
218                .collect(),
219        );
220    } else {
221        // bwrap has no socket filter, so the dirs that hold sockets start empty instead
222        p.scratch = SCRATCH
223            .iter()
224            .map(PathBuf::from)
225            .filter(|d| d.is_dir())
226            .collect();
227    }
228
229    // The tmux server runs outside the sandbox, so its socket in /tmp must stay out of reach
230    p.unix_sockets = Access::Only(vec![run.work_dir.clone(), run.temp.clone()]);
231
232    if let Some(common) = &run.common_dir {
233        git_rules(
234            common,
235            run.git_dir.as_ref(),
236            run.own_ref.as_deref(),
237            &mut p.read_only,
238        );
239
240        if run.git_dir.as_ref().is_some_and(|g| g != common) {
241            p.read_only.push(run.work_dir.join(".git"));
242        }
243    }
244
245    for dir in home_writable(&run.home) {
246        find_git_dirs(&dir, GIT_SCAN_DEPTH, &mut p.read_only);
247    }
248
249    // /private/tmp stays writable, but the agent must not delete or replace these sockets.
250    // bwrap hides those in a scratch dir, and binding one back would expose it
251    let hidden = p.scratch.clone();
252    p.read_only.extend(
253        socket_dirs(&run.temp)
254            .into_iter()
255            .filter(|d| !hidden.iter().any(|s| d.starts_with(s))),
256    );
257
258    p.read_only.push(run.work_dir.join(".orch.yml"));
259    p.read_only.extend(
260        AGENT_CONFIG
261            .iter()
262            .chain(HOME_EXEC_CONFIG)
263            .map(|path| run.home.join(path)),
264    );
265    // A tool on PATH inside the home, such as ~/.cargo/bin, runs later as the operator
266    p.read_only.extend(
267        run.path_dirs
268            .iter()
269            .filter(|d| d.starts_with(&run.home))
270            .cloned(),
271    );
272
273    let mut keep: Vec<PathBuf> = vec![run.work_dir.clone(), run.temp.clone()];
274    keep.extend(run.git_dirs().cloned());
275
276    if run.internal {
277        keep.extend(["orch.db", "orch.db-wal", "orch.db-shm"].map(|f| run.orch_home.join(f)));
278    }
279    // The daemon's loopback write endpoint takes this token, so reading it is a write to the store
280    let write_token = run.orch_home.join("state/cluster.port");
281
282    read_only_around(&run.orch_home, &keep, &mut p.read_only);
283
284    for project in &run.projects {
285        read_only_around(project, &keep, &mut p.read_only);
286    }
287
288    // The crate's list hides cargo's config too, which holds build settings agents need
289    p.hidden = known::credentials(&run.home)
290        .into_iter()
291        .filter(|path| {
292            ![".cargo/config", ".cargo/config.toml"]
293                .map(|c| run.home.join(c))
294                .contains(path)
295        })
296        .collect();
297    p.hidden.push(run.home.join(".gnupg"));
298
299    // The web UI's token drives the daemon's API, config edits and plan imports among it
300    p.hidden.push(run.orch_home.join(UI_TOKEN));
301
302    if !run.internal {
303        p.hidden.push(write_token);
304    }
305
306    p.own_signals = true;
307
308    // launchctl and setuid binaries start processes outside the sandbox
309    if run.seatbelt {
310        p.apple_events = false;
311        p.no_exec.push(known::LAUNCHCTL.into());
312        p.no_exec.extend(known::setuid_binaries().iter().cloned());
313    }
314
315    p
316}
317
318/// The web UI's port and token. No agent may read it, it would drive the daemon through the UI's API
319const UI_TOKEN: &str = "state/ui.port";
320
321/// The agent's own login and settings, which it reads to start. The Security framework reads the
322/// login keychain in the calling process, and its access rules still give the agent only its own item
323const CHAT_AGENT_HOME: &[&str] = &[".claude", ".claude.json", "Library/Keychains"];
324
325/// Where agents keep sessions and caches, which the control chat writes to resume a conversation
326const AGENT_STATE: &[&str] = &[
327    ".claude/projects",
328    ".claude/todos",
329    ".claude/shell-snapshots",
330    ".claude/statsig",
331    ".codex",
332    ".local/share/opencode",
333    ".local/state/opencode",
334];
335
336/// Other agents' settings, read at start
337const AGENT_CONFIG_READ: &[&str] = &[".codex", ".config/opencode", ".grok"];
338
339/// What a chat agent may touch, as opposed to a task agent's [`policy`]
340struct ChatRun {
341    home: PathBuf,
342    orch_home: PathBuf,
343    /// The project a project chat reads, none for the control chat
344    project: Option<PathBuf>,
345    temp: PathBuf,
346    path_dirs: Vec<PathBuf>,
347    seatbelt: bool,
348    /// The control chat keeps agent sessions and acts through orch, so it writes session dirs and
349    /// reads the daemon's write token. A project chat does neither
350    control: bool,
351}
352
353/// The sandbox prefix for a project chat agent. It reads the project and orch's store and config,
354/// writes only its temp dir, and cannot read the rest of the home or any credential
355pub fn chat_argv(project: &Path, temp: &Path) -> anyhow::Result<Vec<OsString>> {
356    chat_sandbox(Some(project), temp, false)
357}
358
359/**
360 * The sandbox prefix for the control chat, which Telegram and the other channels reach. It reads
361 * orch's home and acts through orch, and cannot read the rest of the home or any credential.
362 * Inside another Seatbelt sandbox, which cannot nest, it runs in that one
363 **/
364pub fn control_argv(temp: &Path) -> anyhow::Result<Vec<OsString>> {
365    match chat_sandbox(None, temp, true) {
366        Err(e)
367            if e.downcast_ref::<sandbox_jail::Error>()
368                .is_some_and(|e| matches!(e, sandbox_jail::Error::Nested)) =>
369        {
370            tracing::info!("already inside a sandbox, the control chat runs in it");
371            Ok(Vec::new())
372        }
373        other => other,
374    }
375}
376
377fn chat_sandbox(
378    project: Option<&Path>,
379    temp: &Path,
380    control: bool,
381) -> anyhow::Result<Vec<OsString>> {
382    let backend = Backend::detect()?;
383    let home = env::var_os("HOME")
384        .map(PathBuf::from)
385        .ok_or_else(|| anyhow::anyhow!("HOME is not set"))?;
386    let run = ChatRun {
387        home,
388        orch_home: home::orch_home()?,
389        project: project.map(Path::to_path_buf),
390        temp: temp.to_path_buf(),
391        path_dirs: env::var_os("PATH")
392            .map(|p| env::split_paths(&p).collect())
393            .unwrap_or_default(),
394        seatbelt: matches!(backend, Backend::Seatbelt),
395        control,
396    };
397    Ok(Sandbox::new(backend, chat_policy(&run))?.argv().to_vec())
398}
399
400fn chat_policy(run: &ChatRun) -> Policy {
401    let mut p = Policy::default();
402    p.writable.push(run.temp.clone());
403    // `orch task list` opens the store, and SQLite writes its -wal and -shm files even to read
404    p.writable.extend(
405        ["orch.db", "orch.db-wal", "orch.db-shm"]
406            .map(|f| run.orch_home.join(f))
407            .into_iter()
408            .filter(|f| f.exists()),
409    );
410
411    if run.seatbelt {
412        p.writable.push("/private/tmp".into());
413        p.mach_services = Access::Only(
414            known::BASIC_MACH_SERVICES
415                .iter()
416                .chain(&[KEYCHAIN])
417                .map(ToString::to_string)
418                .collect(),
419        );
420    } else {
421        p.scratch = SCRATCH
422            .iter()
423            .map(PathBuf::from)
424            .filter(|d| d.is_dir())
425            .collect();
426    }
427
428    p.unix_sockets = Access::Only(vec![run.temp.clone()]);
429
430    if run.control {
431        p.writable.extend(
432            AGENT_STATE
433                .iter()
434                .map(|d| run.home.join(d))
435                .filter(|d| d.is_dir()),
436        );
437        // Codex writes its state beside its settings, which stay as the owner wrote them
438        p.read_only
439            .extend(AGENT_CONFIG.iter().map(|path| run.home.join(path)));
440    }
441
442    // The tmux server and launchd's sockets sit in the writable /private/tmp, and an agent that
443    // deleted or replaced one would end every session or stand in for the ssh agent
444    p.read_only.extend(socket_dirs(&run.temp));
445
446    p.unreadable.push(run.home.clone());
447    p.readable.extend(run.project.iter().cloned());
448    p.readable.push(run.orch_home.clone());
449    p.readable
450        .extend(AGENT_CONFIG_READ.iter().map(|f| run.home.join(f)));
451    p.readable
452        .extend(CHAT_AGENT_HOME.iter().map(|f| run.home.join(f)));
453    p.readable.extend(
454        run.path_dirs
455            .iter()
456            .filter(|d| d.starts_with(&run.home))
457            .cloned(),
458    );
459
460    p.hidden = known::credentials(&run.home);
461    p.hidden.push(run.home.join(".gnupg"));
462    p.hidden.push(run.orch_home.join(UI_TOKEN));
463    // The daemon's loopback write endpoint takes this token, and a project chat only reads
464    if !run.control {
465        p.hidden.push(run.orch_home.join("state/cluster.port"));
466    }
467
468    p.own_signals = true;
469    if run.seatbelt {
470        p.apple_events = false;
471        p.no_exec.push(known::LAUNCHCTL.into());
472        p.no_exec.extend(known::setuid_binaries().iter().cloned());
473    }
474
475    p
476}
477
478/// How many levels below a writable home dir are searched for repositories
479const GIT_SCAN_DEPTH: usize = 4;
480
481// Hooks and config of a repository orch does not know run as the operator on its next git command
482fn find_git_dirs(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) {
483    let git = dir.join(".git");
484
485    if git.is_dir() {
486        out.extend(["hooks", "config", "info", "modules"].map(|f| git.join(f)));
487    }
488
489    if depth == 0 {
490        return;
491    }
492
493    for entry in fs::read_dir(dir).into_iter().flatten().flatten() {
494        let name = entry.file_name();
495
496        if entry.file_type().is_ok_and(|t| t.is_dir()) && name != ".git" && name != "node_modules" {
497            find_git_dirs(&entry.path(), depth - 1, out);
498        }
499    }
500}
501
502/// The tmux and launchd socket dirs in the shared temp dirs, which the tmux server and the
503/// ssh-agent keep running outside the sandbox
504fn socket_dirs(temp: &Path) -> Vec<PathBuf> {
505    let mut roots = vec![PathBuf::from("/private/tmp"), PathBuf::from("/tmp")];
506    roots.extend(env::var_os("TMUX_TMPDIR").map(PathBuf::from));
507    roots.push(temp.to_path_buf());
508
509    roots
510        .iter()
511        .filter_map(|r| fs::read_dir(r).ok())
512        .flatten()
513        .flatten()
514        .filter(|e| {
515            let name = e.file_name();
516            let name = name.to_string_lossy();
517            name.starts_with("tmux-") || name.starts_with("com.apple.launchd.")
518        })
519        .map(|e| e.path())
520        .collect()
521}
522
523/// The home's writable parts: its top-level dirs but [`HOME_READ_ONLY`], and [`HOME_WRITABLE`]
524/// inside those. The home itself stays read-only, so no new dotfile appears at its top
525fn home_writable(home: &Path) -> Vec<PathBuf> {
526    let mut dirs: Vec<PathBuf> = fs::read_dir(home)
527        .into_iter()
528        .flatten()
529        .flatten()
530        .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
531        .filter(|e| !HOME_READ_ONLY.contains(&e.file_name().to_string_lossy().as_ref()))
532        .map(|e| e.path())
533        .collect();
534    dirs.extend(
535        HOME_WRITABLE
536            .iter()
537            .map(|d| home.join(d))
538            .filter(|d| d.is_dir()),
539    );
540    dirs
541}
542
543/**
544 * The git common dir is writable for objects, the task's branch, remote refs and the task's own
545 * worktree dir, and read-only around those: hooks and config run the next time the operator runs
546 * git, and another branch is the operator's work. Paths git would pick up when they appear are
547 * read-only even when missing, and so is a loose ref for a branch only `packed-refs` holds, since
548 * it would win over the packed one
549 **/
550fn git_rules(
551    common: &Path,
552    git_dir: Option<&PathBuf>,
553    own_ref: Option<&str>,
554    out: &mut Vec<PathBuf>,
555) {
556    out.extend(
557        [
558            "hooks",
559            "config",
560            "info",
561            "modules",
562            "packed-refs",
563            "refs/tags",
564            "commondir",
565            "gitdir",
566            "config.worktree",
567        ]
568        .map(|d| common.join(d)),
569    );
570    let own: Vec<PathBuf> = own_ref
571        .map(|r| vec![common.join(r), common.join("logs").join(r)])
572        .unwrap_or_default();
573
574    match git_dir {
575        Some(dir) if dir != common => {
576            let mut keep = vec![
577                common.join("objects"),
578                common.join("refs/remotes"),
579                common.join("logs/refs/remotes"),
580                dir.clone(),
581            ];
582            keep.extend(own.iter().cloned());
583            read_only_around(common, &keep, out);
584            out.extend(["HEAD", "commondir", "gitdir", "config.worktree"].map(|f| dir.join(f)));
585        }
586        // The worktree is the main checkout, so its index and HEAD live in the common dir
587        _ => read_only_around(&common.join("refs/heads"), &own, out),
588    }
589
590    let packed = fs::read_to_string(common.join("packed-refs")).unwrap_or_default();
591    for name in packed
592        .lines()
593        .filter_map(|l| l.split_once(' ').map(|(_, r)| r))
594    {
595        let path = common.join(name);
596
597        if name.starts_with("refs/heads/") && !own.contains(&path) && !path.exists() {
598            out.push(path);
599        }
600    }
601}
602
603/**
604 * Every entry of `dir` read-only but the paths in `keep`. An entry that holds a kept path is
605 * walked instead, so `~/.orch` stays read-only around the task's own worktree, and a main checkout
606 * around its `.git`. A missing `dir` adds nothing
607 **/
608fn read_only_around(dir: &Path, keep: &[PathBuf], out: &mut Vec<PathBuf>) {
609    let Ok(entries) = fs::read_dir(dir) else {
610        return;
611    };
612
613    for entry in entries.flatten() {
614        let path = entry.path();
615
616        if keep.iter().any(|k| path.starts_with(k)) {
617            continue;
618        }
619
620        let holds_kept = keep.iter().any(|k| k.starts_with(&path));
621        let is_dir = entry.file_type().is_ok_and(|t| t.is_dir());
622
623        if holds_kept && is_dir {
624            read_only_around(&path, keep, out);
625        } else if !holds_kept {
626            out.push(path);
627        }
628    }
629}
630
631#[cfg(test)]
632mod tests {
633    use super::*;
634    use std::fs;
635    #[cfg(target_os = "macos")]
636    use std::os::unix::net::UnixListener;
637    #[cfg(target_os = "macos")]
638    use std::thread;
639
640    #[tokio::test]
641    async fn argv_error_is_tagged_so_spawn_blocks_the_task() {
642        let inv = AgentInvocation {
643            agent: "claude".to_string(),
644            model: None,
645            reasoning_effort: None,
646            work_dir: PathBuf::from("/nonexistent/work"),
647            system_prompt: String::new(),
648            agent_message: String::new(),
649            task_id: "t".to_string(),
650            disallowed_tools: vec![],
651            git_author_name: String::new(),
652            git_author_email: String::new(),
653            output_file: PathBuf::from("/nonexistent/out.json"),
654            timeout_seconds: 0,
655            repo: "o/r".to_string(),
656            attempt: 1,
657            sandbox: true,
658            main_project_dir: PathBuf::from("/nonexistent/main"),
659            branch: String::new(),
660        };
661        let err = argv(&inv, Path::new("/tmp/orch-test-run"))
662            .await
663            .expect_err("no checkout, so no sandbox");
664        assert!(err.downcast_ref::<SandboxFailed>().is_some());
665        assert!(err.to_string().starts_with("the OS sandbox cannot start: "));
666    }
667
668    /// A home with an orch home inside, two worktrees and a main checkout, and the run of one task
669    fn fixture(internal: bool) -> (tempfile::TempDir, Run) {
670        let root = tempfile::tempdir().unwrap();
671        let r = root.path().canonicalize().unwrap();
672        let (home, orch) = (r.join("home"), r.join("home/.orch"));
673        for dir in [
674            "home/.orch/worktrees/proj/mine",
675            "home/.orch/worktrees/proj/other",
676            "home/.orch/state",
677            "home/proj/.git/worktrees/mine",
678            "home/proj/.git/refs/heads/feat",
679            "home/proj/src",
680            "home/proj/.git/objects",
681            "home/proj/.git/worktrees/other",
682            "home/.config/nvim",
683            "home/.claude",
684            "home/.cargo/bin",
685            "home/Library/Caches",
686            "home/Library/LaunchAgents",
687        ] {
688            fs::create_dir_all(r.join(dir)).unwrap();
689        }
690        for file in [
691            "home/.orch/config.yml",
692            "home/.orch/orch.db",
693            "home/proj/README.md",
694            "home/proj/.git/refs/heads/main",
695            "home/proj/.git/refs/heads/feat/mine",
696            "home/proj/.git/worktrees/mine/HEAD",
697            "home/.zshrc",
698            "home/.claude.json",
699        ] {
700            fs::write(r.join(file), "").unwrap();
701        }
702        fs::write(
703            r.join("home/proj/.git/packed-refs"),
704            "# pack-refs with: peeled\nabc refs/heads/release\n",
705        )
706        .unwrap();
707
708        let run = Run {
709            work_dir: orch.join("worktrees/proj/mine"),
710            git_dir: Some(home.join("proj/.git/worktrees/mine")),
711            common_dir: Some(home.join("proj/.git")),
712            own_ref: Some("refs/heads/feat/mine".into()),
713            home: home.clone(),
714            orch_home: orch,
715            projects: vec![home.join("proj")],
716            path_dirs: vec![home.join(".cargo/bin"), "/usr/bin".into()],
717            temp: r.join("tmp"),
718            internal,
719            seatbelt: false,
720        };
721        (root, run)
722    }
723
724    fn chat_fixture() -> ChatRun {
725        ChatRun {
726            home: PathBuf::from("/home/u"),
727            orch_home: PathBuf::from("/home/u/.orch"),
728            project: Some(PathBuf::from("/home/u/code/app")),
729            temp: PathBuf::from("/tmp/chat"),
730            path_dirs: vec![
731                PathBuf::from("/home/u/.cargo/bin"),
732                PathBuf::from("/usr/bin"),
733            ],
734            seatbelt: true,
735            control: false,
736        }
737    }
738
739    #[test]
740    fn no_task_can_read_the_web_ui_token() {
741        for internal in [false, true] {
742            let (_root, run) = fixture(internal);
743            let token = run.orch_home.join("state/ui.port");
744            assert!(policy(&run).hidden.contains(&token), "internal: {internal}");
745        }
746    }
747
748    #[test]
749    fn no_chat_can_read_the_web_ui_token() {
750        let token = PathBuf::from("/home/u/.orch/state/ui.port");
751        let mut run = chat_fixture();
752        assert!(
753            chat_policy(&run).hidden.contains(&token),
754            "the project chat"
755        );
756        run.project = None;
757        run.control = true;
758        assert!(
759            chat_policy(&run).hidden.contains(&token),
760            "the control chat"
761        );
762    }
763
764    #[test]
765    fn the_control_chat_reads_no_project_and_may_act_through_orch() {
766        let mut run = chat_fixture();
767        run.project = None;
768        run.control = true;
769        let p = chat_policy(&run);
770        assert!(
771            !p.readable.iter().any(|r| r.starts_with("/home/u/code")),
772            "no project folder"
773        );
774        assert!(
775            !p.hidden
776                .contains(&PathBuf::from("/home/u/.orch/state/cluster.port")),
777            "it acts through the daemon"
778        );
779        assert!(
780            p.hidden.contains(&PathBuf::from("/home/u/.ssh")),
781            "credentials stay hidden"
782        );
783        assert!(
784            p.unreadable.contains(&PathBuf::from("/home/u")),
785            "the home stays closed"
786        );
787    }
788
789    #[test]
790    fn a_chat_writes_only_its_temp_dir() {
791        let p = chat_policy(&chat_fixture());
792        assert!(
793            p.writable.contains(&PathBuf::from("/tmp/chat")),
794            "its temp dir"
795        );
796        assert!(
797            !p.writable.iter().any(|w| w.starts_with("/home/u/code")),
798            "never the project"
799        );
800    }
801
802    #[test]
803    fn a_chat_reads_the_project_but_not_the_rest_of_the_home() {
804        let p = chat_policy(&chat_fixture());
805        assert!(
806            p.unreadable.contains(&PathBuf::from("/home/u")),
807            "the home is closed"
808        );
809        assert!(
810            p.readable.contains(&PathBuf::from("/home/u/code/app")),
811            "the project is open"
812        );
813        assert!(
814            p.readable.contains(&PathBuf::from("/home/u/.claude")),
815            "the agent can log in"
816        );
817        assert!(
818            p.readable.contains(&PathBuf::from("/home/u/.cargo/bin")),
819            "tools on PATH"
820        );
821    }
822
823    #[test]
824    fn a_chat_cannot_see_credentials_or_the_write_token() {
825        let p = chat_policy(&chat_fixture());
826        assert!(
827            p.hidden.contains(&PathBuf::from("/home/u/.ssh")),
828            "ssh keys"
829        );
830        assert!(
831            p.hidden.contains(&PathBuf::from("/home/u/.config/gh")),
832            "the gh token"
833        );
834        assert!(
835            p.hidden
836                .contains(&PathBuf::from("/home/u/.orch/state/cluster.port")),
837            "the daemon's write token"
838        );
839    }
840
841    #[test]
842    fn orch_home_is_read_only_around_the_task_worktree() {
843        let (_root, run) = fixture(false);
844        let p = policy(&run);
845        let o = &run.orch_home;
846        for path in [
847            o.join("config.yml"),
848            o.join("state"),
849            o.join("orch.db"),
850            o.join("worktrees/proj/other"),
851        ] {
852            assert!(
853                p.read_only.contains(&path),
854                "{} not read-only",
855                path.display()
856            );
857        }
858        for path in [
859            o.join("worktrees"),
860            o.join("worktrees/proj"),
861            run.work_dir.clone(),
862        ] {
863            assert!(!p.read_only.contains(&path), "{} read-only", path.display());
864        }
865        assert!(p.writable.contains(&run.work_dir));
866    }
867
868    #[test]
869    fn the_main_checkout_is_read_only_but_its_git_dir() {
870        let (_root, run) = fixture(false);
871        let p = policy(&run);
872        let proj = run.home.join("proj");
873        assert!(p.read_only.contains(&proj.join("src")));
874        assert!(p.read_only.contains(&proj.join("README.md")));
875        assert!(!p.read_only.contains(&proj.join(".git")));
876        assert!(p.read_only.contains(&proj.join(".git/hooks")));
877        assert!(p.read_only.contains(&proj.join(".git/config")));
878    }
879
880    #[test]
881    fn only_the_task_branch_is_writable_in_the_git_dir() {
882        let (_root, run) = fixture(false);
883        let p = policy(&run);
884        let git = run.home.join("proj/.git");
885        for path in [
886            "refs/heads/main",
887            "refs/heads/release",
888            "packed-refs",
889            "hooks",
890            "config",
891            "commondir",
892            "gitdir",
893            "config.worktree",
894        ] {
895            assert!(
896                p.read_only.contains(&git.join(path)),
897                "{path} not read-only"
898            );
899        }
900        assert!(!p.read_only.contains(&git.join("refs/heads/feat/mine")));
901        assert!(!p.read_only.contains(&git.join("refs/heads/feat")));
902        assert!(!p.read_only.contains(&git.join("objects")));
903        assert!(p.read_only.contains(&git.join("worktrees/other")));
904        assert!(p.read_only.contains(&git.join("worktrees/mine/HEAD")));
905        assert!(p.read_only.contains(&run.work_dir.join(".git")));
906        assert!(p.writable.contains(&git));
907    }
908
909    #[test]
910    fn hooks_and_config_of_an_unknown_repository_are_read_only() {
911        let (_root, run) = fixture(false);
912        let git = run.home.join("code/deep/other/.git");
913        fs::create_dir_all(&git).unwrap();
914        let p = policy(&run);
915        assert!(p.read_only.contains(&git.join("hooks")));
916        assert!(p.read_only.contains(&git.join("config")));
917        assert!(!p.read_only.contains(&git));
918    }
919
920    #[test]
921    fn only_the_home_s_cache_dirs_are_writable() {
922        let (_root, run) = fixture(false);
923        let p = policy(&run);
924        let h = &run.home;
925        for path in [".cargo", ".orch", "Library/Caches"] {
926            assert!(p.writable.contains(&h.join(path)), "{path} not writable");
927        }
928        for path in ["", ".config", ".claude", "Library"] {
929            assert!(!p.writable.contains(&h.join(path)), "{path:?} writable");
930        }
931        assert!(p.read_only.contains(&h.join(".cargo/bin")));
932        assert!(!p.read_only.contains(&PathBuf::from("/usr/bin")));
933    }
934
935    #[test]
936    fn no_socket_outside_the_worktree_and_no_launch_services() {
937        let (_root, mut run) = fixture(false);
938        run.seatbelt = true;
939        let p = policy(&run);
940        let Access::Only(sockets) = &p.unix_sockets else {
941            panic!("every unix socket is reachable");
942        };
943        assert_eq!(sockets, &vec![run.work_dir, run.temp]);
944        assert!(
945            !sockets
946                .iter()
947                .any(|s| s.starts_with("/tmp") || s.starts_with("/private/tmp"))
948        );
949        let Access::Only(mach) = &p.mach_services else {
950            panic!("every Mach service is reachable");
951        };
952        assert!(mach.iter().any(|s| s == KEYCHAIN));
953        assert!(!mach.iter().any(|s| s.contains("launchservices")));
954    }
955
956    #[test]
957    fn code_running_config_in_a_writable_home_dir_is_read_only() {
958        let (_root, run) = fixture(false);
959        let p = policy(&run);
960        assert!(p.writable.contains(&run.home.join(".cargo")));
961        assert!(p.read_only.contains(&run.home.join(".cargo/config.toml")));
962    }
963
964    #[test]
965    fn a_git_dir_the_agent_could_have_pointed_elsewhere_is_refused() {
966        let (_root, run) = fixture(false);
967        let (work, main) = (&run.work_dir, run.home.join("proj"));
968        let (git, common) = (
969            run.git_dir.clone().unwrap(),
970            run.common_dir.clone().unwrap(),
971        );
972
973        fs::write(
974            git.join("gitdir"),
975            format!("{}\n", work.join(".git").display()),
976        )
977        .unwrap();
978        assert!(check_git_dirs(work, &main, Some(&git), Some(&common)).is_ok());
979
980        // Pointed at the common dir, which only the main checkout uses
981        assert!(check_git_dirs(work, &main, Some(&common), Some(&common)).is_err());
982        assert!(check_git_dirs(&main, &main, Some(&common), Some(&common)).is_ok());
983        // Another worktree's git dir, or none at all
984        let other = common.join("worktrees/other");
985        fs::write(other.join("gitdir"), "/elsewhere/.git\n").unwrap();
986        assert!(check_git_dirs(work, &main, Some(&other), Some(&common)).is_err());
987        assert!(check_git_dirs(work, &main, Some(&run.home), Some(&common)).is_err());
988        assert!(check_git_dirs(work, &main, None, Some(&common)).is_err());
989    }
990
991    #[test]
992    fn a_job_task_may_write_the_store() {
993        let (_root, run) = fixture(true);
994        assert!(
995            !policy(&run)
996                .read_only
997                .contains(&run.orch_home.join("orch.db"))
998        );
999    }
1000
1001    #[test]
1002    fn only_a_job_task_sees_the_write_endpoint_token() {
1003        let (_root, run) = fixture(false);
1004        let token = run.orch_home.join("state/cluster.port");
1005        assert!(policy(&run).hidden.contains(&token));
1006        let (_root, run) = fixture(true);
1007        assert!(!policy(&run).hidden.contains(&token));
1008    }
1009
1010    #[test]
1011    fn keys_are_hidden_and_startup_files_read_only() {
1012        let (_root, run) = fixture(false);
1013        let p = policy(&run);
1014        assert!(p.hidden.contains(&run.home.join(".ssh")));
1015        assert!(p.hidden.contains(&run.home.join(".gnupg")));
1016        assert!(!p.hidden.iter().any(|h| h.ends_with(".cargo/config.toml")));
1017        assert!(p.read_only.contains(&run.work_dir.join(".orch.yml")));
1018    }
1019
1020    // A real Seatbelt run of the policy. Skipped where no sandbox starts, such as inside another one
1021    #[cfg(target_os = "macos")]
1022    #[test]
1023    fn the_kernel_enforces_the_policy() {
1024        let Ok(backend) = Backend::detect() else {
1025            eprintln!("skipped: no OS sandbox starts here");
1026            return;
1027        };
1028        let (_root, mut run) = fixture(false);
1029        run.seatbelt = backend == Backend::Seatbelt;
1030        let other = run.orch_home.join("worktrees/proj/other");
1031        fs::create_dir_all(run.home.join(".ssh")).unwrap();
1032        fs::write(run.home.join(".ssh/key"), "k").unwrap();
1033        let script = format!(
1034            "echo ok > {w}/f && ! echo x > {o}/config.yml && ! echo x > {other}/f \
1035             && ! echo x > {w}/.orch.yml && ! echo x >> {h}/.zshrc && ! cat {h}/.ssh/key \
1036             && ! echo x > {h}/.new-dotfile && ! echo x > {h}/.claude.json \
1037             && echo cache > {h}/.cargo/probe",
1038            w = run.work_dir.display(),
1039            o = run.orch_home.display(),
1040            other = other.display(),
1041            h = run.home.display(),
1042        );
1043        let out = Sandbox::new(backend, policy(&run))
1044            .unwrap()
1045            .command("/bin/sh")
1046            .args(["-c", &script])
1047            .output()
1048            .unwrap();
1049        assert!(
1050            out.status.success(),
1051            "{}",
1052            String::from_utf8_lossy(&out.stderr)
1053        );
1054        assert!(run.work_dir.join("f").exists());
1055        assert!(!other.join("f").exists());
1056    }
1057
1058    // A socket outside the worktree, such as tmux's, is out of reach, and another branch's ref too
1059    #[cfg(target_os = "macos")]
1060    #[test]
1061    fn the_kernel_keeps_sockets_and_other_branches_out_of_reach() {
1062        let Ok(backend) = Backend::detect() else {
1063            eprintln!("skipped: no OS sandbox starts here");
1064            return;
1065        };
1066        let (_root, mut run) = fixture(false);
1067        run.seatbelt = backend == Backend::Seatbelt;
1068        for dir in [&run.work_dir, &run.home] {
1069            let listener = UnixListener::bind(dir.join("s")).unwrap();
1070            thread::spawn(move || listener.incoming().for_each(drop));
1071        }
1072        let git = run.home.join("proj/.git");
1073        let script = format!(
1074            "/usr/bin/nc -U {w}/s </dev/null && ! /usr/bin/nc -U {h}/s </dev/null \
1075             && echo sha > {g}/refs/heads/feat/mine && ! echo sha > {g}/refs/heads/main",
1076            w = run.work_dir.display(),
1077            h = run.home.display(),
1078            g = git.display(),
1079        );
1080        let out = Sandbox::new(backend, policy(&run))
1081            .unwrap()
1082            .command("/bin/sh")
1083            .args(["-c", &script])
1084            .output()
1085            .unwrap();
1086        assert!(
1087            out.status.success(),
1088            "{}",
1089            String::from_utf8_lossy(&out.stderr)
1090        );
1091        assert_eq!(fs::read_to_string(git.join("refs/heads/main")).unwrap(), "");
1092    }
1093
1094    // A missing commondir in the common dir would redirect git to a dir the agent controls
1095    #[cfg(target_os = "macos")]
1096    #[test]
1097    fn the_kernel_refuses_a_new_commondir_in_the_common_dir() {
1098        let Ok(backend) = Backend::detect() else {
1099            eprintln!("skipped: no OS sandbox starts here");
1100            return;
1101        };
1102        let (_root, mut run) = fixture(false);
1103        run.seatbelt = backend == Backend::Seatbelt;
1104        let git = run.home.join("proj/.git");
1105        assert!(!git.join("commondir").exists());
1106        let script = format!(
1107            "! echo {w} > {g}/commondir",
1108            w = run.work_dir.display(),
1109            g = git.display()
1110        );
1111        let out = Sandbox::new(backend, policy(&run))
1112            .unwrap()
1113            .command("/bin/sh")
1114            .args(["-c", &script])
1115            .output()
1116            .unwrap();
1117        assert!(
1118            out.status.success(),
1119            "{}",
1120            String::from_utf8_lossy(&out.stderr)
1121        );
1122        assert!(!git.join("commondir").exists());
1123    }
1124
1125    // Removing or replacing tmux's socket file is refused
1126    #[cfg(target_os = "macos")]
1127    #[test]
1128    fn the_kernel_keeps_the_tmux_socket_in_the_temp_dir_in_place() {
1129        let Ok(backend) = Backend::detect() else {
1130            eprintln!("skipped: no OS sandbox starts here");
1131            return;
1132        };
1133        let (_root, mut run) = fixture(false);
1134        run.seatbelt = backend == Backend::Seatbelt;
1135        let dir = tempfile::Builder::new()
1136            .prefix("tmux-")
1137            .tempdir_in(&run.home)
1138            .unwrap();
1139        run.temp = run.home.clone();
1140        let sock = dir.path().join("default");
1141        fs::write(&sock, "").unwrap();
1142        let script = format!(
1143            "! rm {s} && ! mv {s} {s}2 && ! echo x > {d}/new",
1144            s = sock.display(),
1145            d = dir.path().display(),
1146        );
1147        let out = Sandbox::new(backend, policy(&run))
1148            .unwrap()
1149            .command("/bin/sh")
1150            .args(["-c", &script])
1151            .output()
1152            .unwrap();
1153        assert!(
1154            out.status.success(),
1155            "{}",
1156            String::from_utf8_lossy(&out.stderr)
1157        );
1158        assert!(sock.exists());
1159    }
1160
1161    // A logged-in claude answers under the policy with the real home: `--run-ignored only claude`
1162    #[cfg(target_os = "macos")]
1163    #[test]
1164    #[ignore = "needs a logged-in claude on the host"]
1165    fn claude_answers_inside_the_sandbox_with_the_real_home() {
1166        let root = tempfile::tempdir().unwrap();
1167        let work = root.path().canonicalize().unwrap();
1168        let home = PathBuf::from(env::var_os("HOME").unwrap());
1169        let run = Run {
1170            work_dir: work.clone(),
1171            git_dir: None,
1172            common_dir: None,
1173            own_ref: None,
1174            home: home.clone(),
1175            orch_home: home.join(".orch"),
1176            projects: vec![],
1177            path_dirs: env::split_paths(&env::var_os("PATH").unwrap()).collect(),
1178            temp: env::temp_dir(),
1179            internal: false,
1180            seatbelt: true,
1181        };
1182        let out = Sandbox::new(Backend::Seatbelt, policy(&run))
1183            .unwrap()
1184            .command("/bin/sh")
1185            .args(["-c", "claude -p --model haiku 'Reply with the word ok'"])
1186            .current_dir(&work)
1187            .output()
1188            .unwrap();
1189        let text = String::from_utf8_lossy(&out.stdout).to_lowercase();
1190        assert!(
1191            text.contains("ok"),
1192            "{text}{}",
1193            String::from_utf8_lossy(&out.stderr)
1194        );
1195    }
1196
1197    #[test]
1198    fn a_worktree_that_is_the_main_checkout_stays_writable() {
1199        let (_root, mut run) = fixture(false);
1200        run.work_dir = run.home.join("proj");
1201        let p = policy(&run);
1202        assert!(!p.read_only.contains(&run.work_dir));
1203        assert!(!p.read_only.contains(&run.work_dir.join("src")));
1204    }
1205}