Skip to main content

base/interface/exec/
sandbox.rs

1//! `Sandbox` — how a process is constrained.
2//!
3//! The split this contract exists to keep: a backend decides *how* to
4//! constrain, the kernel decides *what* to constrain and *whether to at all*.
5//! The policy below is the kernel's; an implementation may only report how
6//! much of it it managed to deliver.
7//!
8//! **The hard invariant: a policy that asked for constraint must never
9//! silently become an unconstrained run.** A backend that cannot deliver says
10//! so through [`Enforcement`], and the caller — with
11//! `sandbox.require` — decides whether to refuse. A `warn!` nobody
12//! reads is not a decision.
13
14use std::net::SocketAddr;
15use std::path::{Path, PathBuf};
16
17use super::env::EnvScope;
18use super::process::ProcessSpec;
19
20/// What to constrain. The kernel's, not a backend's.
21///
22/// Defaults bake in a deny-read list (`~/.ssh`, `~/.aws`, …) so that a naive
23/// Bash command does not dump credential files into the model's transcript by
24/// accident. Not every field lands cleanly on every backend; the ones that do
25/// not are reported through [`Enforcement`] rather than ignored.
26#[derive(Debug, Clone, Default)]
27pub struct SandboxPolicy {
28    /// Absolute paths the sandbox is allowed to **read**, on top of the
29    /// universal default (everything readable). An entry that is also in
30    /// `deny_read` is re-allowed; a parent directory, or a path below a
31    /// denied one, changes nothing.
32    pub allow_read: Vec<PathBuf>,
33    /// Absolute paths the sandbox is **denied** read access to. Defaults
34    /// include common credential stores (see [`default_deny_read`]).
35    pub deny_read: Vec<PathBuf>,
36    /// Paths denied as named, under no `allow_read`: the backends deny each
37    /// path's own spellings and do not follow the links inside it.
38    pub deny_read_exact: Vec<PathBuf>,
39    /// Filename segments no command may write inside a writable root: a path
40    /// is refused when a component under the root equals one or begins with
41    /// it followed by a dot. macOS refuses new and existing paths alike;
42    /// Linux can only mount over the entries that exist when the command
43    /// starts.
44    pub deny_write: Vec<String>,
45    /// Network policy — see [`NetworkMode`].
46    pub network_mode: NetworkMode,
47    /// Domains allowed to make outbound connections when `network_mode` is
48    /// [`NetworkMode::Allowlist`]. Ignored otherwise. What each backend makes
49    /// of it is under [`NetworkMode::Allowlist`].
50    pub allowed_domains: Vec<String>,
51    /// The only place outbound connections may go under
52    /// [`NetworkMode::Proxy`]. Ignored otherwise.
53    pub egress_proxy: Option<EgressProxy>,
54    /// Paths outside `cwd` this command may still write to.
55    ///
56    /// Part of the policy rather than a separate argument because it answers
57    /// the same question the rest of it does — what may be written — and a
58    /// backend that received it separately could be handed a policy that
59    /// looks complete and is not.
60    pub additional_writable: Vec<PathBuf>,
61    /// Directories no command writes in, nor moves aside, wherever they lie:
62    /// the host's skill directories and its own packages.
63    pub read_only_dirs: Vec<PathBuf>,
64    /// Nothing is writable but `additional_writable` and `/dev`: not `cwd`,
65    /// not the state root's working directories, not the per-user temporary
66    /// directory. For the engine's own git, which reads the project and
67    /// writes only where its bookkeeping lives.
68    pub only_additional_writable: bool,
69    /// Where a working directory that is a linked worktree commits to, as
70    /// the engine checked it when it made the worktree: its git directory is
71    /// guarded as `<cwd>/.git` is otherwise, and what of it is writable is
72    /// [`crate::paths::WorktreeGit::writable`] in `additional_writable`. The
73    /// backends never follow the worktree's own links to find it, since a
74    /// command may have rewritten them.
75    pub worktree_git: Option<crate::paths::WorktreeGit>,
76    /// This instance's global state root, whose configuration a command may
77    /// not rewrite. `None` protects no state root: the backends do not guess
78    /// `$HOME/.agix`, since a redirected instance whose sandbox protected it
79    /// would be guarding a file it does not use while leaving its real
80    /// settings.json writable. Every session's policy names one
81    /// ([`SandboxSettings::policy`]).
82    pub state_root: Option<PathBuf>,
83    /// Other instances' state roots on this machine
84    /// ([`crate::paths::known_state_roots`]): a command reads none of their
85    /// credentials, writes nothing in them and connects to no socket in them.
86    pub foreign_state_roots: Vec<PathBuf>,
87    /// What the instance names a project's directory: the configuration
88    /// root guarded in `cwd`.
89    pub layout: crate::paths::Layout,
90    /// Also refuse the ways a command can have another process act for it
91    /// outside the sandbox: on macOS sending Apple events, opening apps and
92    /// URLs through LaunchServices, and writing preferences through
93    /// `cfprefsd`; on Linux the host's IPC namespace and the session bus.
94    /// For an unattended session, where nobody approved the command.
95    pub deny_ipc_escapes: bool,
96    /// What may be read at all; `deny_read` and the engine's credentials
97    /// stay unreadable inside it.
98    pub read: ReadScope,
99    /// The environment the command starts from. The backend marks the
100    /// confined spec with it ([`ProcessSpec::env_scope`]); the process
101    /// provider applies it.
102    pub env: EnvScope,
103}
104
105/// What a confined command may read.
106#[derive(Debug, Clone, Default, PartialEq, Eq)]
107pub enum ReadScope {
108    #[default]
109    Everything,
110    /// These roots, and those of the backend's own table: the system
111    /// directories programs load from and the user's git configuration.
112    /// Anywhere else a command sees names and metadata but no contents.
113    Only(Vec<PathBuf>),
114}
115
116impl ReadScope {
117    /// Whether `path` is under one of the caller's roots. The backend's own
118    /// table is not consulted.
119    pub fn names(&self, path: &Path) -> bool {
120        match self {
121            Self::Everything => true,
122            Self::Only(roots) => roots.iter().any(|root| path.starts_with(root)),
123        }
124    }
125}
126
127impl SandboxPolicy {
128    /// The policy for a command let through on its own word
129    /// (`ExecProfile::Strict`): no network, nothing writable but `tmpdir`,
130    /// nothing readable but `readable` and `tmpdir`, the minimal
131    /// environment, and the IPC routes out refused. What this policy keeps
132    /// from being read stays unreadable under the strict one.
133    pub fn strict(
134        &self,
135        readable: impl IntoIterator<Item = PathBuf>,
136        tmpdir: Option<PathBuf>,
137    ) -> Self {
138        let writable: Vec<PathBuf> = tmpdir.into_iter().collect();
139        Self {
140            allow_read: self.allow_read.clone(),
141            deny_read: self.deny_read.clone(),
142            deny_read_exact: self.deny_read_exact.clone(),
143            deny_write: self.deny_write.clone(),
144            network_mode: NetworkMode::DenyAll,
145            allowed_domains: Vec::new(),
146            egress_proxy: None,
147            read: ReadScope::Only(
148                readable
149                    .into_iter()
150                    .chain(writable.iter().cloned())
151                    .collect(),
152            ),
153            additional_writable: writable,
154            read_only_dirs: self.read_only_dirs.clone(),
155            only_additional_writable: true,
156            worktree_git: self.worktree_git.clone(),
157            state_root: self.state_root.clone(),
158            foreign_state_roots: self.foreign_state_roots.clone(),
159            layout: self.layout.clone(),
160            deny_ipc_escapes: true,
161            env: EnvScope::Minimal,
162        }
163    }
164}
165
166#[derive(
167    Debug,
168    Clone,
169    Copy,
170    PartialEq,
171    Eq,
172    Default,
173    serde::Serialize,
174    serde::Deserialize,
175    schemars::JsonSchema,
176)]
177#[serde(rename_all = "snake_case")]
178pub enum NetworkMode {
179    /// Unrestricted outbound (default; Bash often needs `curl` / `npm install`).
180    #[default]
181    Unrestricted,
182    /// No outbound network access at all. On macOS 26 that includes name
183    /// resolution, which goes through `mDNSResponder`'s unix socket.
184    DenyAll,
185    /// Outbound restricted to `SandboxPolicy::allowed_domains`. Neither
186    /// backend can filter by domain: macOS lets through localhost when the
187    /// list names it and nothing else, Linux cuts the network entirely, and
188    /// both report the domains they could not allow as unmet.
189    Allowlist,
190    /// Outbound only to [`SandboxPolicy::egress_proxy`], with the command's
191    /// `*_PROXY` variables pointing at it; what the proxy lets through is the
192    /// proxy's business. Without an `egress_proxy` the network is cut, as
193    /// under `DenyAll`, and reported unmet.
194    Proxy,
195}
196
197/// `sandbox.network.proxy`: the proxy a sandboxed command's traffic must go
198/// through. Addresses, never names, so that nothing has to be resolved to
199/// write the rule or the variables.
200#[derive(Debug, Clone, PartialEq, Eq)]
201pub struct EgressProxy {
202    /// An HTTP proxy that takes `CONNECT`.
203    pub http: SocketAddr,
204    /// A SOCKS5 proxy, for `ALL_PROXY`.
205    pub socks: Option<SocketAddr>,
206    /// `NO_PROXY`. Empty overrides whatever the command would inherit, so
207    /// even `localhost` goes through the proxy.
208    pub no_proxy: Vec<String>,
209}
210
211impl EgressProxy {
212    pub fn addresses(&self) -> impl Iterator<Item = SocketAddr> + '_ {
213        std::iter::once(self.http).chain(self.socks)
214    }
215}
216
217/// The engine's sandbox settings for a session, as `settings.json`'s
218/// `sandbox` section gave them: what a command is held to, before any one
219/// call narrows it. Every [`SandboxPolicy`] a command or the engine's own git
220/// runs under is derived from this, here.
221#[derive(Debug, Clone, Default)]
222pub struct SandboxSettings {
223    pub allow_read: Vec<PathBuf>,
224    /// Empty means the built-in credential list ([`default_deny_read`]); a
225    /// list replaces it whole.
226    pub deny_read: Vec<PathBuf>,
227    pub network_mode: NetworkMode,
228    pub allowed_domains: Vec<String>,
229    pub egress_proxy: Option<EgressProxy>,
230    /// Filename segments no tool may write, on top of the built-in ones;
231    /// sandboxed commands are held to them too ([`SandboxPolicy::deny_write`]).
232    pub deny_write: Vec<String>,
233    /// Paths exempt from the write deny rules.
234    pub allow_write: Vec<PathBuf>,
235    /// This instance's sensitive paths: its state root, so the profile
236    /// protects the settings files that actually govern it, and the
237    /// credentials the gate and the file tools refuse.
238    pub paths: std::sync::Arc<crate::paths::SensitivePaths>,
239    pub require_enforcement: bool,
240    /// `sandbox.unattended_needs_network_policy: false`.
241    pub unattended_allows_open_network: bool,
242    /// `sandbox.enabled`: commands run outside the OS sandbox.
243    pub disabled: bool,
244    /// [`SandboxPolicy::worktree_git`], for a session working in a linked
245    /// worktree.
246    pub worktree_git: Option<crate::paths::WorktreeGit>,
247    /// A sandboxed command writes nothing but these and its `TMPDIR`: a
248    /// sub-agent the host started with `writes`.
249    pub writable_only: Option<Vec<PathBuf>>,
250}
251
252impl SandboxSettings {
253    /// The policy a session's command runs under before its call adds what
254    /// it may write.
255    pub fn policy(&self) -> SandboxPolicy {
256        let deny_read = if self.deny_read.is_empty() {
257            default_deny_read()
258        } else {
259            self.deny_read.clone()
260        };
261        SandboxPolicy {
262            allow_read: self.allow_read.clone(),
263            deny_read,
264            deny_read_exact: Vec::new(),
265            deny_write: self.deny_write.clone(),
266            network_mode: self.network_mode,
267            allowed_domains: self.allowed_domains.clone(),
268            egress_proxy: self.egress_proxy.clone(),
269            state_root: self.paths.state_root().map(Path::to_path_buf),
270            foreign_state_roots: self.paths.foreign_state_roots(),
271            layout: self.paths.layout().clone(),
272            additional_writable: Vec::new(),
273            read_only_dirs: Vec::new(),
274            only_additional_writable: false,
275            worktree_git: self.worktree_git.clone(),
276            deny_ipc_escapes: false,
277            read: ReadScope::Everything,
278            env: EnvScope::Session,
279        }
280    }
281
282    /// The session's own temporary directory: a sandboxed command's `TMPDIR`,
283    /// and the only temporary directory it may write besides the one macOS
284    /// `mktemp` insists on. Not created here.
285    ///
286    /// Under the state root rather than in the system temporary directory: on
287    /// macOS that is the per-user `DARWIN_USER_TEMP_DIR` every sandboxed
288    /// command may write, so one session's commands could reach into
289    /// another's.
290    pub fn session_tmp_dir(&self, session_id: &str) -> PathBuf {
291        self.paths.session_tmp_dir(session_id).unwrap_or_else(|| {
292            let id: String = session_id
293                .chars()
294                .filter(|c| c.is_ascii_alphanumeric() || *c == '-')
295                .collect();
296            std::env::temp_dir().join(format!("agix-{id}"))
297        })
298    }
299
300    /// What the session's sandbox holds a command to, for the permission
301    /// policy to read: one probe command confined the way a command nobody
302    /// attends is, since that is the command the answer lets run. Only
303    /// `exec.sandbox` is asked; nothing runs.
304    pub fn confinement(
305        &self,
306        exec: &super::ExecProviders,
307        cwd: &Path,
308        session_id: &str,
309    ) -> ConfinementReport {
310        let (require, network) = (
311            self.require_enforcement,
312            self.unattended_allows_open_network,
313        );
314        if self.disabled {
315            return ConfinementReport::disabled(require, network);
316        }
317        let mut policy = self.policy();
318        policy.additional_writable = vec![self.session_tmp_dir(session_id)];
319        policy.deny_ipc_escapes = true;
320        let probe = ProcessSpec::new("bash", cwd).args(["-c", "true"]);
321        ConfinementReport::probe(&*exec.sandbox, probe, &policy, require, network)
322    }
323
324    /// How the engine starts its own git and helpers: through the session's
325    /// providers, and inside its sandbox whenever the session's shell
326    /// commands are, so what a repository such a command configured makes
327    /// git run is held to the same roots. `tmpdir` is the session's, made
328    /// ready.
329    pub fn engine_git(
330        &self,
331        exec: &super::ExecProviders,
332        trust: crate::permission::ProjectTrust,
333        tmpdir: Option<PathBuf>,
334    ) -> crate::engine_exec::EngineExec {
335        use crate::engine_exec::{Confinement, EngineExec};
336        let confinement = if self.disabled {
337            Confinement::Unconfined
338        } else {
339            Confinement::Sandboxed {
340                policy: self.policy(),
341                require_enforcement: self.require_enforcement,
342                tmpdir,
343            }
344        };
345        EngineExec::new(exec.clone(), confinement, trust)
346    }
347}
348
349/// Default deny-read paths — credential stores that almost never want to be
350/// inside an LLM tool result. User can override via `sandbox.allow_read` in
351/// settings.json. Returned absolute (`HOME` resolved).
352///
353/// 两个生产调用点:
354/// - `SandboxSettings::policy` —— 空 `deny_read` 回落到这里,作为真正的沙盒 profile;
355/// - `bash::classify` —— 命令分类时用同一份名单判断某个参数是不是在读凭据,
356///   避免 `cat ~/.ssh/id_rsa` 被当成"只读命令"静默放行。
357///   两处共用一份定义,是为了不让"沙盒挡得住"和"分类器放得过"两套标准打架。
358pub fn default_deny_read() -> Vec<PathBuf> {
359    crate::paths::home_dir()
360        .map(|h| default_deny_read_in(&h))
361        .unwrap_or_default()
362}
363
364/// [`default_deny_read`] for the home directory `home`.
365pub fn default_deny_read_in(home: &Path) -> Vec<PathBuf> {
366    crate::paths::HOME_CREDENTIAL_STORES
367        .iter()
368        .map(|p| home.join(p))
369        .collect()
370}
371
372/// Which backend ran. Advisory — for logs and tests.
373#[derive(Debug, Clone, Copy, PartialEq, Eq)]
374pub enum SandboxMode {
375    /// Explicitly turned off by configuration.
376    Disabled,
377    /// No backend for this platform, or its tool is missing.
378    Unavailable,
379    /// macOS `sandbox-exec`.
380    MacOSSandboxExec,
381    /// Linux `bubblewrap`.
382    LinuxBwrap,
383}
384
385/// How much of the policy is actually in force.
386///
387/// This is the field a caller acts on, as against [`SandboxMode`], which only
388/// names the backend.
389#[derive(Debug, Clone, Copy, PartialEq, Eq)]
390pub enum Enforcement {
391    /// Everything the policy asked for.
392    Full,
393    /// Some of it. The backend has capabilities the policy needs and lacks
394    /// others — neither backend has a domain-level network filter, so an
395    /// allowlist of domains becomes "no network" (localhost aside, on macOS),
396    /// which is stricter in one direction and not what was asked for in the
397    /// other. What is missing is listed in [`Confined::unmet`].
398    Partial,
399    /// None of it. The command below runs unconstrained.
400    None,
401}
402
403/// A command, after the sandbox has had its say.
404#[derive(Debug, Clone)]
405pub struct Confined {
406    /// What to actually run — usually the original program wrapped in the
407    /// backend's own.
408    pub spec: ProcessSpec,
409    pub mode: SandboxMode,
410    pub enforcement: Enforcement,
411    /// The parts of the policy this backend could not deliver, one per line,
412    /// in words a person can act on. Empty when `enforcement` is `Full`.
413    pub unmet: Vec<String>,
414}
415
416/// How a process is constrained.
417///
418/// A pure transformation, which is what makes it testable: it turns the
419/// command someone meant to run into the command that will actually run, and
420/// reports honestly how much of the policy survived. It does not execute
421/// anything — that is [`Process`](super::Process), and keeping them apart is
422/// what lets a caller inspect the confinement before committing to it.
423pub trait Sandbox: Send + Sync {
424    fn confine(&self, spec: ProcessSpec, policy: &SandboxPolicy) -> Confined;
425}
426
427/// What the session's sandbox holds a command to, found once when the session
428/// is built. The permission policy reads it and never probes the sandbox
429/// itself.
430#[derive(Debug, Clone, PartialEq, Eq)]
431#[non_exhaustive]
432pub struct ConfinementReport {
433    /// How much of the session's policy holds a command.
434    pub session: Enforcement,
435    /// What of the session's policy does not hold, as [`Confined::unmet`].
436    pub session_unmet: Vec<String>,
437    /// How much of the strict policy ([`SandboxPolicy::strict`]) holds one.
438    pub strict: Enforcement,
439    /// What of the strict policy does not hold, as [`Confined::unmet`].
440    pub strict_unmet: Vec<String>,
441    /// The model cannot reach whatever host it likes.
442    pub network_restricted: bool,
443    pub require_enforcement: bool,
444    pub unattended_allows_open_network: bool,
445}
446
447impl Default for ConfinementReport {
448    /// Nothing found out: no command is held.
449    fn default() -> Self {
450        Self {
451            session: Enforcement::None,
452            session_unmet: Vec::new(),
453            strict: Enforcement::None,
454            strict_unmet: Vec::new(),
455            network_restricted: false,
456            require_enforcement: false,
457            unattended_allows_open_network: false,
458        }
459    }
460}
461
462impl ConfinementReport {
463    /// Confine a probe command under `policy`, and under its strict
464    /// counterpart, and report how much of each held.
465    pub fn probe(
466        sandbox: &dyn Sandbox,
467        probe: ProcessSpec,
468        policy: &SandboxPolicy,
469        require_enforcement: bool,
470        unattended_allows_open_network: bool,
471    ) -> Self {
472        let strict = sandbox.confine(probe.clone(), &policy.strict(Vec::new(), None));
473        let session = sandbox.confine(probe, policy);
474        Self {
475            session: session.enforcement,
476            session_unmet: session.unmet,
477            strict: strict.enforcement,
478            strict_unmet: strict.unmet,
479            network_restricted: !matches!(policy.network_mode, NetworkMode::Unrestricted),
480            require_enforcement,
481            unattended_allows_open_network,
482        }
483    }
484
485    /// No sandbox at all: the session turned it off.
486    pub fn disabled(require_enforcement: bool, unattended_allows_open_network: bool) -> Self {
487        Self {
488            require_enforcement,
489            unattended_allows_open_network,
490            ..Self::default()
491        }
492    }
493
494    /// A command nobody can be asked about may run: the sandbox fully holds
495    /// it, and the network is restricted when the settings ask for that too.
496    pub fn holds_unattended(&self) -> bool {
497        self.session == Enforcement::Full
498            && (self.unattended_allows_open_network || self.network_restricted)
499    }
500}
501
502#[cfg(test)]
503mod settings_tests {
504    use super::*;
505
506    #[test]
507    fn the_policy_carries_the_settings_through() {
508        let settings = SandboxSettings {
509            allow_read: vec![PathBuf::from("/home/u/.npmrc")],
510            deny_read: vec![PathBuf::from("/tmp/secret")],
511            allowed_domains: vec!["api.example.com".to_string()],
512            network_mode: NetworkMode::Allowlist,
513            ..Default::default()
514        };
515        let policy = settings.policy();
516        assert_eq!(policy.allow_read, [PathBuf::from("/home/u/.npmrc")]);
517        assert_eq!(policy.deny_read, [PathBuf::from("/tmp/secret")]);
518        assert_eq!(policy.allowed_domains, ["api.example.com"]);
519        assert_eq!(policy.network_mode, NetworkMode::Allowlist);
520    }
521
522    /// An empty `deny_read` is the built-in credential list, not "deny
523    /// nothing"; `allow_read` re-allows on top of it and is not defaulted.
524    #[test]
525    fn an_empty_deny_read_is_the_credential_defaults() {
526        let policy = SandboxSettings::default().policy();
527        assert_eq!(policy.deny_read, default_deny_read());
528        assert!(policy.allow_read.is_empty());
529        if crate::paths::home_dir().is_some() {
530            let joined = policy
531                .deny_read
532                .iter()
533                .map(|p| p.display().to_string())
534                .collect::<Vec<_>>()
535                .join("|");
536            assert!(joined.contains(".ssh") && joined.contains(".aws"));
537        }
538    }
539
540    #[test]
541    fn a_proxy_restricts_the_network_and_the_strict_policy_drops_it() {
542        struct Holds;
543        impl Sandbox for Holds {
544            fn confine(&self, spec: ProcessSpec, _: &SandboxPolicy) -> Confined {
545                Confined {
546                    spec,
547                    mode: SandboxMode::MacOSSandboxExec,
548                    enforcement: Enforcement::Full,
549                    unmet: Vec::new(),
550                }
551            }
552        }
553        let settings = SandboxSettings {
554            network_mode: NetworkMode::Proxy,
555            egress_proxy: Some(EgressProxy {
556                http: "127.0.0.1:3128".parse().unwrap(),
557                socks: None,
558                no_proxy: Vec::new(),
559            }),
560            ..Default::default()
561        };
562        let policy = settings.policy();
563        assert_eq!(policy.egress_proxy, settings.egress_proxy);
564        let strict = policy.strict(Vec::new(), None);
565        assert_eq!(strict.network_mode, NetworkMode::DenyAll);
566        assert!(strict.egress_proxy.is_none());
567        let probe = ProcessSpec::new("bash", Path::new("/work"));
568        let report = ConfinementReport::probe(&Holds, probe, &policy, false, true);
569        assert!(report.network_restricted);
570        assert!(report.holds_unattended());
571    }
572
573    #[test]
574    fn a_disabled_sandbox_confines_neither_commands_nor_the_engines_git() {
575        let settings = SandboxSettings {
576            disabled: true,
577            ..Default::default()
578        };
579        let exec = super::super::ExecProviders::in_process();
580        let report = settings.confinement(&exec, Path::new("/work"), "s");
581        assert_eq!(report, ConfinementReport::disabled(false, false));
582        let git = settings.engine_git(&exec, crate::permission::ProjectTrust::Trusted, None);
583        assert!(!git.is_sandboxed());
584    }
585}