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            work_dir: PathBuf::from("/nonexistent/work"),
646            system_prompt: String::new(),
647            agent_message: String::new(),
648            task_id: "t".to_string(),
649            disallowed_tools: vec![],
650            git_author_name: String::new(),
651            git_author_email: String::new(),
652            output_file: PathBuf::from("/nonexistent/out.json"),
653            timeout_seconds: 0,
654            repo: "o/r".to_string(),
655            attempt: 1,
656            sandbox: true,
657            main_project_dir: PathBuf::from("/nonexistent/main"),
658            branch: String::new(),
659        };
660        let err = argv(&inv, Path::new("/tmp/orch-test-run"))
661            .await
662            .expect_err("no checkout, so no sandbox");
663        assert!(err.downcast_ref::<SandboxFailed>().is_some());
664        assert!(err.to_string().starts_with("the OS sandbox cannot start: "));
665    }
666
667    /// A home with an orch home inside, two worktrees and a main checkout, and the run of one task
668    fn fixture(internal: bool) -> (tempfile::TempDir, Run) {
669        let root = tempfile::tempdir().unwrap();
670        let r = root.path().canonicalize().unwrap();
671        let (home, orch) = (r.join("home"), r.join("home/.orch"));
672        for dir in [
673            "home/.orch/worktrees/proj/mine",
674            "home/.orch/worktrees/proj/other",
675            "home/.orch/state",
676            "home/proj/.git/worktrees/mine",
677            "home/proj/.git/refs/heads/feat",
678            "home/proj/src",
679            "home/proj/.git/objects",
680            "home/proj/.git/worktrees/other",
681            "home/.config/nvim",
682            "home/.claude",
683            "home/.cargo/bin",
684            "home/Library/Caches",
685            "home/Library/LaunchAgents",
686        ] {
687            fs::create_dir_all(r.join(dir)).unwrap();
688        }
689        for file in [
690            "home/.orch/config.yml",
691            "home/.orch/orch.db",
692            "home/proj/README.md",
693            "home/proj/.git/refs/heads/main",
694            "home/proj/.git/refs/heads/feat/mine",
695            "home/proj/.git/worktrees/mine/HEAD",
696            "home/.zshrc",
697            "home/.claude.json",
698        ] {
699            fs::write(r.join(file), "").unwrap();
700        }
701        fs::write(
702            r.join("home/proj/.git/packed-refs"),
703            "# pack-refs with: peeled\nabc refs/heads/release\n",
704        )
705        .unwrap();
706
707        let run = Run {
708            work_dir: orch.join("worktrees/proj/mine"),
709            git_dir: Some(home.join("proj/.git/worktrees/mine")),
710            common_dir: Some(home.join("proj/.git")),
711            own_ref: Some("refs/heads/feat/mine".into()),
712            home: home.clone(),
713            orch_home: orch,
714            projects: vec![home.join("proj")],
715            path_dirs: vec![home.join(".cargo/bin"), "/usr/bin".into()],
716            temp: r.join("tmp"),
717            internal,
718            seatbelt: false,
719        };
720        (root, run)
721    }
722
723    fn chat_fixture() -> ChatRun {
724        ChatRun {
725            home: PathBuf::from("/home/u"),
726            orch_home: PathBuf::from("/home/u/.orch"),
727            project: Some(PathBuf::from("/home/u/code/app")),
728            temp: PathBuf::from("/tmp/chat"),
729            path_dirs: vec![
730                PathBuf::from("/home/u/.cargo/bin"),
731                PathBuf::from("/usr/bin"),
732            ],
733            seatbelt: true,
734            control: false,
735        }
736    }
737
738    #[test]
739    fn no_task_can_read_the_web_ui_token() {
740        for internal in [false, true] {
741            let (_root, run) = fixture(internal);
742            let token = run.orch_home.join("state/ui.port");
743            assert!(policy(&run).hidden.contains(&token), "internal: {internal}");
744        }
745    }
746
747    #[test]
748    fn no_chat_can_read_the_web_ui_token() {
749        let token = PathBuf::from("/home/u/.orch/state/ui.port");
750        let mut run = chat_fixture();
751        assert!(
752            chat_policy(&run).hidden.contains(&token),
753            "the project chat"
754        );
755        run.project = None;
756        run.control = true;
757        assert!(
758            chat_policy(&run).hidden.contains(&token),
759            "the control chat"
760        );
761    }
762
763    #[test]
764    fn the_control_chat_reads_no_project_and_may_act_through_orch() {
765        let mut run = chat_fixture();
766        run.project = None;
767        run.control = true;
768        let p = chat_policy(&run);
769        assert!(
770            !p.readable.iter().any(|r| r.starts_with("/home/u/code")),
771            "no project folder"
772        );
773        assert!(
774            !p.hidden
775                .contains(&PathBuf::from("/home/u/.orch/state/cluster.port")),
776            "it acts through the daemon"
777        );
778        assert!(
779            p.hidden.contains(&PathBuf::from("/home/u/.ssh")),
780            "credentials stay hidden"
781        );
782        assert!(
783            p.unreadable.contains(&PathBuf::from("/home/u")),
784            "the home stays closed"
785        );
786    }
787
788    #[test]
789    fn a_chat_writes_only_its_temp_dir() {
790        let p = chat_policy(&chat_fixture());
791        assert!(
792            p.writable.contains(&PathBuf::from("/tmp/chat")),
793            "its temp dir"
794        );
795        assert!(
796            !p.writable.iter().any(|w| w.starts_with("/home/u/code")),
797            "never the project"
798        );
799    }
800
801    #[test]
802    fn a_chat_reads_the_project_but_not_the_rest_of_the_home() {
803        let p = chat_policy(&chat_fixture());
804        assert!(
805            p.unreadable.contains(&PathBuf::from("/home/u")),
806            "the home is closed"
807        );
808        assert!(
809            p.readable.contains(&PathBuf::from("/home/u/code/app")),
810            "the project is open"
811        );
812        assert!(
813            p.readable.contains(&PathBuf::from("/home/u/.claude")),
814            "the agent can log in"
815        );
816        assert!(
817            p.readable.contains(&PathBuf::from("/home/u/.cargo/bin")),
818            "tools on PATH"
819        );
820    }
821
822    #[test]
823    fn a_chat_cannot_see_credentials_or_the_write_token() {
824        let p = chat_policy(&chat_fixture());
825        assert!(
826            p.hidden.contains(&PathBuf::from("/home/u/.ssh")),
827            "ssh keys"
828        );
829        assert!(
830            p.hidden.contains(&PathBuf::from("/home/u/.config/gh")),
831            "the gh token"
832        );
833        assert!(
834            p.hidden
835                .contains(&PathBuf::from("/home/u/.orch/state/cluster.port")),
836            "the daemon's write token"
837        );
838    }
839
840    #[test]
841    fn orch_home_is_read_only_around_the_task_worktree() {
842        let (_root, run) = fixture(false);
843        let p = policy(&run);
844        let o = &run.orch_home;
845        for path in [
846            o.join("config.yml"),
847            o.join("state"),
848            o.join("orch.db"),
849            o.join("worktrees/proj/other"),
850        ] {
851            assert!(
852                p.read_only.contains(&path),
853                "{} not read-only",
854                path.display()
855            );
856        }
857        for path in [
858            o.join("worktrees"),
859            o.join("worktrees/proj"),
860            run.work_dir.clone(),
861        ] {
862            assert!(!p.read_only.contains(&path), "{} read-only", path.display());
863        }
864        assert!(p.writable.contains(&run.work_dir));
865    }
866
867    #[test]
868    fn the_main_checkout_is_read_only_but_its_git_dir() {
869        let (_root, run) = fixture(false);
870        let p = policy(&run);
871        let proj = run.home.join("proj");
872        assert!(p.read_only.contains(&proj.join("src")));
873        assert!(p.read_only.contains(&proj.join("README.md")));
874        assert!(!p.read_only.contains(&proj.join(".git")));
875        assert!(p.read_only.contains(&proj.join(".git/hooks")));
876        assert!(p.read_only.contains(&proj.join(".git/config")));
877    }
878
879    #[test]
880    fn only_the_task_branch_is_writable_in_the_git_dir() {
881        let (_root, run) = fixture(false);
882        let p = policy(&run);
883        let git = run.home.join("proj/.git");
884        for path in [
885            "refs/heads/main",
886            "refs/heads/release",
887            "packed-refs",
888            "hooks",
889            "config",
890            "commondir",
891            "gitdir",
892            "config.worktree",
893        ] {
894            assert!(
895                p.read_only.contains(&git.join(path)),
896                "{path} not read-only"
897            );
898        }
899        assert!(!p.read_only.contains(&git.join("refs/heads/feat/mine")));
900        assert!(!p.read_only.contains(&git.join("refs/heads/feat")));
901        assert!(!p.read_only.contains(&git.join("objects")));
902        assert!(p.read_only.contains(&git.join("worktrees/other")));
903        assert!(p.read_only.contains(&git.join("worktrees/mine/HEAD")));
904        assert!(p.read_only.contains(&run.work_dir.join(".git")));
905        assert!(p.writable.contains(&git));
906    }
907
908    #[test]
909    fn hooks_and_config_of_an_unknown_repository_are_read_only() {
910        let (_root, run) = fixture(false);
911        let git = run.home.join("code/deep/other/.git");
912        fs::create_dir_all(&git).unwrap();
913        let p = policy(&run);
914        assert!(p.read_only.contains(&git.join("hooks")));
915        assert!(p.read_only.contains(&git.join("config")));
916        assert!(!p.read_only.contains(&git));
917    }
918
919    #[test]
920    fn only_the_home_s_cache_dirs_are_writable() {
921        let (_root, run) = fixture(false);
922        let p = policy(&run);
923        let h = &run.home;
924        for path in [".cargo", ".orch", "Library/Caches"] {
925            assert!(p.writable.contains(&h.join(path)), "{path} not writable");
926        }
927        for path in ["", ".config", ".claude", "Library"] {
928            assert!(!p.writable.contains(&h.join(path)), "{path:?} writable");
929        }
930        assert!(p.read_only.contains(&h.join(".cargo/bin")));
931        assert!(!p.read_only.contains(&PathBuf::from("/usr/bin")));
932    }
933
934    #[test]
935    fn no_socket_outside_the_worktree_and_no_launch_services() {
936        let (_root, mut run) = fixture(false);
937        run.seatbelt = true;
938        let p = policy(&run);
939        let Access::Only(sockets) = &p.unix_sockets else {
940            panic!("every unix socket is reachable");
941        };
942        assert_eq!(sockets, &vec![run.work_dir, run.temp]);
943        assert!(
944            !sockets
945                .iter()
946                .any(|s| s.starts_with("/tmp") || s.starts_with("/private/tmp"))
947        );
948        let Access::Only(mach) = &p.mach_services else {
949            panic!("every Mach service is reachable");
950        };
951        assert!(mach.iter().any(|s| s == KEYCHAIN));
952        assert!(!mach.iter().any(|s| s.contains("launchservices")));
953    }
954
955    #[test]
956    fn code_running_config_in_a_writable_home_dir_is_read_only() {
957        let (_root, run) = fixture(false);
958        let p = policy(&run);
959        assert!(p.writable.contains(&run.home.join(".cargo")));
960        assert!(p.read_only.contains(&run.home.join(".cargo/config.toml")));
961    }
962
963    #[test]
964    fn a_git_dir_the_agent_could_have_pointed_elsewhere_is_refused() {
965        let (_root, run) = fixture(false);
966        let (work, main) = (&run.work_dir, run.home.join("proj"));
967        let (git, common) = (
968            run.git_dir.clone().unwrap(),
969            run.common_dir.clone().unwrap(),
970        );
971
972        fs::write(
973            git.join("gitdir"),
974            format!("{}\n", work.join(".git").display()),
975        )
976        .unwrap();
977        assert!(check_git_dirs(work, &main, Some(&git), Some(&common)).is_ok());
978
979        // Pointed at the common dir, which only the main checkout uses
980        assert!(check_git_dirs(work, &main, Some(&common), Some(&common)).is_err());
981        assert!(check_git_dirs(&main, &main, Some(&common), Some(&common)).is_ok());
982        // Another worktree's git dir, or none at all
983        let other = common.join("worktrees/other");
984        fs::write(other.join("gitdir"), "/elsewhere/.git\n").unwrap();
985        assert!(check_git_dirs(work, &main, Some(&other), Some(&common)).is_err());
986        assert!(check_git_dirs(work, &main, Some(&run.home), Some(&common)).is_err());
987        assert!(check_git_dirs(work, &main, None, Some(&common)).is_err());
988    }
989
990    #[test]
991    fn a_job_task_may_write_the_store() {
992        let (_root, run) = fixture(true);
993        assert!(
994            !policy(&run)
995                .read_only
996                .contains(&run.orch_home.join("orch.db"))
997        );
998    }
999
1000    #[test]
1001    fn only_a_job_task_sees_the_write_endpoint_token() {
1002        let (_root, run) = fixture(false);
1003        let token = run.orch_home.join("state/cluster.port");
1004        assert!(policy(&run).hidden.contains(&token));
1005        let (_root, run) = fixture(true);
1006        assert!(!policy(&run).hidden.contains(&token));
1007    }
1008
1009    #[test]
1010    fn keys_are_hidden_and_startup_files_read_only() {
1011        let (_root, run) = fixture(false);
1012        let p = policy(&run);
1013        assert!(p.hidden.contains(&run.home.join(".ssh")));
1014        assert!(p.hidden.contains(&run.home.join(".gnupg")));
1015        assert!(!p.hidden.iter().any(|h| h.ends_with(".cargo/config.toml")));
1016        assert!(p.read_only.contains(&run.work_dir.join(".orch.yml")));
1017    }
1018
1019    // A real Seatbelt run of the policy. Skipped where no sandbox starts, such as inside another one
1020    #[cfg(target_os = "macos")]
1021    #[test]
1022    fn the_kernel_enforces_the_policy() {
1023        let Ok(backend) = Backend::detect() else {
1024            eprintln!("skipped: no OS sandbox starts here");
1025            return;
1026        };
1027        let (_root, mut run) = fixture(false);
1028        run.seatbelt = backend == Backend::Seatbelt;
1029        let other = run.orch_home.join("worktrees/proj/other");
1030        fs::create_dir_all(run.home.join(".ssh")).unwrap();
1031        fs::write(run.home.join(".ssh/key"), "k").unwrap();
1032        let script = format!(
1033            "echo ok > {w}/f && ! echo x > {o}/config.yml && ! echo x > {other}/f \
1034             && ! echo x > {w}/.orch.yml && ! echo x >> {h}/.zshrc && ! cat {h}/.ssh/key \
1035             && ! echo x > {h}/.new-dotfile && ! echo x > {h}/.claude.json \
1036             && echo cache > {h}/.cargo/probe",
1037            w = run.work_dir.display(),
1038            o = run.orch_home.display(),
1039            other = other.display(),
1040            h = run.home.display(),
1041        );
1042        let out = Sandbox::new(backend, policy(&run))
1043            .unwrap()
1044            .command("/bin/sh")
1045            .args(["-c", &script])
1046            .output()
1047            .unwrap();
1048        assert!(
1049            out.status.success(),
1050            "{}",
1051            String::from_utf8_lossy(&out.stderr)
1052        );
1053        assert!(run.work_dir.join("f").exists());
1054        assert!(!other.join("f").exists());
1055    }
1056
1057    // A socket outside the worktree, such as tmux's, is out of reach, and another branch's ref too
1058    #[cfg(target_os = "macos")]
1059    #[test]
1060    fn the_kernel_keeps_sockets_and_other_branches_out_of_reach() {
1061        let Ok(backend) = Backend::detect() else {
1062            eprintln!("skipped: no OS sandbox starts here");
1063            return;
1064        };
1065        let (_root, mut run) = fixture(false);
1066        run.seatbelt = backend == Backend::Seatbelt;
1067        for dir in [&run.work_dir, &run.home] {
1068            let listener = UnixListener::bind(dir.join("s")).unwrap();
1069            thread::spawn(move || listener.incoming().for_each(drop));
1070        }
1071        let git = run.home.join("proj/.git");
1072        let script = format!(
1073            "/usr/bin/nc -U {w}/s </dev/null && ! /usr/bin/nc -U {h}/s </dev/null \
1074             && echo sha > {g}/refs/heads/feat/mine && ! echo sha > {g}/refs/heads/main",
1075            w = run.work_dir.display(),
1076            h = run.home.display(),
1077            g = git.display(),
1078        );
1079        let out = Sandbox::new(backend, policy(&run))
1080            .unwrap()
1081            .command("/bin/sh")
1082            .args(["-c", &script])
1083            .output()
1084            .unwrap();
1085        assert!(
1086            out.status.success(),
1087            "{}",
1088            String::from_utf8_lossy(&out.stderr)
1089        );
1090        assert_eq!(fs::read_to_string(git.join("refs/heads/main")).unwrap(), "");
1091    }
1092
1093    // A missing commondir in the common dir would redirect git to a dir the agent controls
1094    #[cfg(target_os = "macos")]
1095    #[test]
1096    fn the_kernel_refuses_a_new_commondir_in_the_common_dir() {
1097        let Ok(backend) = Backend::detect() else {
1098            eprintln!("skipped: no OS sandbox starts here");
1099            return;
1100        };
1101        let (_root, mut run) = fixture(false);
1102        run.seatbelt = backend == Backend::Seatbelt;
1103        let git = run.home.join("proj/.git");
1104        assert!(!git.join("commondir").exists());
1105        let script = format!(
1106            "! echo {w} > {g}/commondir",
1107            w = run.work_dir.display(),
1108            g = git.display()
1109        );
1110        let out = Sandbox::new(backend, policy(&run))
1111            .unwrap()
1112            .command("/bin/sh")
1113            .args(["-c", &script])
1114            .output()
1115            .unwrap();
1116        assert!(
1117            out.status.success(),
1118            "{}",
1119            String::from_utf8_lossy(&out.stderr)
1120        );
1121        assert!(!git.join("commondir").exists());
1122    }
1123
1124    // Removing or replacing tmux's socket file is refused
1125    #[cfg(target_os = "macos")]
1126    #[test]
1127    fn the_kernel_keeps_the_tmux_socket_in_the_temp_dir_in_place() {
1128        let Ok(backend) = Backend::detect() else {
1129            eprintln!("skipped: no OS sandbox starts here");
1130            return;
1131        };
1132        let (_root, mut run) = fixture(false);
1133        run.seatbelt = backend == Backend::Seatbelt;
1134        let dir = tempfile::Builder::new()
1135            .prefix("tmux-")
1136            .tempdir_in(&run.home)
1137            .unwrap();
1138        run.temp = run.home.clone();
1139        let sock = dir.path().join("default");
1140        fs::write(&sock, "").unwrap();
1141        let script = format!(
1142            "! rm {s} && ! mv {s} {s}2 && ! echo x > {d}/new",
1143            s = sock.display(),
1144            d = dir.path().display(),
1145        );
1146        let out = Sandbox::new(backend, policy(&run))
1147            .unwrap()
1148            .command("/bin/sh")
1149            .args(["-c", &script])
1150            .output()
1151            .unwrap();
1152        assert!(
1153            out.status.success(),
1154            "{}",
1155            String::from_utf8_lossy(&out.stderr)
1156        );
1157        assert!(sock.exists());
1158    }
1159
1160    // A logged-in claude answers under the policy with the real home: `--run-ignored only claude`
1161    #[cfg(target_os = "macos")]
1162    #[test]
1163    #[ignore = "needs a logged-in claude on the host"]
1164    fn claude_answers_inside_the_sandbox_with_the_real_home() {
1165        let root = tempfile::tempdir().unwrap();
1166        let work = root.path().canonicalize().unwrap();
1167        let home = PathBuf::from(env::var_os("HOME").unwrap());
1168        let run = Run {
1169            work_dir: work.clone(),
1170            git_dir: None,
1171            common_dir: None,
1172            own_ref: None,
1173            home: home.clone(),
1174            orch_home: home.join(".orch"),
1175            projects: vec![],
1176            path_dirs: env::split_paths(&env::var_os("PATH").unwrap()).collect(),
1177            temp: env::temp_dir(),
1178            internal: false,
1179            seatbelt: true,
1180        };
1181        let out = Sandbox::new(Backend::Seatbelt, policy(&run))
1182            .unwrap()
1183            .command("/bin/sh")
1184            .args(["-c", "claude -p --model haiku 'Reply with the word ok'"])
1185            .current_dir(&work)
1186            .output()
1187            .unwrap();
1188        let text = String::from_utf8_lossy(&out.stdout).to_lowercase();
1189        assert!(
1190            text.contains("ok"),
1191            "{text}{}",
1192            String::from_utf8_lossy(&out.stderr)
1193        );
1194    }
1195
1196    #[test]
1197    fn a_worktree_that_is_the_main_checkout_stays_writable() {
1198        let (_root, mut run) = fixture(false);
1199        run.work_dir = run.home.join("proj");
1200        let p = policy(&run);
1201        assert!(!p.read_only.contains(&run.work_dir));
1202        assert!(!p.read_only.contains(&run.work_dir.join("src")));
1203    }
1204}