Skip to main content

orch/engine/runner/
sandbox.rs

1//! The OS sandbox around a task or review agent, on unless `workflow.sandbox` is `false`. The policy and
2//! why it is shaped this way are in docs/plans/2026-10-28-agent-sandboxes.md
3
4use crate::config;
5use crate::home;
6use sandbox_jail::{Access, Backend, Policy, Sandbox, known};
7use std::env;
8use std::error;
9use std::ffi::OsString;
10use std::fmt;
11use std::fmt::Display;
12use std::fmt::Formatter;
13use std::fs;
14use std::path::{Component, Path, PathBuf};
15use std::sync::{Mutex, PoisonError};
16use std::time::{Duration, Instant};
17use tokio::fs as async_fs;
18use tokio::process::Command;
19use tokio::task;
20
21/// Top-level dirs of the home that stay read-only: what loads or runs later as the operator, the
22/// agents' own settings, and keys. Everything at the top of the home that is not a dir is read-only too
23const HOME_READ_ONLY: &[&str] = &[
24    ".config", ".claude", ".ssh", ".gnupg", "bin", "Library", ".local", ".passbox",
25];
26
27/// Writable parts of the read-only dirs above, for caches and agent state
28const HOME_WRITABLE: &[&str] = &[
29    "Library/Caches",
30    "Library/Logs",
31    ".local/share",
32    ".local/state",
33];
34
35/// Codex's settings and instructions, which sit beside the state it rewrites
36const AGENT_CONFIG: &[&str] = &[".codex/config.toml", ".codex/AGENTS.md", ".codex/rules"];
37
38/// Config inside writable home dirs that runs code on the operator's next build or shell, read-only
39/// even when missing. Cargo's `rustc-wrapper` and `runner`, gradle's init scripts, shell frameworks
40const HOME_EXEC_CONFIG: &[&str] = &[
41    ".cargo/config",
42    ".cargo/config.toml",
43    ".gradle/init.d",
44    ".gradle/init.gradle",
45    ".gradle/gradle.properties",
46    ".m2/settings.xml",
47    ".oh-my-zsh",
48    ".zprezto",
49];
50
51/// The one socket in the home an agent may connect to: passbox's broker, which asks the operator
52/// before it hands out a secret. Its ssh-agent socket beside it stays out of reach
53const HOME_SOCKETS: &[&str] = &[".passbox/broker.sock"];
54
55/// State other tools trust, inside the writable `.local/state`, read-only even when missing:
56/// shipcheck posts a PR's required checks from its cache and runs what its `trusted` file names
57const HOME_TRUSTED_STATE: &[&str] = &[".local/state/shipcheck"];
58
59/// The address and password of opencode's background service, which runs tools outside the sandbox
60const OPENCODE_SERVICE: &[&str] = &[
61    ".local/state/opencode/service.json",
62    ".config/opencode/service.json",
63];
64
65/// The tmux, ssh-agent and Docker sockets that would let an agent start a process outside
66const SCRATCH: &[&str] = &["/tmp", "/run", "/var/tmp"];
67
68/// macOS services an agent may look up: the basics, and securityd for its keychain login. Not
69/// LaunchServices, which `open` uses to start an app outside the sandbox
70const KEYCHAIN: &str = "com.apple.SecurityServer";
71
72/// More services a task agent may look up: certificate trust, which `curl` needs for chains the
73/// system file lacks, and the read-only LaunchServices database, which `xcodebuild` needs to tell
74/// a project from a folder. Neither starts a process
75const TASK_MACH_SERVICES: &[&str] = &["com.apple.TrustEvaluationAgent", "com.apple.lsd.mapdb"];
76
77/// The calendar, which scheduled jobs read. A GitHub-issue task has no use for it
78const JOB_MACH_SERVICES: &[&str] = &["com.apple.CalendarAgent"];
79
80/// The run's own temp dir, so no socket of the operator's apps in the shared one is in reach
81pub fn run_temp_dir(attempt_dir: &Path) -> PathBuf {
82    attempt_dir.join("tmp")
83}
84
85/// The empty config dir `gh` gets in the sandbox, inside the run's temp dir
86pub fn gh_config_dir(temp: &Path) -> PathBuf {
87    temp.join("gh")
88}
89
90/// Whether the project runs its agents in the sandbox. It is on unless `workflow.sandbox` is
91/// `false` in the project's `.orch.yml` or the global config
92pub fn enabled(project_dir: &Path) -> bool {
93    is_on(config::get_for_project(project_dir, "workflow.sandbox").ok())
94}
95
96/// Like [`enabled`] from the global config alone, for a run whose project is unknown
97pub fn enabled_globally() -> bool {
98    is_on(config::get_global("workflow.sandbox").ok())
99}
100
101// Only an explicit `false` turns it off, so a typo in the value cannot run an agent unsandboxed
102fn is_on(setting: Option<String>) -> bool {
103    setting.is_none_or(|v| v.trim() != "false")
104}
105
106/**
107 * The program and arguments that go before the agent command, or why the sandbox cannot start.
108 * The worktree's `.git` file is the agent's to write, so the common dir comes from the main
109 * checkout and the branch from orch's records, and a git dir outside them refuses the run
110 **/
111pub async fn argv(inv: &Scope<'_>, temp: &Path) -> anyhow::Result<Vec<OsString>> {
112    build(inv, temp)
113        .await
114        .map_err(|e| anyhow::Error::new(SandboxFailed(format!("{e:#}"))))
115}
116
117/// The parts of an agent run the sandbox policy depends on
118#[derive(Debug)]
119pub struct Scope<'a> {
120    pub work_dir: &'a Path,
121    pub main_project_dir: &'a Path,
122    pub branch: &'a str,
123    pub task_id: &'a str,
124}
125
126/// The sandbox cannot start. It is the operator's setup, so it blocks the task and counts against no agent
127#[derive(Debug)]
128pub struct SandboxFailed(pub String);
129
130impl Display for SandboxFailed {
131    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
132        write!(f, "the OS sandbox cannot start: {}", self.0)
133    }
134}
135
136impl error::Error for SandboxFailed {}
137
138async fn build(inv: &Scope<'_>, temp: &Path) -> anyhow::Result<Vec<OsString>> {
139    let backend = Backend::detect()?;
140    let common_dir = resolve_git_dir_arg(inv.main_project_dir, "--git-common-dir").await?;
141    let git_dir = resolve_git_dir_arg(inv.work_dir, "--git-dir").await?;
142
143    check_git_dirs(
144        inv.work_dir,
145        inv.main_project_dir,
146        git_dir.as_deref(),
147        common_dir.as_deref(),
148    )?;
149
150    let home = env::var_os("HOME")
151        .map(PathBuf::from)
152        .ok_or_else(|| anyhow::anyhow!("HOME is not set, so the sandbox cannot hide its keys"))?;
153    let mut projects: Vec<PathBuf> = config::get_projects_with_paths()
154        .unwrap_or_default()
155        .into_iter()
156        .map(|(_, dir)| dir)
157        // A config with `gh.repo` and no `projects:` names the project `.`, a path no policy holds
158        .filter(|dir| dir.is_absolute())
159        .collect();
160    projects.push(inv.main_project_dir.to_path_buf());
161    let path_dirs = env::var_os("PATH")
162        .map(|p| env::split_paths(&p).collect())
163        .unwrap_or_default();
164
165    let extra = Extra::from_config(inv.main_project_dir, &home);
166    let run = Run {
167        work_dir: inv.work_dir.to_path_buf(),
168        git_dir,
169        common_dir,
170        own_ref: (!inv.branch.is_empty()).then(|| format!("refs/heads/{}", inv.branch)),
171        home,
172        orch_home: home::orch_home()?,
173        projects,
174        path_dirs,
175        temp: temp.to_path_buf(),
176        extra,
177        internal: inv.task_id.starts_with("internal:"),
178        seatbelt: backend == Backend::Seatbelt,
179    };
180    // The policy reads many dirs, so it stays off the async workers
181    task::spawn_blocking(move || {
182        // bwrap binds only a path that exists, and the preflight's temp dir is new
183        fs::create_dir_all(&run.temp)?;
184        let sandbox = Sandbox::new(backend, policy(&run))?;
185        Ok(sandbox.argv().to_vec())
186    })
187    .await?
188}
189
190/**
191 * Refuses a worktree whose git dir the agent could have pointed elsewhere. Only the main checkout
192 * has the common dir as its git dir. A linked worktree's git dir is in `<common>/worktrees`, and
193 * its `gitdir` file, which the agent cannot write, points back at this worktree
194 **/
195fn check_git_dirs(
196    work_dir: &Path,
197    main_project_dir: &Path,
198    git_dir: Option<&Path>,
199    common_dir: Option<&Path>,
200) -> anyhow::Result<()> {
201    let real = |p: &Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
202
203    match (git_dir, common_dir) {
204        (Some(git), Some(common)) if git == common => anyhow::ensure!(
205            real(work_dir) == real(main_project_dir),
206            "the worktree {} uses the repository's own git dir {}",
207            work_dir.display(),
208            common.display()
209        ),
210        (Some(git), Some(common)) => {
211            anyhow::ensure!(
212                git.starts_with(common.join("worktrees")),
213                "the worktree's git dir {} is outside its repository {}",
214                git.display(),
215                common.display()
216            );
217            let back = fs::read_to_string(git.join("gitdir")).unwrap_or_default();
218            anyhow::ensure!(
219                real(Path::new(back.trim())) == real(&work_dir.join(".git")),
220                "the git dir {} belongs to another worktree",
221                git.display()
222            );
223        }
224        (None, Some(common)) => anyhow::bail!(
225            "the worktree {} has no git dir in {}",
226            work_dir.display(),
227            common.display()
228        ),
229        _ => {}
230    }
231
232    Ok(())
233}
234
235/**
236 * Paths added to the policy. `sandbox.write` adds a writable path, from the main checkout's
237 * `.orch.yml` and the global config. `sandbox.read`, which shows a hidden credential path, and
238 * `sandbox.sockets`, a unix socket or a dir of them, come from the global config alone: a merged
239 * change to `.orch.yml` must not hand later tasks a credential or Docker's socket. No entry lifts
240 * a read-only rule, which wins over a writable one
241 **/
242#[derive(Default)]
243struct Extra {
244    write: Vec<PathBuf>,
245    read: Vec<PathBuf>,
246    sockets: Vec<PathBuf>,
247}
248
249impl Extra {
250    fn from_config(project_dir: &Path, home: &Path) -> Self {
251        let paths = |list: Vec<String>| -> Vec<PathBuf> {
252            list.iter().filter_map(|text| expand(text, home)).collect()
253        };
254        let mut write = paths(config::get_list_for_project(project_dir, "sandbox.write"));
255        write.retain(|path| {
256            let allowed = may_write(path, home);
257
258            if !allowed {
259                tracing::warn!(path = %path.display(), "sandbox.write entry refused, it is too wide or holds keys or startup files");
260            }
261
262            allowed
263        });
264        Self {
265            write,
266            read: paths(config::get_global_list("sandbox.read")),
267            sockets: paths(config::get_global_list("sandbox.sockets")),
268        }
269    }
270}
271
272/// Parts of the home no config entry makes writable: keys, the agents' and orch's own files, and
273/// what runs at login or from `PATH`
274const NEVER_WRITABLE: &[&str] = &[
275    ".ssh",
276    ".gnupg",
277    ".passbox",
278    ".claude",
279    ".orch",
280    ".config/git",
281    "bin",
282    ".local/bin",
283    "library/launchagents",
284    "library/keychains",
285];
286
287/**
288 * Whether a `sandbox.write` entry is narrow enough: not the home, a parent of it or an entry at
289 * its top, where the shell's startup files are, and not inside [`NEVER_WRITABLE`], whatever its
290 * case, since macOS file systems ignore it. A guard against a mistake: `.orch.yml` is trusted as
291 * a whole, its `bash` jobs already run as the operator
292 **/
293fn may_write(path: &Path, home: &Path) -> bool {
294    if home.starts_with(path) || path.components().any(|c| c == Component::ParentDir) {
295        return false;
296    }
297
298    let Ok(inside) = path.strip_prefix(home) else {
299        return true;
300    };
301    let lower = PathBuf::from(inside.to_string_lossy().to_lowercase());
302    inside.components().count() > 1 && !NEVER_WRITABLE.iter().any(|dir| lower.starts_with(dir))
303}
304
305/// An absolute path, with `~/` as the home. A relative one names nothing a policy can hold
306fn expand(text: &str, home: &Path) -> Option<PathBuf> {
307    let path = match text.strip_prefix("~/") {
308        Some(rest) => home.join(rest),
309        None => PathBuf::from(text),
310    };
311    path.is_absolute().then_some(path)
312}
313
314/// Package manager settings in the home, hidden since they can hold a registry token: the file,
315/// the variable that points its tool at another one, and whether it holds one setting a line
316const PACKAGE_CONFIG: &[(&str, &str, bool)] = &[
317    (".npmrc", "NPM_CONFIG_USERCONFIG", true),
318    (".config/uv/uv.toml", "UV_CONFIG_FILE", false),
319    (".config/pip/pip.conf", "PIP_CONFIG_FILE", false),
320];
321
322/// What marks a line of package manager config as a credential
323const SECRET_WORDS: &[&str] = &["_auth", "password", "token", "secret", "key", "cert"];
324
325fn holds_secret(line: &str) -> bool {
326    let lower = line.to_lowercase();
327    // A URL with a user in it, as in https://user:pass@host
328    let user_in_url = lower.split("://").skip(1).any(|rest| {
329        rest.split(['/', ' ', '"', '\''])
330            .next()
331            .is_some_and(|host| host.contains('@'))
332    });
333    user_in_url || SECRET_WORDS.iter().any(|word| lower.contains(word))
334}
335
336/**
337 * Copies of the operator's package manager settings without their credentials, written under
338 * `temp`, as `(variable, file)` for the agent's environment, so an install inside the sandbox
339 * follows the operator's rules, such as a minimum package age. `.npmrc` holds one setting a line
340 * and loses its credential lines. A TOML or INI file that holds a credential is not copied at
341 * all, since a dropped line can break it
342 **/
343pub fn package_config(home: &Path, temp: &Path) -> Vec<(&'static str, PathBuf)> {
344    let dir = temp.join("config");
345    let mut found = Vec::new();
346
347    for (file, variable, by_line) in PACKAGE_CONFIG {
348        let Ok(text) = fs::read_to_string(home.join(file)) else {
349            continue;
350        };
351        if !by_line && text.lines().any(holds_secret) {
352            continue;
353        }
354
355        let kept: String = text
356            .lines()
357            .filter(|line| !holds_secret(line))
358            .flat_map(|line| [line, "\n"])
359            .collect();
360        let copy = dir.join(file.rsplit('/').next().unwrap_or(file));
361
362        if fs::create_dir_all(&dir).is_ok() && fs::write(&copy, kept).is_ok() {
363            found.push((*variable, copy));
364        }
365    }
366
367    found
368}
369
370/// What the policy of one run depends on
371struct Run {
372    work_dir: PathBuf,
373    git_dir: Option<PathBuf>,
374    common_dir: Option<PathBuf>,
375    /// The task's branch, `refs/heads/<branch>`, from orch's records
376    own_ref: Option<String>,
377    home: PathBuf,
378    orch_home: PathBuf,
379    projects: Vec<PathBuf>,
380    path_dirs: Vec<PathBuf>,
381    /// The run's own temp dir, where the agent may also connect to a socket
382    temp: PathBuf,
383    /// Paths the operator's config adds to the policy
384    extra: Extra,
385    internal: bool,
386    seatbelt: bool,
387}
388
389impl Run {
390    fn git_dirs(&self) -> impl Iterator<Item = &PathBuf> {
391        self.git_dir.iter().chain(&self.common_dir)
392    }
393}
394
395fn policy(run: &Run) -> Policy {
396    let mut p = Policy::default();
397    p.writable.push(run.work_dir.clone());
398    p.writable.extend(run.git_dirs().cloned());
399    p.writable.extend(home_writable(&run.home));
400    p.writable.push(run.temp.clone());
401    p.writable
402        .extend(claude_project_dir(&run.home, &run.work_dir));
403
404    // bwrap binds only a path that exists, Seatbelt lets the agent create a missing one
405    p.writable.extend(
406        run.extra
407            .write
408            .iter()
409            .filter(|path| run.seatbelt || path.exists())
410            .cloned(),
411    );
412
413    if run.seatbelt {
414        p.writable.push("/private/tmp".into());
415        let jobs: &[&str] = if run.internal { JOB_MACH_SERVICES } else { &[] };
416        p.mach_services = Access::Only(
417            known::BASIC_MACH_SERVICES
418                .iter()
419                .chain(&[KEYCHAIN])
420                .chain(TASK_MACH_SERVICES)
421                .chain(jobs)
422                .map(ToString::to_string)
423                .collect(),
424        );
425    } else {
426        // bwrap has no socket filter, so the dirs that hold sockets start empty instead
427        p.scratch = SCRATCH
428            .iter()
429            .map(PathBuf::from)
430            .filter(|d| d.is_dir())
431            .collect();
432    }
433
434    // The tmux server runs outside the sandbox, so its socket in /tmp must stay out of reach
435    let mut sockets = vec![run.work_dir.clone(), run.temp.clone()];
436    sockets.extend(
437        HOME_SOCKETS
438            .iter()
439            .map(|s| run.home.join(s))
440            .filter(|s| s.exists()),
441    );
442    sockets.extend(run.extra.sockets.iter().cloned());
443    p.unix_sockets = Access::Only(sockets);
444
445    if let Some(common) = &run.common_dir {
446        git_rules(
447            common,
448            run.git_dir.as_ref(),
449            run.own_ref.as_deref(),
450            &mut p.read_only,
451        );
452
453        if run.git_dir.as_ref().is_some_and(|g| g != common) {
454            p.read_only.push(run.work_dir.join(".git"));
455        }
456    }
457
458    p.read_only.extend(home_git_dirs(&run.home));
459
460    // /private/tmp stays writable, but the agent must not delete or replace these sockets.
461    // bwrap hides those in a scratch dir, and binding one back would expose it
462    let hidden = p.scratch.clone();
463    p.read_only.extend(
464        socket_dirs(&run.temp)
465            .into_iter()
466            .filter(|d| !hidden.iter().any(|s| d.starts_with(s))),
467    );
468
469    p.read_only.push(run.work_dir.join(".orch.yml"));
470    p.read_only.extend(
471        AGENT_CONFIG
472            .iter()
473            .chain(HOME_EXEC_CONFIG)
474            .chain(HOME_TRUSTED_STATE)
475            .map(|path| run.home.join(path)),
476    );
477    // A tool on PATH inside the home, such as ~/.cargo/bin, runs later as the operator
478    p.read_only.extend(
479        run.path_dirs
480            .iter()
481            .filter(|d| d.starts_with(&run.home))
482            .cloned(),
483    );
484
485    let mut keep: Vec<PathBuf> = vec![run.work_dir.clone(), run.temp.clone()];
486    keep.extend(run.git_dirs().cloned());
487
488    if run.internal {
489        keep.extend(["orch.db", "orch.db-wal", "orch.db-shm"].map(|f| run.orch_home.join(f)));
490    }
491    // The daemon's loopback write endpoint takes this token, so reading it is a write to the store
492    let write_token = run.orch_home.join("state/cluster.port");
493
494    read_only_around(&run.orch_home, &keep, &mut p.read_only);
495
496    for project in &run.projects {
497        read_only_around(project, &keep, &mut p.read_only);
498    }
499
500    // The crate's list hides cargo's config too, which holds build settings agents need
501    p.hidden = known::credentials(&run.home)
502        .into_iter()
503        .filter(|path| {
504            ![".cargo/config", ".cargo/config.toml"]
505                .map(|c| run.home.join(c))
506                .contains(path)
507        })
508        .filter(|path| !run.extra.read.iter().any(|open| path.starts_with(open)))
509        .collect();
510    p.hidden.push(run.home.join(".gnupg"));
511    p.hidden
512        .extend(OPENCODE_SERVICE.iter().map(|f| run.home.join(f)));
513
514    // The web UI's token drives the daemon's API, config edits and plan imports among it
515    p.hidden.push(run.orch_home.join(UI_TOKEN));
516
517    if !run.internal {
518        p.hidden.push(write_token);
519    }
520
521    p.own_signals = true;
522
523    // launchctl and setuid binaries start processes outside the sandbox
524    if run.seatbelt {
525        p.apple_events = false;
526        p.no_exec.push(known::LAUNCHCTL.into());
527        p.no_exec.extend(known::setuid_binaries().iter().cloned());
528    }
529
530    p
531}
532
533/// The web UI's port and token. No agent may read it, it would drive the daemon through the UI's API
534const UI_TOKEN: &str = "state/ui.port";
535
536/// The agent's own login and settings, which it reads to start. The Security framework reads the
537/// login keychain in the calling process, and its access rules still give the agent only its own item
538const CHAT_AGENT_HOME: &[&str] = &[".claude", ".claude.json", "Library/Keychains"];
539
540/// Where agents keep sessions and caches, which the control chat writes to resume a conversation
541const AGENT_STATE: &[&str] = &[
542    ".claude/projects",
543    ".claude/todos",
544    ".claude/shell-snapshots",
545    ".claude/statsig",
546    ".codex",
547    ".local/share/opencode",
548    ".local/state/opencode",
549];
550
551/// Other agents' settings, read at start
552const AGENT_CONFIG_READ: &[&str] = &[".codex", ".config/opencode", ".grok"];
553
554/// What a chat agent may touch, as opposed to a task agent's [`policy`]
555struct ChatRun {
556    home: PathBuf,
557    orch_home: PathBuf,
558    /// The project a project chat reads, none for the control chat
559    project: Option<PathBuf>,
560    temp: PathBuf,
561    path_dirs: Vec<PathBuf>,
562    seatbelt: bool,
563    /// The control chat keeps agent sessions and acts through orch, so it writes session dirs and
564    /// reads the daemon's write token. A project chat does neither
565    control: bool,
566}
567
568/// The sandbox prefix for a project chat agent. It reads the project and orch's store and config,
569/// writes only its temp dir, and cannot read the rest of the home or any credential
570pub fn chat_argv(project: &Path, temp: &Path) -> anyhow::Result<Vec<OsString>> {
571    chat_sandbox(Some(project), temp, false)
572}
573
574/**
575 * The sandbox prefix for the control chat, which Telegram and the other channels reach. It reads
576 * orch's home and acts through orch, and cannot read the rest of the home or any credential.
577 * Inside another Seatbelt sandbox, which cannot nest, it runs in that one
578 **/
579pub fn control_argv(temp: &Path) -> anyhow::Result<Vec<OsString>> {
580    match chat_sandbox(None, temp, true) {
581        Err(e)
582            if e.downcast_ref::<sandbox_jail::Error>()
583                .is_some_and(|e| matches!(e, sandbox_jail::Error::Nested)) =>
584        {
585            tracing::info!("already inside a sandbox, the control chat runs in it");
586            Ok(Vec::new())
587        }
588        other => other,
589    }
590}
591
592fn chat_sandbox(
593    project: Option<&Path>,
594    temp: &Path,
595    control: bool,
596) -> anyhow::Result<Vec<OsString>> {
597    let backend = Backend::detect()?;
598    let home = env::var_os("HOME")
599        .map(PathBuf::from)
600        .ok_or_else(|| anyhow::anyhow!("HOME is not set"))?;
601    let run = ChatRun {
602        home,
603        orch_home: home::orch_home()?,
604        project: project.map(Path::to_path_buf),
605        temp: temp.to_path_buf(),
606        path_dirs: env::var_os("PATH")
607            .map(|p| env::split_paths(&p).collect())
608            .unwrap_or_default(),
609        seatbelt: matches!(backend, Backend::Seatbelt),
610        control,
611    };
612    Ok(Sandbox::new(backend, chat_policy(&run))?.argv().to_vec())
613}
614
615fn chat_policy(run: &ChatRun) -> Policy {
616    let mut p = Policy::default();
617    p.writable.push(run.temp.clone());
618    // `orch task list` opens the store, and SQLite writes its -wal and -shm files even to read
619    p.writable.extend(
620        ["orch.db", "orch.db-wal", "orch.db-shm"]
621            .map(|f| run.orch_home.join(f))
622            .into_iter()
623            .filter(|f| f.exists()),
624    );
625
626    if run.seatbelt {
627        p.writable.push("/private/tmp".into());
628        p.mach_services = Access::Only(
629            known::BASIC_MACH_SERVICES
630                .iter()
631                .chain(&[KEYCHAIN])
632                .map(ToString::to_string)
633                .collect(),
634        );
635    } else {
636        p.scratch = SCRATCH
637            .iter()
638            .map(PathBuf::from)
639            .filter(|d| d.is_dir())
640            .collect();
641    }
642
643    p.unix_sockets = Access::Only(vec![run.temp.clone()]);
644
645    if run.control {
646        p.writable.extend(
647            AGENT_STATE
648                .iter()
649                .map(|d| run.home.join(d))
650                .filter(|d| d.is_dir()),
651        );
652        // Codex writes its state beside its settings, which stay as the owner wrote them
653        p.read_only
654            .extend(AGENT_CONFIG.iter().map(|path| run.home.join(path)));
655    }
656
657    // The tmux server and launchd's sockets sit in the writable /private/tmp, and an agent that
658    // deleted or replaced one would end every session or stand in for the ssh agent
659    p.read_only.extend(socket_dirs(&run.temp));
660
661    p.unreadable.push(run.home.clone());
662    p.readable.extend(run.project.iter().cloned());
663    p.readable.push(run.orch_home.clone());
664    p.readable
665        .extend(AGENT_CONFIG_READ.iter().map(|f| run.home.join(f)));
666    p.readable
667        .extend(CHAT_AGENT_HOME.iter().map(|f| run.home.join(f)));
668    p.readable.extend(
669        run.path_dirs
670            .iter()
671            .filter(|d| d.starts_with(&run.home))
672            .cloned(),
673    );
674
675    p.hidden = known::credentials(&run.home);
676    p.hidden.push(run.home.join(".gnupg"));
677    p.hidden.push(run.orch_home.join(UI_TOKEN));
678    // The daemon's loopback write endpoint takes this token, and a project chat only reads
679    if !run.control {
680        p.hidden.push(run.orch_home.join("state/cluster.port"));
681    }
682
683    p.own_signals = true;
684    if run.seatbelt {
685        p.apple_events = false;
686        p.no_exec.push(known::LAUNCHCTL.into());
687        p.no_exec.extend(known::setuid_binaries().iter().cloned());
688    }
689
690    p
691}
692
693/// How many levels below a writable home dir are searched for repositories
694const GIT_SCAN_DEPTH: usize = 4;
695
696/// How long a scan of the home for repositories is reused. It takes seconds and every run needs it
697/// twice in a row. Kept short, since a repository cloned after the scan is not in it
698const GIT_SCAN_TTL: Duration = Duration::from_secs(60);
699
700static GIT_SCAN: Mutex<Option<(Instant, PathBuf, Vec<PathBuf>)>> = Mutex::new(None);
701
702/// The hooks and config of every repository under the home's writable dirs, from a recent scan
703fn home_git_dirs(home: &Path) -> Vec<PathBuf> {
704    let mut last = GIT_SCAN.lock().unwrap_or_else(PoisonError::into_inner);
705
706    if let Some((at, of, found)) = last.as_ref()
707        && of == home
708        && at.elapsed() < GIT_SCAN_TTL
709    {
710        return found.clone();
711    }
712
713    let mut found = Vec::new();
714
715    for dir in home_writable(home) {
716        find_git_dirs(&dir, GIT_SCAN_DEPTH, &mut found);
717    }
718
719    *last = Some((Instant::now(), home.to_path_buf(), found.clone()));
720    found
721}
722
723// Hooks and config of a repository orch does not know run as the operator on its next git command
724fn find_git_dirs(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) {
725    let git = dir.join(".git");
726
727    if git.is_dir() {
728        out.extend(["hooks", "config", "info", "modules"].map(|f| git.join(f)));
729    }
730
731    if depth == 0 {
732        return;
733    }
734
735    for entry in fs::read_dir(dir).into_iter().flatten().flatten() {
736        let name = entry.file_name();
737
738        if entry.file_type().is_ok_and(|t| t.is_dir()) && name != ".git" && name != "node_modules" {
739            find_git_dirs(&entry.path(), depth - 1, out);
740        }
741    }
742}
743
744/// The tmux and launchd socket dirs in the shared temp dirs, which the tmux server and the
745/// ssh-agent keep running outside the sandbox
746fn socket_dirs(temp: &Path) -> Vec<PathBuf> {
747    let mut roots = vec![PathBuf::from("/private/tmp"), PathBuf::from("/tmp")];
748    roots.extend(env::var_os("TMUX_TMPDIR").map(PathBuf::from));
749    roots.push(temp.to_path_buf());
750
751    roots
752        .iter()
753        .filter_map(|r| fs::read_dir(r).ok())
754        .flatten()
755        .flatten()
756        .filter(|e| {
757            let name = e.file_name();
758            let name = name.to_string_lossy();
759            name.starts_with("tmux-") || name.starts_with("com.apple.launchd.")
760        })
761        .map(|e| e.path())
762        .collect()
763}
764
765/**
766 * Where Claude Code keeps the session of a run in this worktree: its transcript, and the tool
767 * output too long for the context. Without it a long command output is cut off with no notice.
768 * The dir is named after the cwd with every character but letters and digits as `-`
769 **/
770fn claude_project_dir(home: &Path, work_dir: &Path) -> Option<PathBuf> {
771    let projects = home.join(".claude/projects");
772    let name: String = work_dir
773        .to_string_lossy()
774        .chars()
775        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
776        .collect();
777    let dir = projects.join(name);
778
779    // bwrap binds only a path that exists
780    (projects.is_dir() && fs::create_dir_all(&dir).is_ok()).then_some(dir)
781}
782
783/// The home's writable parts: its top-level dirs but [`HOME_READ_ONLY`], and [`HOME_WRITABLE`]
784/// inside those. The home itself stays read-only, so no new dotfile appears at its top
785fn home_writable(home: &Path) -> Vec<PathBuf> {
786    let mut dirs: Vec<PathBuf> = fs::read_dir(home)
787        .into_iter()
788        .flatten()
789        .flatten()
790        .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
791        .filter(|e| !HOME_READ_ONLY.contains(&e.file_name().to_string_lossy().as_ref()))
792        .map(|e| e.path())
793        .collect();
794    dirs.extend(
795        HOME_WRITABLE
796            .iter()
797            .map(|d| home.join(d))
798            .filter(|d| d.is_dir()),
799    );
800    dirs
801}
802
803/**
804 * The git common dir is writable for objects, the task's branch, remote refs and the task's own
805 * worktree dir, and read-only around those: hooks and config run the next time the operator runs
806 * git, and another branch is the operator's work. Paths git would pick up when they appear are
807 * read-only even when missing, and so is a loose ref for a branch only `packed-refs` holds, since
808 * it would win over the packed one
809 **/
810fn git_rules(
811    common: &Path,
812    git_dir: Option<&PathBuf>,
813    own_ref: Option<&str>,
814    out: &mut Vec<PathBuf>,
815) {
816    out.extend(
817        [
818            "hooks",
819            "config",
820            "info",
821            "modules",
822            "packed-refs",
823            "refs/tags",
824            "commondir",
825            "gitdir",
826            "config.worktree",
827        ]
828        .map(|d| common.join(d)),
829    );
830    let own: Vec<PathBuf> = own_ref
831        .map(|r| vec![common.join(r), common.join("logs").join(r)])
832        .unwrap_or_default();
833
834    match git_dir {
835        Some(dir) if dir != common => {
836            let mut keep = vec![
837                common.join("objects"),
838                common.join("refs/remotes"),
839                common.join("logs/refs/remotes"),
840                dir.clone(),
841            ];
842            keep.extend(own.iter().cloned());
843            read_only_around(common, &keep, out);
844            // HEAD stays writable, a rebase detaches it. Other branches stay read-only whatever it
845            // names, and orch pushes the task's branch by name
846            out.extend(["commondir", "gitdir", "config.worktree"].map(|f| dir.join(f)));
847        }
848        // The worktree is the main checkout, so its index and HEAD live in the common dir
849        _ => read_only_around(&common.join("refs/heads"), &own, out),
850    }
851
852    let packed = fs::read_to_string(common.join("packed-refs")).unwrap_or_default();
853    for name in packed
854        .lines()
855        .filter_map(|l| l.split_once(' ').map(|(_, r)| r))
856    {
857        let path = common.join(name);
858
859        if name.starts_with("refs/heads/") && !own.contains(&path) && !path.exists() {
860            out.push(path);
861        }
862    }
863}
864
865/**
866 * Every entry of `dir` read-only but the paths in `keep`. An entry that holds a kept path is
867 * walked instead, so `~/.orch` stays read-only around the task's own worktree, and a main checkout
868 * around its `.git`. A missing `dir` adds nothing
869 **/
870fn read_only_around(dir: &Path, keep: &[PathBuf], out: &mut Vec<PathBuf>) {
871    let Ok(entries) = fs::read_dir(dir) else {
872        return;
873    };
874
875    for entry in entries.flatten() {
876        let path = entry.path();
877
878        if keep.iter().any(|k| path.starts_with(k)) {
879            continue;
880        }
881
882        let holds_kept = keep.iter().any(|k| k.starts_with(&path));
883        let is_dir = entry.file_type().is_ok_and(|t| t.is_dir());
884
885        if holds_kept && is_dir {
886            read_only_around(&path, keep, out);
887        } else if !holds_kept {
888            out.push(path);
889        }
890    }
891}
892
893/// Run `git rev-parse <arg>` from `work_dir` and canonicalize the
894/// result. Returns `Ok(None)` when git is not available or the command fails.
895pub(crate) async fn resolve_git_dir_arg(
896    work_dir: &Path,
897    arg: &str,
898) -> anyhow::Result<Option<PathBuf>> {
899    let output = Command::new("git")
900        .args(["rev-parse", arg])
901        .current_dir(work_dir)
902        .output()
903        .await?;
904
905    if !output.status.success() {
906        return Ok(None);
907    }
908
909    let raw = String::from_utf8_lossy(&output.stdout).trim().to_string();
910    if raw.is_empty() {
911        return Ok(None);
912    }
913
914    // The path may be relative to work_dir; canonicalize to absolute.
915    let candidate = if Path::new(&raw).is_absolute() {
916        PathBuf::from(&raw)
917    } else {
918        work_dir.join(&raw)
919    };
920
921    let canonical = async_fs::canonicalize(&candidate)
922        .await
923        .unwrap_or(candidate);
924    Ok(Some(canonical))
925}
926
927#[cfg(test)]
928mod tests {
929    use super::*;
930    #[cfg(any(target_os = "macos", target_os = "linux"))]
931    use serial_test::serial;
932    use std::fs;
933    #[cfg(target_os = "macos")]
934    use std::os::unix::net::UnixListener;
935    #[cfg(any(target_os = "macos", target_os = "linux"))]
936    use std::process::Command;
937    #[cfg(target_os = "macos")]
938    use std::thread;
939
940    #[test]
941    fn only_an_explicit_false_turns_the_sandbox_off() {
942        assert!(is_on(None));
943        assert!(is_on(Some("os".into())));
944        assert!(is_on(Some("flase".into())));
945        assert!(!is_on(Some("false".into())));
946        assert!(!is_on(Some(" false\n".into())));
947    }
948
949    #[tokio::test]
950    async fn argv_error_is_tagged_so_spawn_blocks_the_task() {
951        let inv = Scope {
952            work_dir: Path::new("/nonexistent/work"),
953            main_project_dir: Path::new("/nonexistent/main"),
954            branch: "",
955            task_id: "t",
956        };
957        let err = argv(&inv, Path::new("/tmp/orch-test-run"))
958            .await
959            .expect_err("no checkout, so no sandbox");
960        assert!(err.downcast_ref::<SandboxFailed>().is_some());
961        assert!(err.to_string().starts_with("the OS sandbox cannot start: "));
962    }
963
964    // The preflight passes a temp dir no one made yet, which bwrap refuses to bind
965    #[cfg(any(target_os = "macos", target_os = "linux"))]
966    #[tokio::test]
967    #[serial(orch_home)]
968    async fn argv_makes_the_run_temp_dir_before_the_policy_binds_it() {
969        if Backend::detect().is_err() {
970            eprintln!("skipped: no OS sandbox starts here");
971            return;
972        }
973        let root = tempfile::tempdir().unwrap();
974        let r = root.path().canonicalize().unwrap();
975        let (home, main) = (r.join("home"), r.join("home/proj"));
976        let work = home.join(".orch/worktrees/proj/feat");
977        fs::create_dir_all(&main).unwrap();
978        let git = |dir: &Path, args: &[&str]| {
979            let out = Command::new("git")
980                .args(["-c", "user.name=t", "-c", "user.email=t@t"])
981                .args(args)
982                .current_dir(dir)
983                .output()
984                .unwrap();
985            assert!(
986                out.status.success(),
987                "{}",
988                String::from_utf8_lossy(&out.stderr)
989            );
990        };
991        git(&main, &["init", "-q", "-b", "main"]);
992        git(&main, &["commit", "-q", "--allow-empty", "-m", "init"]);
993        git(
994            &main,
995            &[
996                "worktree",
997                "add",
998                "-q",
999                "-b",
1000                "feat",
1001                work.to_str().unwrap(),
1002            ],
1003        );
1004        let previous = (env::var_os("HOME"), env::var_os("ORCH_HOME"));
1005        // SAFETY: nextest runs each test in its own process, and serial(orch_home) orders the rest
1006        unsafe { env::set_var("HOME", &home) };
1007        // SAFETY: as above
1008        unsafe { env::set_var("ORCH_HOME", home.join(".orch")) };
1009        config::clear_test_cache();
1010        let inv = Scope {
1011            work_dir: &work,
1012            main_project_dir: &main,
1013            branch: "feat",
1014            task_id: "t",
1015        };
1016        let temp = r.join("preflight");
1017        let built = argv(&inv, &temp).await;
1018        for (key, value) in [("HOME", previous.0), ("ORCH_HOME", previous.1)] {
1019            match value {
1020                // SAFETY: as above
1021                Some(v) => unsafe { env::set_var(key, v) },
1022                // SAFETY: as above
1023                None => unsafe { env::remove_var(key) },
1024            }
1025        }
1026        config::clear_test_cache();
1027        assert!(!built.unwrap().is_empty());
1028        assert!(temp.is_dir());
1029    }
1030
1031    /// A home with an orch home inside, two worktrees and a main checkout, and the run of one task
1032    fn fixture(internal: bool) -> (tempfile::TempDir, Run) {
1033        let root = tempfile::tempdir().unwrap();
1034        let r = root.path().canonicalize().unwrap();
1035        let (home, orch) = (r.join("home"), r.join("home/.orch"));
1036        for dir in [
1037            "home/.orch/worktrees/proj/mine",
1038            "home/.orch/worktrees/proj/other",
1039            "home/.orch/state",
1040            "home/proj/.git/worktrees/mine",
1041            "home/proj/.git/refs/heads/feat",
1042            "home/proj/src",
1043            "home/proj/.git/objects",
1044            "home/proj/.git/worktrees/other",
1045            "home/.config/nvim",
1046            "home/.claude",
1047            "home/.cargo/bin",
1048            "home/Library/Caches",
1049            "home/Library/LaunchAgents",
1050            "tmp",
1051        ] {
1052            fs::create_dir_all(r.join(dir)).unwrap();
1053        }
1054        for file in [
1055            "home/.orch/config.yml",
1056            "home/.orch/orch.db",
1057            "home/proj/README.md",
1058            "home/proj/.git/refs/heads/main",
1059            "home/proj/.git/refs/heads/feat/mine",
1060            "home/proj/.git/worktrees/mine/HEAD",
1061            "home/proj/.git/worktrees/mine/gitdir",
1062            "home/.zshrc",
1063            "home/.claude.json",
1064        ] {
1065            fs::write(r.join(file), "").unwrap();
1066        }
1067        fs::write(
1068            r.join("home/proj/.git/packed-refs"),
1069            "# pack-refs with: peeled\nabc refs/heads/release\n",
1070        )
1071        .unwrap();
1072
1073        let run = Run {
1074            work_dir: orch.join("worktrees/proj/mine"),
1075            git_dir: Some(home.join("proj/.git/worktrees/mine")),
1076            common_dir: Some(home.join("proj/.git")),
1077            own_ref: Some("refs/heads/feat/mine".into()),
1078            home: home.clone(),
1079            orch_home: orch,
1080            projects: vec![home.join("proj")],
1081            path_dirs: vec![home.join(".cargo/bin"), "/usr/bin".into()],
1082            temp: r.join("tmp"),
1083            extra: Extra::default(),
1084            internal,
1085            seatbelt: false,
1086        };
1087        (root, run)
1088    }
1089
1090    fn chat_fixture() -> ChatRun {
1091        ChatRun {
1092            home: PathBuf::from("/home/u"),
1093            orch_home: PathBuf::from("/home/u/.orch"),
1094            project: Some(PathBuf::from("/home/u/code/app")),
1095            temp: PathBuf::from("/tmp/chat"),
1096            path_dirs: vec![
1097                PathBuf::from("/home/u/.cargo/bin"),
1098                PathBuf::from("/usr/bin"),
1099            ],
1100            seatbelt: true,
1101            control: false,
1102        }
1103    }
1104
1105    #[test]
1106    fn no_task_can_read_the_web_ui_token() {
1107        for internal in [false, true] {
1108            let (_root, run) = fixture(internal);
1109            let token = run.orch_home.join("state/ui.port");
1110            assert!(policy(&run).hidden.contains(&token), "internal: {internal}");
1111        }
1112    }
1113
1114    #[test]
1115    fn no_chat_can_read_the_web_ui_token() {
1116        let token = PathBuf::from("/home/u/.orch/state/ui.port");
1117        let mut run = chat_fixture();
1118        assert!(
1119            chat_policy(&run).hidden.contains(&token),
1120            "the project chat"
1121        );
1122        run.project = None;
1123        run.control = true;
1124        assert!(
1125            chat_policy(&run).hidden.contains(&token),
1126            "the control chat"
1127        );
1128    }
1129
1130    #[test]
1131    fn the_control_chat_reads_no_project_and_may_act_through_orch() {
1132        let mut run = chat_fixture();
1133        run.project = None;
1134        run.control = true;
1135        let p = chat_policy(&run);
1136        assert!(
1137            !p.readable.iter().any(|r| r.starts_with("/home/u/code")),
1138            "no project folder"
1139        );
1140        assert!(
1141            !p.hidden
1142                .contains(&PathBuf::from("/home/u/.orch/state/cluster.port")),
1143            "it acts through the daemon"
1144        );
1145        assert!(
1146            p.hidden.contains(&PathBuf::from("/home/u/.ssh")),
1147            "credentials stay hidden"
1148        );
1149        assert!(
1150            p.unreadable.contains(&PathBuf::from("/home/u")),
1151            "the home stays closed"
1152        );
1153    }
1154
1155    #[test]
1156    fn a_chat_writes_only_its_temp_dir() {
1157        let p = chat_policy(&chat_fixture());
1158        assert!(
1159            p.writable.contains(&PathBuf::from("/tmp/chat")),
1160            "its temp dir"
1161        );
1162        assert!(
1163            !p.writable.iter().any(|w| w.starts_with("/home/u/code")),
1164            "never the project"
1165        );
1166    }
1167
1168    #[test]
1169    fn a_chat_reads_the_project_but_not_the_rest_of_the_home() {
1170        let p = chat_policy(&chat_fixture());
1171        assert!(
1172            p.unreadable.contains(&PathBuf::from("/home/u")),
1173            "the home is closed"
1174        );
1175        assert!(
1176            p.readable.contains(&PathBuf::from("/home/u/code/app")),
1177            "the project is open"
1178        );
1179        assert!(
1180            p.readable.contains(&PathBuf::from("/home/u/.claude")),
1181            "the agent can log in"
1182        );
1183        assert!(
1184            p.readable.contains(&PathBuf::from("/home/u/.cargo/bin")),
1185            "tools on PATH"
1186        );
1187    }
1188
1189    #[test]
1190    fn a_chat_cannot_see_credentials_or_the_write_token() {
1191        let p = chat_policy(&chat_fixture());
1192        assert!(
1193            p.hidden.contains(&PathBuf::from("/home/u/.ssh")),
1194            "ssh keys"
1195        );
1196        assert!(
1197            p.hidden.contains(&PathBuf::from("/home/u/.config/gh")),
1198            "the gh token"
1199        );
1200        assert!(
1201            p.hidden
1202                .contains(&PathBuf::from("/home/u/.orch/state/cluster.port")),
1203            "the daemon's write token"
1204        );
1205    }
1206
1207    #[test]
1208    fn orch_home_is_read_only_around_the_task_worktree() {
1209        let (_root, run) = fixture(false);
1210        let p = policy(&run);
1211        let o = &run.orch_home;
1212        for path in [
1213            o.join("config.yml"),
1214            o.join("state"),
1215            o.join("orch.db"),
1216            o.join("worktrees/proj/other"),
1217        ] {
1218            assert!(
1219                p.read_only.contains(&path),
1220                "{} not read-only",
1221                path.display()
1222            );
1223        }
1224        for path in [
1225            o.join("worktrees"),
1226            o.join("worktrees/proj"),
1227            run.work_dir.clone(),
1228        ] {
1229            assert!(!p.read_only.contains(&path), "{} read-only", path.display());
1230        }
1231        assert!(p.writable.contains(&run.work_dir));
1232    }
1233
1234    #[test]
1235    fn the_main_checkout_is_read_only_but_its_git_dir() {
1236        let (_root, run) = fixture(false);
1237        let p = policy(&run);
1238        let proj = run.home.join("proj");
1239        assert!(p.read_only.contains(&proj.join("src")));
1240        assert!(p.read_only.contains(&proj.join("README.md")));
1241        assert!(!p.read_only.contains(&proj.join(".git")));
1242        assert!(p.read_only.contains(&proj.join(".git/hooks")));
1243        assert!(p.read_only.contains(&proj.join(".git/config")));
1244    }
1245
1246    #[test]
1247    fn only_the_task_branch_is_writable_in_the_git_dir() {
1248        let (_root, run) = fixture(false);
1249        let p = policy(&run);
1250        let git = run.home.join("proj/.git");
1251        for path in [
1252            "refs/heads/main",
1253            "refs/heads/release",
1254            "packed-refs",
1255            "hooks",
1256            "config",
1257            "commondir",
1258            "gitdir",
1259            "config.worktree",
1260        ] {
1261            assert!(
1262                p.read_only.contains(&git.join(path)),
1263                "{path} not read-only"
1264            );
1265        }
1266        assert!(!p.read_only.contains(&git.join("refs/heads/feat/mine")));
1267        assert!(!p.read_only.contains(&git.join("refs/heads/feat")));
1268        assert!(!p.read_only.contains(&git.join("objects")));
1269        assert!(p.read_only.contains(&git.join("worktrees/other")));
1270        assert!(p.read_only.contains(&git.join("worktrees/mine/gitdir")));
1271        assert!(!p.read_only.contains(&git.join("worktrees/mine/HEAD")));
1272        assert!(p.read_only.contains(&run.work_dir.join(".git")));
1273        assert!(p.writable.contains(&git));
1274    }
1275
1276    #[test]
1277    fn hooks_and_config_of_an_unknown_repository_are_read_only() {
1278        let (_root, run) = fixture(false);
1279        let git = run.home.join("code/deep/other/.git");
1280        fs::create_dir_all(&git).unwrap();
1281        let p = policy(&run);
1282        assert!(p.read_only.contains(&git.join("hooks")));
1283        assert!(p.read_only.contains(&git.join("config")));
1284        assert!(!p.read_only.contains(&git));
1285    }
1286
1287    #[test]
1288    fn only_the_home_s_cache_dirs_are_writable() {
1289        let (_root, run) = fixture(false);
1290        let p = policy(&run);
1291        let h = &run.home;
1292        for path in [".cargo", ".orch", "Library/Caches"] {
1293            assert!(p.writable.contains(&h.join(path)), "{path} not writable");
1294        }
1295        for path in ["", ".config", ".claude", "Library"] {
1296            assert!(!p.writable.contains(&h.join(path)), "{path:?} writable");
1297        }
1298        assert!(p.read_only.contains(&h.join(".cargo/bin")));
1299        assert!(!p.read_only.contains(&PathBuf::from("/usr/bin")));
1300    }
1301
1302    #[test]
1303    fn no_socket_outside_the_worktree_and_no_launch_services() {
1304        let (root, mut run) = fixture(false);
1305        run.seatbelt = true;
1306        let p = policy(&run);
1307        let Access::Only(sockets) = &p.unix_sockets else {
1308            panic!("every unix socket is reachable");
1309        };
1310        assert_eq!(sockets, &vec![run.work_dir.clone(), run.temp.clone()]);
1311
1312        // Only the broker's socket, and the store beside it is not the agent's to write
1313        fs::create_dir_all(run.home.join(".passbox")).unwrap();
1314        fs::write(run.home.join(".passbox/broker.sock"), "").unwrap();
1315        fs::write(run.home.join(".passbox/ssh-agent.sock"), "").unwrap();
1316        let p = policy(&run);
1317        let Access::Only(sockets) = &p.unix_sockets else {
1318            panic!("every unix socket is reachable");
1319        };
1320        assert!(sockets.contains(&run.home.join(".passbox/broker.sock")));
1321        assert!(!sockets.contains(&run.home.join(".passbox/ssh-agent.sock")));
1322        assert!(!p.writable.contains(&run.home.join(".passbox")));
1323        // The fixture sits under /tmp when TMPDIR does
1324        let fixture_dir = root.path().canonicalize().unwrap();
1325        assert!(!sockets.iter().any(|s| {
1326            !s.starts_with(&fixture_dir) && (s.starts_with("/tmp") || s.starts_with("/private/tmp"))
1327        }));
1328        let Access::Only(mach) = &p.mach_services else {
1329            panic!("every Mach service is reachable");
1330        };
1331        assert!(mach.iter().any(|s| s == KEYCHAIN));
1332        assert!(!mach.iter().any(|s| s.contains("launchservices")));
1333        assert!(!mach.iter().any(|s| s.contains("CalendarAgent")));
1334
1335        let (_root, mut job) = fixture(true);
1336        job.seatbelt = true;
1337        let Access::Only(mach) = policy(&job).mach_services else {
1338            panic!("every Mach service is reachable");
1339        };
1340        assert!(mach.iter().any(|s| s == "com.apple.CalendarAgent"));
1341    }
1342
1343    #[test]
1344    fn code_running_config_in_a_writable_home_dir_is_read_only() {
1345        let (_root, run) = fixture(false);
1346        let p = policy(&run);
1347        assert!(p.writable.contains(&run.home.join(".cargo")));
1348        assert!(p.read_only.contains(&run.home.join(".cargo/config.toml")));
1349    }
1350
1351    #[test]
1352    fn a_git_dir_the_agent_could_have_pointed_elsewhere_is_refused() {
1353        let (_root, run) = fixture(false);
1354        let (work, main) = (&run.work_dir, run.home.join("proj"));
1355        let (git, common) = (
1356            run.git_dir.clone().unwrap(),
1357            run.common_dir.clone().unwrap(),
1358        );
1359
1360        fs::write(
1361            git.join("gitdir"),
1362            format!("{}\n", work.join(".git").display()),
1363        )
1364        .unwrap();
1365        assert!(check_git_dirs(work, &main, Some(&git), Some(&common)).is_ok());
1366
1367        // Pointed at the common dir, which only the main checkout uses
1368        assert!(check_git_dirs(work, &main, Some(&common), Some(&common)).is_err());
1369        assert!(check_git_dirs(&main, &main, Some(&common), Some(&common)).is_ok());
1370        // Another worktree's git dir, or none at all
1371        let other = common.join("worktrees/other");
1372        fs::write(other.join("gitdir"), "/elsewhere/.git\n").unwrap();
1373        assert!(check_git_dirs(work, &main, Some(&other), Some(&common)).is_err());
1374        assert!(check_git_dirs(work, &main, Some(&run.home), Some(&common)).is_err());
1375        assert!(check_git_dirs(work, &main, None, Some(&common)).is_err());
1376    }
1377
1378    #[test]
1379    fn the_config_adds_paths_and_lifts_no_read_only_rule() {
1380        let (_root, mut run) = fixture(false);
1381        let h = run.home.clone();
1382        fs::create_dir_all(h.join(".config/solana/install")).unwrap();
1383        run.extra = Extra {
1384            write: vec![h.join(".config/solana/install")],
1385            read: vec![h.join(".aws")],
1386            sockets: vec![h.join(".docker/run")],
1387        };
1388        let p = policy(&run);
1389        assert!(p.writable.contains(&h.join(".config/solana/install")));
1390        assert!(!p.hidden.contains(&h.join(".aws")));
1391        assert!(p.hidden.contains(&h.join(".ssh")));
1392        let Access::Only(sockets) = &p.unix_sockets else {
1393            panic!("every unix socket is reachable");
1394        };
1395        assert!(sockets.contains(&h.join(".docker/run")));
1396        assert!(p.read_only.contains(&h.join(".cargo/bin")));
1397    }
1398
1399    #[test]
1400    fn a_wide_write_entry_and_one_on_keys_or_startup_files_is_refused() {
1401        let home = Path::new("/home/u");
1402        for allowed in [
1403            "/home/u/.config/solana/install",
1404            "/home/u/Library/Developer/Xcode",
1405            "/opt/tool/cache",
1406        ] {
1407            assert!(may_write(Path::new(allowed), home), "{allowed}");
1408        }
1409        for refused in [
1410            "/",
1411            "/home",
1412            "/home/u",
1413            "/home/u/.zshrc",
1414            "/home/u/.config",
1415            "/home/u/.ssh/authorized_keys",
1416            "/home/u/.claude/settings.json",
1417            "/home/u/.local/bin/tool",
1418            "/home/u/Library/LaunchAgents/x.plist",
1419            "/home/u/.orch/config.yml",
1420            "/home/u/.config/../.ssh/x",
1421            "/home/u/.SSH/authorized_keys",
1422            "/home/u/.config/git/config",
1423        ] {
1424            assert!(!may_write(Path::new(refused), home), "{refused}");
1425        }
1426    }
1427
1428    #[test]
1429    fn a_config_path_is_absolute_or_under_the_home() {
1430        let home = Path::new("/home/u");
1431        assert_eq!(expand("~/.pypirc", home), Some("/home/u/.pypirc".into()));
1432        assert_eq!(expand("/opt/tool", home), Some("/opt/tool".into()));
1433        assert_eq!(expand("relative/path", home), None);
1434        assert_eq!(expand("~other/x", home), None);
1435    }
1436
1437    #[test]
1438    fn package_settings_reach_the_agent_without_their_credentials() {
1439        let (root, run) = fixture(false);
1440        let h = &run.home;
1441        fs::write(
1442            h.join(".npmrc"),
1443            "min-release-age=7\n//registry.npmjs.org/:_authToken=npm_abc\nregistry=https://user:pw@r.example/\nsave-exact=true\n",
1444        )
1445        .unwrap();
1446        fs::create_dir_all(h.join(".config/uv")).unwrap();
1447        fs::write(h.join(".config/uv/uv.toml"), "exclude-newer = \"7 days\"\n").unwrap();
1448        fs::create_dir_all(h.join(".config/pip")).unwrap();
1449        fs::write(
1450            h.join(".config/pip/pip.conf"),
1451            "[global]\nindex-url = https://u:p@pypi.example/simple\n",
1452        )
1453        .unwrap();
1454
1455        let temp = root.path().join("run-tmp");
1456        let found = package_config(h, &temp);
1457        let names: Vec<&str> = found.iter().map(|(name, _)| *name).collect();
1458        assert_eq!(names, ["NPM_CONFIG_USERCONFIG", "UV_CONFIG_FILE"]);
1459        let npmrc = fs::read_to_string(&found[0].1).unwrap();
1460        assert_eq!(npmrc, "min-release-age=7\nsave-exact=true\n");
1461        let uv = fs::read_to_string(&found[1].1).unwrap();
1462        assert_eq!(uv, "exclude-newer = \"7 days\"\n");
1463        assert!(found.iter().all(|(_, file)| file.starts_with(&temp)));
1464
1465        // The files themselves stay hidden
1466        let p = policy(&run);
1467        assert!(p.hidden.contains(&h.join(".npmrc")));
1468        assert!(p.hidden.contains(&h.join(".config/uv")));
1469    }
1470
1471    #[test]
1472    fn claude_s_session_dir_of_the_worktree_is_writable() {
1473        let (_root, run) = fixture(false);
1474        assert!(claude_project_dir(&run.home, &run.work_dir).is_none());
1475        fs::create_dir_all(run.home.join(".claude/projects/-other")).unwrap();
1476        let p = policy(&run);
1477        let name = run.work_dir.to_string_lossy().replace(['/', '.'], "-");
1478        let dir = run.home.join(".claude/projects").join(name);
1479        assert!(dir.is_dir());
1480        assert!(p.writable.contains(&dir));
1481        assert!(!p.writable.contains(&run.home.join(".claude/projects")));
1482        assert!(!p.writable.contains(&run.home.join(".claude")));
1483    }
1484
1485    #[test]
1486    fn shipcheck_s_state_is_read_only_and_opencode_s_service_hidden() {
1487        let (_root, run) = fixture(false);
1488        let p = policy(&run);
1489        let h = &run.home;
1490        assert!(p.read_only.contains(&h.join(".local/state/shipcheck")));
1491        assert!(
1492            p.hidden
1493                .contains(&h.join(".local/state/opencode/service.json"))
1494        );
1495        assert!(p.hidden.contains(&h.join(".config/opencode/service.json")));
1496    }
1497
1498    #[test]
1499    fn a_job_task_may_write_the_store() {
1500        let (_root, run) = fixture(true);
1501        assert!(
1502            !policy(&run)
1503                .read_only
1504                .contains(&run.orch_home.join("orch.db"))
1505        );
1506    }
1507
1508    #[test]
1509    fn only_a_job_task_sees_the_write_endpoint_token() {
1510        let (_root, run) = fixture(false);
1511        let token = run.orch_home.join("state/cluster.port");
1512        assert!(policy(&run).hidden.contains(&token));
1513        let (_root, run) = fixture(true);
1514        assert!(!policy(&run).hidden.contains(&token));
1515    }
1516
1517    #[test]
1518    fn keys_are_hidden_and_startup_files_read_only() {
1519        let (_root, run) = fixture(false);
1520        let p = policy(&run);
1521        assert!(p.hidden.contains(&run.home.join(".ssh")));
1522        assert!(p.hidden.contains(&run.home.join(".gnupg")));
1523        assert!(!p.hidden.iter().any(|h| h.ends_with(".cargo/config.toml")));
1524        assert!(p.read_only.contains(&run.work_dir.join(".orch.yml")));
1525    }
1526
1527    // A real Seatbelt run of the policy, skipped where no sandbox starts, such as inside another one.
1528    // Not on Linux: bwrap binds only existing paths, so a missing read-only path such as `.orch.yml` stays writable
1529    #[cfg(target_os = "macos")]
1530    #[test]
1531    fn the_kernel_enforces_the_policy() {
1532        let Ok(backend) = Backend::detect() else {
1533            eprintln!("skipped: no OS sandbox starts here");
1534            return;
1535        };
1536        let (_root, mut run) = fixture(false);
1537        run.seatbelt = backend == Backend::Seatbelt;
1538        let other = run.orch_home.join("worktrees/proj/other");
1539        fs::create_dir_all(run.home.join(".ssh")).unwrap();
1540        fs::write(run.home.join(".ssh/key"), "k").unwrap();
1541        let script = format!(
1542            "echo ok > {w}/f && ! echo x > {o}/config.yml && ! echo x > {other}/f \
1543             && ! echo x > {w}/.orch.yml && ! echo x >> {h}/.zshrc && ! cat {h}/.ssh/key \
1544             && ! echo x > {h}/.new-dotfile && ! echo x > {h}/.claude.json \
1545             && echo cache > {h}/.cargo/probe",
1546            w = run.work_dir.display(),
1547            o = run.orch_home.display(),
1548            other = other.display(),
1549            h = run.home.display(),
1550        );
1551        let out = Sandbox::new(backend, policy(&run))
1552            .unwrap()
1553            .command("/bin/sh")
1554            .args(["-c", &script])
1555            .output()
1556            .unwrap();
1557        assert!(
1558            out.status.success(),
1559            "{}",
1560            String::from_utf8_lossy(&out.stderr)
1561        );
1562        assert!(run.work_dir.join("f").exists());
1563        assert!(!other.join("f").exists());
1564    }
1565
1566    // A socket outside the worktree, such as tmux's, is out of reach, and another branch's ref too
1567    // Not on Linux: bwrap has no socket filter, so a socket in the home stays reachable
1568    #[cfg(target_os = "macos")]
1569    #[test]
1570    fn the_kernel_keeps_sockets_and_other_branches_out_of_reach() {
1571        let Ok(backend) = Backend::detect() else {
1572            eprintln!("skipped: no OS sandbox starts here");
1573            return;
1574        };
1575        let (_root, mut run) = fixture(false);
1576        run.seatbelt = backend == Backend::Seatbelt;
1577        for dir in [&run.work_dir, &run.home] {
1578            let listener = UnixListener::bind(dir.join("s")).unwrap();
1579            thread::spawn(move || listener.incoming().for_each(drop));
1580        }
1581        let git = run.home.join("proj/.git");
1582        let script = format!(
1583            "/usr/bin/nc -U {w}/s </dev/null && ! /usr/bin/nc -U {h}/s </dev/null \
1584             && echo sha > {g}/refs/heads/feat/mine && ! echo sha > {g}/refs/heads/main \
1585             && echo sha > {g}/worktrees/mine/HEAD && ! echo x > {g}/worktrees/mine/gitdir",
1586            w = run.work_dir.display(),
1587            h = run.home.display(),
1588            g = git.display(),
1589        );
1590        let out = Sandbox::new(backend, policy(&run))
1591            .unwrap()
1592            .command("/bin/sh")
1593            .args(["-c", &script])
1594            .output()
1595            .unwrap();
1596        assert!(
1597            out.status.success(),
1598            "{}",
1599            String::from_utf8_lossy(&out.stderr)
1600        );
1601        assert_eq!(fs::read_to_string(git.join("refs/heads/main")).unwrap(), "");
1602    }
1603
1604    // A missing commondir in the common dir would redirect git to a dir the agent controls
1605    // Not on Linux: bwrap binds only existing paths, so a missing `commondir` stays writable
1606    #[cfg(target_os = "macos")]
1607    #[test]
1608    fn the_kernel_refuses_a_new_commondir_in_the_common_dir() {
1609        let Ok(backend) = Backend::detect() else {
1610            eprintln!("skipped: no OS sandbox starts here");
1611            return;
1612        };
1613        let (_root, mut run) = fixture(false);
1614        run.seatbelt = backend == Backend::Seatbelt;
1615        let git = run.home.join("proj/.git");
1616        assert!(!git.join("commondir").exists());
1617        let script = format!(
1618            "! echo {w} > {g}/commondir",
1619            w = run.work_dir.display(),
1620            g = git.display()
1621        );
1622        let out = Sandbox::new(backend, policy(&run))
1623            .unwrap()
1624            .command("/bin/sh")
1625            .args(["-c", &script])
1626            .output()
1627            .unwrap();
1628        assert!(
1629            out.status.success(),
1630            "{}",
1631            String::from_utf8_lossy(&out.stderr)
1632        );
1633        assert!(!git.join("commondir").exists());
1634    }
1635
1636    // Removing or replacing tmux's socket file is refused
1637    #[cfg(any(target_os = "macos", target_os = "linux"))]
1638    #[test]
1639    fn the_kernel_keeps_the_tmux_socket_in_the_temp_dir_in_place() {
1640        let Ok(backend) = Backend::detect() else {
1641            eprintln!("skipped: no OS sandbox starts here");
1642            return;
1643        };
1644        let (_root, mut run) = fixture(false);
1645        run.seatbelt = backend == Backend::Seatbelt;
1646        let dir = tempfile::Builder::new()
1647            .prefix("tmux-")
1648            .tempdir_in(&run.home)
1649            .unwrap();
1650        run.temp = run.home.clone();
1651        let sock = dir.path().join("default");
1652        fs::write(&sock, "").unwrap();
1653        let script = format!(
1654            "! rm {s} && ! mv {s} {s}2 && ! echo x > {d}/new",
1655            s = sock.display(),
1656            d = dir.path().display(),
1657        );
1658        let out = Sandbox::new(backend, policy(&run))
1659            .unwrap()
1660            .command("/bin/sh")
1661            .args(["-c", &script])
1662            .output()
1663            .unwrap();
1664        assert!(
1665            out.status.success(),
1666            "{}",
1667            String::from_utf8_lossy(&out.stderr)
1668        );
1669        assert!(sock.exists());
1670    }
1671
1672    // The run's temp dir, the package settings copy and the `sandbox:` paths, under the kernel
1673    #[cfg(any(target_os = "macos", target_os = "linux"))]
1674    #[test]
1675    fn the_kernel_honors_the_run_temp_dir_package_copies_and_config_paths() {
1676        let Ok(backend) = Backend::detect() else {
1677            eprintln!("skipped: no OS sandbox starts here");
1678            return;
1679        };
1680        let (root, mut run) = fixture(false);
1681        run.seatbelt = backend == Backend::Seatbelt;
1682        let (h, r) = (run.home.clone(), root.path().canonicalize().unwrap());
1683        fs::create_dir_all(&run.temp).unwrap();
1684        fs::write(
1685            h.join(".npmrc"),
1686            "min-release-age=3\n//registry.example/:_authToken=npm-secret\n",
1687        )
1688        .unwrap();
1689        fs::create_dir_all(h.join(".aws")).unwrap();
1690        fs::write(h.join(".aws/config"), "aws").unwrap();
1691        let (outside, shared) = (r.join("outside"), r.parent().unwrap().to_path_buf());
1692        fs::create_dir_all(&outside).unwrap();
1693        let found = package_config(&h, &run.temp);
1694        let npmrc = &found
1695            .iter()
1696            .find(|(v, _)| *v == "NPM_CONFIG_USERCONFIG")
1697            .unwrap()
1698            .1;
1699        let probe = |run: &Run, script: &str| {
1700            let out = Sandbox::new(backend, policy(run))
1701                .unwrap()
1702                .command("/bin/sh")
1703                .args(["-c", script])
1704                .env("TMPDIR", &run.temp)
1705                .output()
1706                .unwrap();
1707            assert!(
1708                out.status.success(),
1709                "{script}\n{}",
1710                String::from_utf8_lossy(&out.stderr)
1711            );
1712        };
1713        let name = format!("{}-probe", r.file_name().unwrap().to_string_lossy());
1714        probe(
1715            &run,
1716            &format!(
1717                "f=$(mktemp \"$TMPDIR/x.XXXXXX\") && echo ok > \"$f\" \
1718                 && ! echo x > {s}/{name} \
1719                 && grep -q min-release-age {n} && ! grep -q npm-secret {n} \
1720                 && ! cat {h}/.npmrc && ! cat {h}/.aws/config && ! echo x > {o}/f",
1721                s = shared.display(),
1722                n = npmrc.display(),
1723                h = h.display(),
1724                o = outside.display(),
1725            ),
1726        );
1727        assert!(!shared.join(&name).exists());
1728
1729        run.extra = Extra {
1730            write: vec![outside.clone(), h.join("proj/src")],
1731            read: vec![h.join(".aws")],
1732            sockets: vec![],
1733        };
1734        probe(
1735            &run,
1736            &format!(
1737                "echo ok > {o}/f && cat {h}/.aws/config && ! cat {h}/.npmrc \
1738                 && ! echo x > {h}/proj/src/f",
1739                o = outside.display(),
1740                h = h.display(),
1741            ),
1742        );
1743        assert!(outside.join("f").exists());
1744        assert!(!h.join("proj/src/f").exists());
1745    }
1746
1747    // A logged-in claude answers under the policy with the real home: `--run-ignored only claude`
1748    #[cfg(target_os = "macos")]
1749    #[test]
1750    #[ignore = "needs a logged-in claude on the host"]
1751    fn claude_answers_inside_the_sandbox_with_the_real_home() {
1752        let root = tempfile::tempdir().unwrap();
1753        let work = root.path().canonicalize().unwrap();
1754        let home = PathBuf::from(env::var_os("HOME").unwrap());
1755        let run = Run {
1756            work_dir: work.clone(),
1757            git_dir: None,
1758            common_dir: None,
1759            own_ref: None,
1760            home: home.clone(),
1761            orch_home: home.join(".orch"),
1762            projects: vec![],
1763            path_dirs: env::split_paths(&env::var_os("PATH").unwrap()).collect(),
1764            temp: env::temp_dir(),
1765            extra: Extra::default(),
1766            internal: false,
1767            seatbelt: true,
1768        };
1769        let out = Sandbox::new(Backend::Seatbelt, policy(&run))
1770            .unwrap()
1771            .command("/bin/sh")
1772            .args(["-c", "claude -p --model haiku 'Reply with the word ok'"])
1773            .current_dir(&work)
1774            .output()
1775            .unwrap();
1776        let text = String::from_utf8_lossy(&out.stdout).to_lowercase();
1777        assert!(
1778            text.contains("ok"),
1779            "{text}{}",
1780            String::from_utf8_lossy(&out.stderr)
1781        );
1782    }
1783
1784    #[test]
1785    fn bwrap_drops_a_missing_write_path_and_seatbelt_keeps_it() {
1786        let (_root, mut run) = fixture(false);
1787        let (missing, present) = (run.home.join("data/new"), run.home.join(".config/nvim"));
1788        run.extra.write = vec![missing.clone(), present.clone()];
1789        let p = policy(&run);
1790        assert!(!p.writable.contains(&missing));
1791        assert!(p.writable.contains(&present));
1792        run.seatbelt = true;
1793        assert!(policy(&run).writable.contains(&missing));
1794    }
1795
1796    #[test]
1797    fn a_worktree_that_is_the_main_checkout_stays_writable() {
1798        let (_root, mut run) = fixture(false);
1799        run.work_dir = run.home.join("proj");
1800        let p = policy(&run);
1801        assert!(!p.read_only.contains(&run.work_dir));
1802        assert!(!p.read_only.contains(&run.work_dir.join("src")));
1803    }
1804}