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