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}
248
249impl SandboxSettings {
250    /// The policy a session's command runs under before its call adds what
251    /// it may write.
252    pub fn policy(&self) -> SandboxPolicy {
253        let deny_read = if self.deny_read.is_empty() {
254            default_deny_read()
255        } else {
256            self.deny_read.clone()
257        };
258        SandboxPolicy {
259            allow_read: self.allow_read.clone(),
260            deny_read,
261            deny_read_exact: Vec::new(),
262            deny_write: self.deny_write.clone(),
263            network_mode: self.network_mode,
264            allowed_domains: self.allowed_domains.clone(),
265            egress_proxy: self.egress_proxy.clone(),
266            state_root: self.paths.state_root().map(Path::to_path_buf),
267            foreign_state_roots: self.paths.foreign_state_roots(),
268            layout: self.paths.layout().clone(),
269            additional_writable: Vec::new(),
270            read_only_dirs: Vec::new(),
271            only_additional_writable: false,
272            worktree_git: self.worktree_git.clone(),
273            deny_ipc_escapes: false,
274            read: ReadScope::Everything,
275            env: EnvScope::Session,
276        }
277    }
278
279    /// The session's own temporary directory: a sandboxed command's `TMPDIR`,
280    /// and the only temporary directory it may write besides the one macOS
281    /// `mktemp` insists on. Not created here.
282    ///
283    /// Under the state root rather than in the system temporary directory: on
284    /// macOS that is the per-user `DARWIN_USER_TEMP_DIR` every sandboxed
285    /// command may write, so one session's commands could reach into
286    /// another's.
287    pub fn session_tmp_dir(&self, session_id: &str) -> PathBuf {
288        self.paths.session_tmp_dir(session_id).unwrap_or_else(|| {
289            let id: String = session_id
290                .chars()
291                .filter(|c| c.is_ascii_alphanumeric() || *c == '-')
292                .collect();
293            std::env::temp_dir().join(format!("agix-{id}"))
294        })
295    }
296
297    /// What the session's sandbox holds a command to, for the permission
298    /// policy to read: one probe command confined the way a command nobody
299    /// attends is, since that is the command the answer lets run. Only
300    /// `exec.sandbox` is asked; nothing runs.
301    pub fn confinement(
302        &self,
303        exec: &super::ExecProviders,
304        cwd: &Path,
305        session_id: &str,
306    ) -> ConfinementReport {
307        let (require, network) = (
308            self.require_enforcement,
309            self.unattended_allows_open_network,
310        );
311        if self.disabled {
312            return ConfinementReport::disabled(require, network);
313        }
314        let mut policy = self.policy();
315        policy.additional_writable = vec![self.session_tmp_dir(session_id)];
316        policy.deny_ipc_escapes = true;
317        let probe = ProcessSpec::new("bash", cwd).args(["-c", "true"]);
318        ConfinementReport::probe(&*exec.sandbox, probe, &policy, require, network)
319    }
320
321    /// How the engine starts its own git and helpers: through the session's
322    /// providers, and inside its sandbox whenever the session's shell
323    /// commands are, so what a repository such a command configured makes
324    /// git run is held to the same roots. `tmpdir` is the session's, made
325    /// ready.
326    pub fn engine_git(
327        &self,
328        exec: &super::ExecProviders,
329        trust: crate::permission::ProjectTrust,
330        tmpdir: Option<PathBuf>,
331    ) -> crate::engine_exec::EngineExec {
332        use crate::engine_exec::{Confinement, EngineExec};
333        let confinement = if self.disabled {
334            Confinement::Unconfined
335        } else {
336            Confinement::Sandboxed {
337                policy: self.policy(),
338                require_enforcement: self.require_enforcement,
339                tmpdir,
340            }
341        };
342        EngineExec::new(exec.clone(), confinement, trust)
343    }
344}
345
346/// Default deny-read paths — credential stores that almost never want to be
347/// inside an LLM tool result. User can override via `sandbox.allow_read` in
348/// settings.json. Returned absolute (`HOME` resolved).
349///
350/// 两个生产调用点:
351/// - `SandboxSettings::policy` —— 空 `deny_read` 回落到这里,作为真正的沙盒 profile;
352/// - `bash::classify` —— 命令分类时用同一份名单判断某个参数是不是在读凭据,
353///   避免 `cat ~/.ssh/id_rsa` 被当成"只读命令"静默放行。
354///   两处共用一份定义,是为了不让"沙盒挡得住"和"分类器放得过"两套标准打架。
355pub fn default_deny_read() -> Vec<PathBuf> {
356    crate::paths::home_dir()
357        .map(|h| default_deny_read_in(&h))
358        .unwrap_or_default()
359}
360
361/// [`default_deny_read`] for the home directory `home`.
362pub fn default_deny_read_in(home: &Path) -> Vec<PathBuf> {
363    crate::paths::HOME_CREDENTIAL_STORES
364        .iter()
365        .map(|p| home.join(p))
366        .collect()
367}
368
369/// Which backend ran. Advisory — for logs and tests.
370#[derive(Debug, Clone, Copy, PartialEq, Eq)]
371pub enum SandboxMode {
372    /// Explicitly turned off by configuration.
373    Disabled,
374    /// No backend for this platform, or its tool is missing.
375    Unavailable,
376    /// macOS `sandbox-exec`.
377    MacOSSandboxExec,
378    /// Linux `bubblewrap`.
379    LinuxBwrap,
380}
381
382/// How much of the policy is actually in force.
383///
384/// This is the field a caller acts on, as against [`SandboxMode`], which only
385/// names the backend.
386#[derive(Debug, Clone, Copy, PartialEq, Eq)]
387pub enum Enforcement {
388    /// Everything the policy asked for.
389    Full,
390    /// Some of it. The backend has capabilities the policy needs and lacks
391    /// others — neither backend has a domain-level network filter, so an
392    /// allowlist of domains becomes "no network" (localhost aside, on macOS),
393    /// which is stricter in one direction and not what was asked for in the
394    /// other. What is missing is listed in [`Confined::unmet`].
395    Partial,
396    /// None of it. The command below runs unconstrained.
397    None,
398}
399
400/// A command, after the sandbox has had its say.
401#[derive(Debug, Clone)]
402pub struct Confined {
403    /// What to actually run — usually the original program wrapped in the
404    /// backend's own.
405    pub spec: ProcessSpec,
406    pub mode: SandboxMode,
407    pub enforcement: Enforcement,
408    /// The parts of the policy this backend could not deliver, one per line,
409    /// in words a person can act on. Empty when `enforcement` is `Full`.
410    pub unmet: Vec<String>,
411}
412
413/// How a process is constrained.
414///
415/// A pure transformation, which is what makes it testable: it turns the
416/// command someone meant to run into the command that will actually run, and
417/// reports honestly how much of the policy survived. It does not execute
418/// anything — that is [`Process`](super::Process), and keeping them apart is
419/// what lets a caller inspect the confinement before committing to it.
420pub trait Sandbox: Send + Sync {
421    fn confine(&self, spec: ProcessSpec, policy: &SandboxPolicy) -> Confined;
422}
423
424/// What the session's sandbox holds a command to, found once when the session
425/// is built. The permission policy reads it and never probes the sandbox
426/// itself.
427#[derive(Debug, Clone, PartialEq, Eq)]
428#[non_exhaustive]
429pub struct ConfinementReport {
430    /// How much of the session's policy holds a command.
431    pub session: Enforcement,
432    /// What of the session's policy does not hold, as [`Confined::unmet`].
433    pub session_unmet: Vec<String>,
434    /// How much of the strict policy ([`SandboxPolicy::strict`]) holds one.
435    pub strict: Enforcement,
436    /// What of the strict policy does not hold, as [`Confined::unmet`].
437    pub strict_unmet: Vec<String>,
438    /// The model cannot reach whatever host it likes.
439    pub network_restricted: bool,
440    pub require_enforcement: bool,
441    pub unattended_allows_open_network: bool,
442}
443
444impl Default for ConfinementReport {
445    /// Nothing found out: no command is held.
446    fn default() -> Self {
447        Self {
448            session: Enforcement::None,
449            session_unmet: Vec::new(),
450            strict: Enforcement::None,
451            strict_unmet: Vec::new(),
452            network_restricted: false,
453            require_enforcement: false,
454            unattended_allows_open_network: false,
455        }
456    }
457}
458
459impl ConfinementReport {
460    /// Confine a probe command under `policy`, and under its strict
461    /// counterpart, and report how much of each held.
462    pub fn probe(
463        sandbox: &dyn Sandbox,
464        probe: ProcessSpec,
465        policy: &SandboxPolicy,
466        require_enforcement: bool,
467        unattended_allows_open_network: bool,
468    ) -> Self {
469        let strict = sandbox.confine(probe.clone(), &policy.strict(Vec::new(), None));
470        let session = sandbox.confine(probe, policy);
471        Self {
472            session: session.enforcement,
473            session_unmet: session.unmet,
474            strict: strict.enforcement,
475            strict_unmet: strict.unmet,
476            network_restricted: !matches!(policy.network_mode, NetworkMode::Unrestricted),
477            require_enforcement,
478            unattended_allows_open_network,
479        }
480    }
481
482    /// No sandbox at all: the session turned it off.
483    pub fn disabled(require_enforcement: bool, unattended_allows_open_network: bool) -> Self {
484        Self {
485            require_enforcement,
486            unattended_allows_open_network,
487            ..Self::default()
488        }
489    }
490
491    /// A command nobody can be asked about may run: the sandbox fully holds
492    /// it, and the network is restricted when the settings ask for that too.
493    pub fn holds_unattended(&self) -> bool {
494        self.session == Enforcement::Full
495            && (self.unattended_allows_open_network || self.network_restricted)
496    }
497}
498
499#[cfg(test)]
500mod settings_tests {
501    use super::*;
502
503    #[test]
504    fn the_policy_carries_the_settings_through() {
505        let settings = SandboxSettings {
506            allow_read: vec![PathBuf::from("/home/u/.npmrc")],
507            deny_read: vec![PathBuf::from("/tmp/secret")],
508            allowed_domains: vec!["api.example.com".to_string()],
509            network_mode: NetworkMode::Allowlist,
510            ..Default::default()
511        };
512        let policy = settings.policy();
513        assert_eq!(policy.allow_read, [PathBuf::from("/home/u/.npmrc")]);
514        assert_eq!(policy.deny_read, [PathBuf::from("/tmp/secret")]);
515        assert_eq!(policy.allowed_domains, ["api.example.com"]);
516        assert_eq!(policy.network_mode, NetworkMode::Allowlist);
517    }
518
519    /// An empty `deny_read` is the built-in credential list, not "deny
520    /// nothing"; `allow_read` re-allows on top of it and is not defaulted.
521    #[test]
522    fn an_empty_deny_read_is_the_credential_defaults() {
523        let policy = SandboxSettings::default().policy();
524        assert_eq!(policy.deny_read, default_deny_read());
525        assert!(policy.allow_read.is_empty());
526        if crate::paths::home_dir().is_some() {
527            let joined = policy
528                .deny_read
529                .iter()
530                .map(|p| p.display().to_string())
531                .collect::<Vec<_>>()
532                .join("|");
533            assert!(joined.contains(".ssh") && joined.contains(".aws"));
534        }
535    }
536
537    #[test]
538    fn a_proxy_restricts_the_network_and_the_strict_policy_drops_it() {
539        struct Holds;
540        impl Sandbox for Holds {
541            fn confine(&self, spec: ProcessSpec, _: &SandboxPolicy) -> Confined {
542                Confined {
543                    spec,
544                    mode: SandboxMode::MacOSSandboxExec,
545                    enforcement: Enforcement::Full,
546                    unmet: Vec::new(),
547                }
548            }
549        }
550        let settings = SandboxSettings {
551            network_mode: NetworkMode::Proxy,
552            egress_proxy: Some(EgressProxy {
553                http: "127.0.0.1:3128".parse().unwrap(),
554                socks: None,
555                no_proxy: Vec::new(),
556            }),
557            ..Default::default()
558        };
559        let policy = settings.policy();
560        assert_eq!(policy.egress_proxy, settings.egress_proxy);
561        let strict = policy.strict(Vec::new(), None);
562        assert_eq!(strict.network_mode, NetworkMode::DenyAll);
563        assert!(strict.egress_proxy.is_none());
564        let probe = ProcessSpec::new("bash", Path::new("/work"));
565        let report = ConfinementReport::probe(&Holds, probe, &policy, false, true);
566        assert!(report.network_restricted);
567        assert!(report.holds_unattended());
568    }
569
570    #[test]
571    fn a_disabled_sandbox_confines_neither_commands_nor_the_engines_git() {
572        let settings = SandboxSettings {
573            disabled: true,
574            ..Default::default()
575        };
576        let exec = super::super::ExecProviders::in_process();
577        let report = settings.confinement(&exec, Path::new("/work"), "s");
578        assert_eq!(report, ConfinementReport::disabled(false, false));
579        let git = settings.engine_git(&exec, crate::permission::ProjectTrust::Trusted, None);
580        assert!(!git.is_sandboxed());
581    }
582}