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