platform/sandbox/mod.rs
1//! The platform sandbox backends, macOS `sandbox-exec` and Linux `bubblewrap`: each
2//! confines a command for a [`SandboxPolicy`] and reports what it delivered as `Enforcement`.
3//! The policy follows the call's `ExecProfile` (`tools::bash::sandbox`): Session is the
4//! session's; Unattended adds `deny_ipc_escapes`; Strict (`SandboxPolicy::strict`) cuts the
5//! network, writes only `TMPDIR`, reads only its roots (`ReadScope::Only`), env `Minimal`.
6//!
7//! - **macOS**: `sandbox-exec -p <profile> <program> <args…>`. The profile is
8//! TinyScheme denying writes outside the allowed subtrees; exec is not
9//! restricted; under `ReadScope::Only` reads are denied but under each root.
10//! Network defaults to open; `DenyAll` / `Allowlist` both use
11//! `(deny network*)`. A profile names a remote host only as `*` or
12//! `localhost`, so the allowlist re-allows localhost when it names it and
13//! no domain at all; the domains it names are reported unmet through
14//! `Enforcement`, as on Linux. `Proxy` re-allows only the proxy's ports on
15//! `localhost` (which covers `127.0.0.1` and `::1`); a proxy off this
16//! machine can be held only to its port, on any host, and is reported
17//! unmet. Name resolution goes through `mDNSResponder`'s unix socket, which
18//! `(deny network*)` covers (measured on macOS 26).
19//! - **Linux**: `bwrap --ro-bind / / --bind <writable> <writable> … <program>`
20//! (`ReadScope::Only`: a read-only bind per root). No bwrap: no constraint. `DenyAll` uses
21//! `--unshare-net`; bwrap has no domain-level filter, so `Allowlist`
22//! degrades to the same whole-network cut rather than silently opening up —
23//! failure goes toward the safer side, and says so through `Enforcement`.
24//! `Proxy` cuts the network too, then binds a unix socket into the
25//! namespace that this process forwards to the proxy (`egress::relay`),
26//! and a `socat` started inside listens on the namespace's
27//! `127.0.0.1:<proxy port>` and connects to it. Without `socat` in the
28//! system directories the network stays cut, reported unmet.
29//! Each command gets a PID namespace of its own, so the pids it sees (`$!`
30//! among them) are not the host's, and a later command does not see what an
31//! earlier one left running. What it left running outlives it, as on macOS.
32//! - **Windows**: no backend.
33//!
34//! # What a confined command may write
35//!
36//! The working directory, the policy's `additional_writable` (the caller puts
37//! the session's own `TMPDIR` there), `/dev`, and on macOS the user's
38//! `DARWIN_USER_TEMP_DIR`, which `mktemp(1)` uses whatever `TMPDIR` says. On
39//! Linux `/tmp` is a private tmpfs that goes away with the command. Every path
40//! is resolved through its symlinks before a rule is written for it.
41//!
42//! Inside those, what the engine or git later acts on outside the sandbox is
43//! read-only — where the policy names a `worktree_git` (the working
44//! directory is a linked worktree), `.git` below means its git directory,
45//! never one found by following the worktree's links: the
46//! project's `.git`, `.agix` and `.claude` entries themselves,
47//! `.git/{config,config.worktree,commondir}` and `.git/hooks/`, the hooks directory
48//! `core.hooksPath` names and the files `.git/config` includes, the same in
49//! the git directory of every submodule under `.git/modules/` (nested ones
50//! included, and the directories leading down to them), the
51//! instance's own project directory but its working entries —
52//! `state/scratchpad/` and `state/memory/`, all the gate leaves out of
53//! configuration there (`base::paths::ConfigRootAt::writable_state_entry`) —
54//! with its configuration (`base::paths::ENGINE_CONFIG_*`: settings, MCP,
55//! hooks, commands, agents, skills, plugins, rules, scenes, policy, scripts,
56//! output styles), what in `state/` the engine exports, forks and resumes
57//! from (`base::paths::PROJECT_STATE_ENGINE_DIRS`: saved tool results,
58//! history) and the embedder's `state/<product id>/` read-only even inside a
59//! writable root the policy names there, all of a foreign configuration root
60//! (`.claude`, and `.agix` under a renamed layout), and in either the
61//! writable roots the policy names inside it stay writable, the project's skills (`.agents/skills/`,
62//! `base::paths::PROJECT_ENGINE_CONFIG_DIRS`, and the `.agents` entry above
63//! it), the control files of each linked worktree's entry under
64//! `.git/worktrees/` (`base::paths::GIT_WORKTREE_CONTROL_FILES`), and the
65//! `.git` links of the engine's worktrees (in the project's worktrees
66//! directories, `.wkts/` unless the settings name another —
67//! `base::paths::SensitivePaths::worktree_dirs_in`) — the last two for a
68//! worktree made after the command started as well, so that what it leaves
69//! running cannot rewrite those of a sub-agent's worktree made later: macOS
70//! by pattern, with the worktrees directory and each worktree directly in it
71//! held in place, Linux by holding `.git/worktrees/` (made, empty, where it
72//! is absent) and the worktrees directory read-only with the worktrees
73//! already in it opened again. A command therefore cannot add a worktree of
74//! its own, nor move one aside to rewrite its link. Under
75//! `only_additional_writable`, the engine's own git, which adds them, is held
76//! only to the ones that exist.
77//! A command in a linked worktree writes of its git directory only what
78//! `additional_writable` names (`base::paths::WorktreeGit::writable`): the
79//! object store but its `objects/info/`, its own entry under `worktrees/`
80//! with an absent control file there shut too (on Linux by an empty file),
81//! and its branch's ref, lock and reflog. On Linux the ref is opened as the
82//! directory it is in — git renames `<ref>.lock` over it, which a bind of the
83//! file refuses — with the other entries there read-only again, and the git
84//! directory is bound read-only beneath, so that `/tmp` does not hide it.
85//! Of the state root only `scratchpad/`, `memory/` and those of
86//! `additional_writable` under `tmp/` (a session's own `TMPDIR`) stay
87//! writable. A project that lives in the state root lifts that fence; the
88//! state root is then guarded as the `.agix` it is — its configuration files
89//! and directories are read-only, but for one the project itself is in —
90//! and the settings and definitions of the root and every scene stay
91//! read-only either way. On Linux the own project directory and each
92//! foreign root is read-only as a whole and the own one's existing working
93//! entries are opened again, so a new entry directly in either cannot be
94//! created; `.agents/skills/` is read-only. A foreign root, `.agents` or
95//! `.agents/skills` that is not there (or is an empty directory) is shut
96//! under an empty read-only tmpfs, and the mount point bwrap makes for it is
97//! removed again once no sandboxed command's namespace lives in the project
98//! — not when bwrap exits, which can be before what the command left behind
99//! (`linux::bwrap_stdio_outside`); the own directory's stays, as the
100//! engine's own.
101//!
102//! A policy with `only_additional_writable` leaves out the working directory,
103//! the state root's working entries and `DARWIN_USER_TEMP_DIR`: only
104//! `additional_writable` and `/dev` are writable, the read-only entries above
105//! still apply inside them. The engine's own git runs under such a policy in
106//! every session whose commands are sandboxed (`base::engine_exec`), so a
107//! filter driver or other program a repository's configuration names runs
108//! confined, writing at most the git directory and the worktrees directory
109//! when it creates a worktree, and only the session's `TMPDIR` otherwise.
110//!
111//! # What a confined command may not read
112//!
113//! The policy's `deny_read` (the credential stores in the user's home, by
114//! default) less its `allow_read`, with the targets of the links in a
115//! denied directory that lead out of it; its `deny_read_exact` (what the
116//! session's `Read` deny rules name) whatever `allow_read` says, each path
117//! as named, no link in it followed; and whatever the policy says, the
118//! credentials of `base::paths` (`CREDENTIALS`, placed on disk by
119//! `SensitivePaths::credential_locations`): the state root's settings files
120//! and MCP OAuth tokens, its own and every scene's, the daemons' socket
121//! tokens under `daemon/auth/`, and the project's `.agix/settings.local.json`
122//! and `.agix/mcp.local.json`. The state root's are also those of each of
123//! the policy's `foreign_state_roots` — another instance's on this machine,
124//! such as `~/.agix` seen from an embedder's `data_root` — none of which a
125//! command can write in either, unless the working directory is inside it.
126//! macOS writes a pattern for each; Linux covers the state roots and the
127//! project's `.agix` with the mounts of `mask::mask_plan`, which a credential
128//! written later does not climb out of, except where escape path 6 says; a
129//! foreign state root's tmpfs is read-only.
130//!
131//! On Linux a denied directory is shut under an empty read-only tmpfs, so a
132//! command can neither read nor write in it; macOS denies reads only.
133//!
134//! A policy whose `read` is `ReadScope::Only` narrows that further
135//! (`read_scope`).
136//!
137//! # What a confined command may not connect to
138//!
139//! The daemon it runs under: a command connected to the daemon's socket would
140//! be its host, free to add an MCP server that runs outside the sandbox, trust
141//! its own project or answer its own permission prompts. So under every
142//! policy, network open or not, a command cannot connect to a unix socket in
143//! the state root (unless the project lives there), in a foreign state root,
144//! or to one this process serves ([`fence_socket`], wherever `--socket` put
145//! it). macOS refuses the
146//! connect, by resolved path; Linux mounts `/dev/null` over the socket — over
147//! each one in a state root and its scene directories, not the directories
148//! themselves, which stay readable. macOS also refuses this process's TCP
149//! and WebSocket ports ([`fence_port`]); on Linux only `--unshare-net` cuts
150//! them off, and the egress relay will not forward to one. Under `Proxy` both
151//! backends set the command's `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY` and
152//! `NO_PROXY`, in both cases, over what it inherits. The daemon refuses its own descendants on the unix socket as
153//! well, which is what holds where no backend runs.
154//!
155//! **Behind the `sandbox` feature: off here, on in assembly and the daemon.** What it
156//! constrains is the commands the *model* runs, which is defence in depth on a
157//! machine whose owner is sitting at it and a boundary only where the agent
158//! acts for someone else. Without the feature the backends are not compiled,
159//! [`PlatformSandbox`] says so, and `sandbox.require` refuses every
160//! command rather than running it unconstrained — which is the same promise the
161//! enforcement report always made, kept one step earlier.
162//!
163//! # Known escape paths
164//!
165//! This is a lightweight write restriction, not a security boundary. Known
166//! ways out:
167//!
168//! 1. **Writable `/dev`**: the macOS profile allows `file-write*` to `/dev`,
169//! so a process can `mknod` a raw disk device and bypass file ACLs.
170//! 2. **Inherited environment**: `LD_PRELOAD` / `DYLD_INSERT_LIBRARIES` are
171//! not cleared, so a dynamic library can be injected.
172//! 3. **Absent git files on Linux, for a git outside the sandbox**: a mount
173//! cannot stand in for a file that does not exist without leaving an empty
174//! one behind, which git refuses to read. So a project with no `.git` yet
175//! can be given one, and a repository with no `commondir` can be given one,
176//! with whatever configuration and filter drivers the command likes. The
177//! engine's own git runs inside the sandbox, so it carries none of that out
178//! unconfined; a git the user runs in the project afterwards does. macOS
179//! denies both.
180//! 4. **Another process acting for the command**: the sandbox follows the
181//! command's own process tree, not what it asks a system service to do.
182//! On macOS, measured against `sandbox-exec`: `open` has LaunchServices
183//! start an app outside the sandbox, `defaults write` has `cfprefsd` write
184//! any preference domain, and an Apple event reaches an app that runs
185//! unconfined (Finder itself refuses events from a sandboxed sender, other
186//! apps need not). launchd refuses `launchctl submit` / `bootstrap` from a
187//! sandboxed caller. A policy with `deny_ipc_escapes` — every unattended
188//! session's — denies `lsopen`, `user-preference-write` and
189//! `appleevent-send`, the keychain through `com.apple.SecurityServer`
190//! (what `security find-generic-password` asks), and the sockets of the
191//! user's tmux and screen sessions. On Linux the same policy adds
192//! `--unshare-ipc` and hides the session bus and the systemd user
193//! manager's socket under `$XDG_RUNTIME_DIR` (and the bus path
194//! `DBUS_SESSION_BUS_ADDRESS` names), so `systemd-run --user` has nothing
195//! to talk to, and screen's socket directory (tmux's is in `/tmp`, private
196//! already); an abstract-socket bus is reachable unless the network is cut
197//! too. A multiplexer on a socket of its own choosing (`tmux -S`) is not
198//! found. With the network open, any local
199//! service listening on a socket the command can reach (sshd, a container
200//! daemon) is a way out under every policy.
201//! 5. **A nested repository planted in the project**: the guard protects the
202//! project's own `.git`, but a command can `git init` a repository in a
203//! subdirectory, write its `.git/config` (`core.fsmonitor` and the like)
204//! and `git add` it into the project's index as a gitlink. The user's own
205//! `git` in the project afterwards, outside the sandbox, enters it and runs
206//! what its configuration names. Neither backend stops this: refusing to
207//! create a `.git` entry would break `git init`, `git clone` and every
208//! package manager that checks out a git dependency, and a repository built
209//! elsewhere and moved in would evade it anyway. The engine's own `git`
210//! carries `-c core.fsmonitor=false` and is unaffected. Above the backends,
211//! the runtime looks for one after every command not held to the strict
212//! profile (`tools::nested_repos`; a background command when its task
213//! ends): an undeclared gitlink whose configuration names a program has its
214//! `.git` moved aside unless the person attending keeps it. What it does
215//! not catch is what a command starts that outlives it and plants one
216//! later.
217//! 6. **A credential written later directly into a writable directory, on
218//! Linux**: a `/dev/null` bind is pinned to the file there at wrap time, so
219//! a key file the engine creates afterwards, or rename-writes over the old
220//! one, is readable by what a command left running. A tmpfs over the
221//! directory would close this, and swallow every new entry the project
222//! makes in it. That is the state root's own key files, and `daemon/auth`
223//! while it does not exist, when the project is the state root; a scene's
224//! key files, and its `mcp/oauth` while it does not exist, when the
225//! project is that scene directory; and the key files of a project whose
226//! `.agix` is a symbolic link. What lies outside the project, the
227//! configuration directories a command cannot write anyway and a real
228//! `.agix` directory are masked whole. macOS matches its denials by path
229//! and has no such gap.
230//! 7. **A `deny_read` entry inside a writable directory, on macOS**: matched
231//! by path, so a command that may write the directory renames the file,
232//! or a directory above it, and reads it under the new name. The
233//! `Read(...)` deny rules in `deny_read_exact` mostly name files in the
234//! project, which is writable. On Linux the entry is a mount, which a
235//! rename does not carry off.
236//!
237//! Not among them, measured on bubblewrap 0.8: `/proc` is mounted afresh for
238//! the command's PID namespace, so it shows neither the host's processes nor
239//! their `fd` and `root`; a command inherits no descriptor of the daemon's but
240//! its stdio, the daemon opening every one close-on-exec; and it has no
241//! controlling terminal to push input into through `/dev/tty`, since
242//! `LocalProcess` starts it in a session of its own.
243
244pub use base::interface::exec::{
245 default_deny_read, default_deny_read_in, Confined, EgressProxy, Enforcement, EnvScope,
246 NetworkMode, ProcessSpec, ReadScope, Sandbox, SandboxMode, SandboxPolicy,
247};
248use std::path::{Path, PathBuf};
249
250#[cfg(all(feature = "sandbox", any(target_os = "macos", target_os = "linux")))]
251mod egress;
252mod fence;
253#[cfg(all(feature = "sandbox", target_os = "linux"))]
254mod linux;
255#[cfg(all(feature = "sandbox", target_os = "macos"))]
256mod macos;
257#[cfg(feature = "sandbox")]
258#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
259mod mask;
260#[cfg(all(feature = "sandbox", target_os = "macos"))]
261mod patterns;
262#[cfg(all(feature = "sandbox", any(target_os = "macos", target_os = "linux")))]
263mod read_scope;
264#[cfg(feature = "sandbox")]
265mod roots;
266#[cfg(test)]
267mod tests;
268
269pub use fence::{fence_port, fence_secret, fence_socket, Fence};
270
271/// The system directories programs load from: what a command reads to
272/// start at all, and what `ReadScope::Only` lets it read whatever its roots.
273#[cfg(target_os = "macos")]
274const SYSTEM_READ_ROOTS: &[&str] = &[
275 "/usr",
276 "/bin",
277 "/sbin",
278 "/System",
279 "/Library/Developer/CommandLineTools",
280 "/Applications/Xcode.app/Contents/Developer",
281 "/private/etc",
282 "/private/var/db/timezone",
283 "/opt/homebrew",
284 "/usr/local",
285 "/dev",
286];
287
288#[cfg(target_os = "linux")]
289const SYSTEM_READ_ROOTS: &[&str] = &[
290 "/usr",
291 "/bin",
292 "/sbin",
293 "/lib",
294 "/lib32",
295 "/lib64",
296 "/libx32",
297 "/etc",
298 "/opt",
299 "/nix/store",
300];
301
302#[cfg(not(any(target_os = "macos", target_os = "linux")))]
303const SYSTEM_READ_ROOTS: &[&str] = &[];
304
305pub fn system_read_roots() -> Vec<PathBuf> {
306 SYSTEM_READ_ROOTS.iter().map(PathBuf::from).collect()
307}
308
309/// Where a confined command may write besides its working directory and the
310/// policy's `additional_writable`: device nodes, and on macOS the per-user
311/// temporary directory, where mktemp(1) creates its file whatever `TMPDIR`
312/// says — without it every script calling a bare `mktemp` fails. That one is
313/// left out when only the named roots are writable.
314pub fn implicit_writable_roots(only_additional: bool) -> Vec<PathBuf> {
315 #[cfg_attr(not(all(feature = "sandbox", target_os = "macos")), allow(unused_mut))]
316 let mut roots = vec![PathBuf::from("/dev")];
317 #[cfg(all(feature = "sandbox", target_os = "macos"))]
318 if !only_additional {
319 roots.extend(macos::darwin_user_temp_dir());
320 }
321 #[cfg(not(all(feature = "sandbox", target_os = "macos")))]
322 let _ = only_additional;
323 roots
324}
325
326#[derive(Debug, Clone)]
327pub struct SandboxOptions<'a> {
328 pub command: &'a str,
329 pub cwd: &'a Path,
330 pub additional_writable: &'a [PathBuf],
331 pub disable: bool,
332 /// Extended policy (deny-read, network mode, etc).
333 /// Falls back to safe defaults via `SandboxPolicy::default()`.
334 pub policy: SandboxPolicy,
335}
336
337/// Pick the platform backend and wrap the command.
338///
339/// Never fails: no available backend means no constraint, reported honestly
340/// through [`Enforcement`] rather than by refusing here. Whether an
341/// unconstrained run is acceptable is the caller's decision, not this
342/// function's.
343pub fn wrap(opts: SandboxOptions<'_>) -> Confined {
344 let inner = bash_spec(opts.command);
345 if opts.disable {
346 return plain(inner, SandboxMode::Disabled);
347 }
348 let env = CommandEnv {
349 set: &[],
350 scope: opts.policy.env,
351 };
352 wrap_program(inner, opts.cwd, opts.additional_writable, &opts.policy, env)
353}
354
355/// The environment a confined program starts with, as far as the sandbox can
356/// tell: what its spec sets, over what `scope` lets it inherit from the
357/// daemon's.
358#[derive(Debug, Clone, Copy)]
359#[cfg_attr(
360 not(all(feature = "sandbox", any(target_os = "macos", target_os = "linux"))),
361 allow(dead_code)
362)]
363struct CommandEnv<'a> {
364 set: &'a [(String, String)],
365 scope: EnvScope,
366}
367
368/// [`wrap`] for any program, not only a shell command.
369#[cfg_attr(
370 not(all(feature = "sandbox", any(target_os = "macos", target_os = "linux"))),
371 allow(unused_variables)
372)]
373fn wrap_program(
374 inner: ProcessSpec,
375 cwd: &Path,
376 additional_writable: &[PathBuf],
377 policy: &SandboxPolicy,
378 env: CommandEnv<'_>,
379) -> Confined {
380 #[cfg(not(feature = "sandbox"))]
381 {
382 unavailable(
383 inner,
384 "this build has no sandbox backend; rebuild with `--features sandbox`",
385 )
386 }
387
388 #[cfg(feature = "sandbox")]
389 {
390 if let Some(odd) = non_utf8_path(cwd, additional_writable, policy) {
391 return Confined {
392 spec: inner,
393 unmet: vec![format!(
394 "{} is not valid UTF-8, which a sandbox profile cannot name",
395 odd.display()
396 )],
397 mode: SandboxMode::Unavailable,
398 enforcement: Enforcement::None,
399 };
400 }
401 #[cfg(target_os = "macos")]
402 {
403 macos::mac_wrap(inner, cwd, additional_writable, policy, env)
404 }
405
406 #[cfg(target_os = "linux")]
407 {
408 linux::linux_wrap(inner, cwd, additional_writable, policy, env)
409 }
410
411 // Windows / other unsupported platforms
412 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
413 {
414 plain(inner, SandboxMode::Unavailable)
415 }
416 }
417}
418
419/// The first path of the call that is not UTF-8. Profiles and bwrap
420/// arguments are text: such a path would be written lossily, as one that
421/// does not exist.
422#[cfg(feature = "sandbox")]
423fn non_utf8_path<'a>(
424 cwd: &'a Path,
425 additional_writable: &'a [PathBuf],
426 policy: &'a SandboxPolicy,
427) -> Option<&'a Path> {
428 let roots = match &policy.read {
429 ReadScope::Everything => &[][..],
430 ReadScope::Only(roots) => roots,
431 };
432 std::iter::once(cwd)
433 .chain(additional_writable.iter().map(PathBuf::as_path))
434 .chain(policy.additional_writable.iter().map(PathBuf::as_path))
435 .chain(policy.deny_read.iter().map(PathBuf::as_path))
436 .chain(policy.deny_read_exact.iter().map(PathBuf::as_path))
437 .chain(policy.allow_read.iter().map(PathBuf::as_path))
438 .chain(policy.state_root.iter().map(PathBuf::as_path))
439 .chain(roots.iter().map(PathBuf::as_path))
440 .find(|p| p.to_str().is_none())
441}
442
443/// A command nothing wrapped, and the reason in words the operator can act on.
444#[cfg(not(feature = "sandbox"))]
445fn unavailable(inner: ProcessSpec, why: &str) -> Confined {
446 Confined {
447 spec: inner,
448 unmet: vec![why.to_string()],
449 mode: SandboxMode::Unavailable,
450 enforcement: Enforcement::None,
451 }
452}
453
454fn plain(inner: ProcessSpec, mode: SandboxMode) -> Confined {
455 Confined {
456 spec: inner,
457 unmet: vec!["nothing is constrained".into()],
458 mode,
459 // Nothing wraps this command, so nothing constrains it — true whether
460 // the user asked for no sandbox or the platform could not provide one.
461 // Which of those it was is `mode`'s job to say.
462 enforcement: Enforcement::None,
463 }
464}
465
466/// macOS sandbox-exec 的 TinyScheme 字符串里 `\` 和 `"` 要转义。
467///
468/// 只有 macOS 的配置生成器调用它,但函数本身和平台无关——它的测试在哪个平台上
469/// 都该跑,所以这里没有跟着调用方一起 `cfg` 掉,而是只在别的平台上豁免"未使用"。
470#[cfg(feature = "sandbox")]
471#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
472fn sandbox_escape(s: &str) -> String {
473 s.replace('\\', "\\\\").replace('"', "\\\"")
474}
475
476/// Where the terminal multiplexers this user runs listen. Typing into one of
477/// their sessions runs a command in a shell outside the sandbox.
478#[cfg(all(feature = "sandbox", any(target_os = "macos", target_os = "linux")))]
479fn multiplexer_paths() -> Vec<PathBuf> {
480 let uid = unsafe { libc::getuid() };
481 let tmux_dir = format!("tmux-{uid}");
482 let var = |name: &str| {
483 std::env::var_os(name)
484 .filter(|v| !v.is_empty())
485 .map(PathBuf::from)
486 };
487 let mut paths: Vec<PathBuf> = if cfg!(target_os = "macos") {
488 vec![
489 Path::new("/private/tmp").join(&tmux_dir),
490 "/private/tmp/screens".into(),
491 ]
492 } else {
493 vec!["/run/screen".into(), "/var/run/screen".into()]
494 };
495 paths.extend(var("TMUX_TMPDIR").map(|d| d.join(&tmux_dir)));
496 paths.extend(var("SCREENDIR"));
497 // `$TMUX` is `<socket>,<server pid>,<session>`.
498 if let Ok(tmux) = std::env::var("TMUX") {
499 paths.extend(
500 tmux.split(',')
501 .next()
502 .filter(|s| !s.is_empty())
503 .map(PathBuf::from),
504 );
505 }
506 let mut paths: Vec<PathBuf> = paths
507 .iter()
508 .map(|p| base::path::resolve_physically(p))
509 .collect();
510 paths.sort();
511 paths.dedup();
512 paths
513}
514
515/// A shell command as a process spec. The one place `bash -c` is spelled, so
516/// that every backend wraps the same thing.
517fn bash_spec(command: &str) -> ProcessSpec {
518 ProcessSpec::new("bash", std::path::Path::new("."))
519 .args(["-c".to_string(), command.to_string()])
520}
521
522/// The platform backends behind the contract.
523///
524/// Holds nothing: which backend applies is a fact about the machine, decided
525/// per call by `cfg`, and the policy arrives as an argument.
526pub struct PlatformSandbox;
527
528impl Sandbox for PlatformSandbox {
529 fn confine(&self, spec: ProcessSpec, policy: &SandboxPolicy) -> Confined {
530 let ProcessSpec {
531 program,
532 args,
533 cwd,
534 env,
535 env_scope,
536 stdin,
537 } = spec;
538 let inner = ProcessSpec::new(program, Path::new(".")).args(args);
539 let env_scope = match policy.env {
540 EnvScope::Minimal => EnvScope::Minimal,
541 EnvScope::Session => env_scope,
542 };
543 let seen = CommandEnv {
544 set: &env,
545 scope: env_scope,
546 };
547 let mut confined = wrap_program(inner, &cwd, &policy.additional_writable, policy, seen);
548 #[cfg(all(feature = "sandbox", any(target_os = "macos", target_os = "linux")))]
549 if matches!(
550 confined.mode,
551 SandboxMode::MacOSSandboxExec | SandboxMode::LinuxBwrap
552 ) {
553 let unmet = read_scope::unmet(
554 &policy.read,
555 &read_scope::UserDirs::of(seen),
556 read_scope::var(seen, "PATH").as_deref(),
557 );
558 if !unmet.is_empty() {
559 confined.unmet.extend(unmet);
560 confined.enforcement = Enforcement::Partial;
561 }
562 }
563 confined.spec.cwd = cwd;
564 let backend_env = std::mem::replace(&mut confined.spec.env, env);
565 confined.spec.env.extend(backend_env);
566 confined.spec.env_scope = env_scope;
567 confined.spec.stdin = stdin;
568 confined
569 }
570}
571
572/// 一行可读的沙盒可用性描述,给 `/doctor` 用。
573/// macOS:恒"available: sandbox-exec"(系统自带)。
574/// Linux:bwrap 在 PATH 时 available;否则报 unavailable + 提示装。
575/// 其它平台:unavailable + 平台名。
576pub fn sandbox_status() -> String {
577 #[cfg(not(feature = "sandbox"))]
578 {
579 "unavailable: this build has no sandbox backend (`--features sandbox`)".to_string()
580 }
581 #[cfg(all(feature = "sandbox", target_os = "macos"))]
582 {
583 "available: sandbox-exec".to_string()
584 }
585 #[cfg(all(feature = "sandbox", target_os = "linux"))]
586 {
587 if linux::bwrap_available() {
588 "available: bwrap".to_string()
589 } else {
590 "unavailable: bwrap not in PATH (install bubblewrap)".to_string()
591 }
592 }
593 #[cfg(all(
594 feature = "sandbox",
595 not(any(target_os = "macos", target_os = "linux"))
596 ))]
597 {
598 format!("unavailable on {}", std::env::consts::OS)
599 }
600}