Skip to main content

runtime/tools/exec/
confinement.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4// Copyright (c) 2026 2youg1 and the sprawling contributors
5
6//! The confinement a host command runs under: which arm this machine
7//! gives, and what that arm promises.
8//!
9//! [`crate::sandbox`] is the other half of the execution boundary: a
10//! wasip1 guest that reaches a host directory only when a
11//! [`Mount`](crate::sandbox::Mount) named it, and reaches no network at
12//! all because wasip1 has no way to obtain a socket. A program the agent
13//! asks for is not a guest, so its isolation has to be bought from the
14//! platform, and no platform sells all of it. What this module owns is
15//! therefore a taxonomy rather than a switch: every arm states, axis by
16//! axis, what it keeps and what it does not.
17//!
18//! **An arm that cannot say what it does not hold is worse than no arm.**
19//! The agent reads [`Confinement::statement`] in the exec tool's own
20//! description before it acts; a report that said only "sandboxed" would
21//! send it into a box whose network is open.
22//!
23//! A placement is a copy of the working tree, synced to it before each
24//! command, so a command that ruins it ruins nothing of the person's and
25//! nothing the next command sees. The copy is bounded and lives in
26//! [`placing::copy`](crate::tools::Confinement); a tree over the bound is
27//! refused by name rather than half-copied, because a sandbox that
28//! silently answers for files it did not carry is the failure this
29//! module exists to prevent.
30
31use std::path::PathBuf;
32
33/// One axis a confinement arm can promise, or refuse to promise.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
35pub enum Guarantee {
36    /// Writes through the working directory land on a copy; the tree the
37    /// person has stays as it is.
38    Filesystem,
39    /// The command cannot open a network connection.
40    Network,
41    /// The whole process tree ends when the command ends.
42    ProcessTree,
43    /// The command runs with an identity of its own.
44    User,
45    /// CPU and memory ceilings are enforced, not merely asked for.
46    Resources,
47}
48
49impl Guarantee {
50    /// Every axis, in the order a report lists them.
51    pub const ALL: [Guarantee; 5] = [
52        Guarantee::Filesystem,
53        Guarantee::Network,
54        Guarantee::ProcessTree,
55        Guarantee::User,
56        Guarantee::Resources,
57    ];
58
59    /// What holding this axis means, in the words a sentence shown to a
60    /// caller may use.
61    pub fn phrase(self) -> &'static str {
62        match self {
63            Guarantee::Filesystem => "writes through the working directory land on a copy",
64            Guarantee::Network => "the network is closed",
65            Guarantee::ProcessTree => "the whole process tree ends with the command",
66            Guarantee::User => "the command runs as a user of its own",
67            Guarantee::Resources => "CPU and memory ceilings are enforced",
68        }
69    }
70
71    /// What not holding it means, as the thing the caller does not get.
72    /// Stated as a missing capability rather than as an absence, because
73    /// the list it lands in is a list of what is not bought.
74    pub fn unkept(self) -> &'static str {
75        match self {
76            Guarantee::Filesystem => "that writes land on a copy",
77            Guarantee::Network => "network isolation",
78            Guarantee::ProcessTree => "process-tree containment",
79            Guarantee::User => "a user of its own",
80            Guarantee::Resources => "CPU and memory ceilings",
81        }
82    }
83}
84
85/// Whether one arm keeps one axis.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum Kept {
88    Yes,
89    No,
90}
91
92/// What one arm promises, axis by axis.
93///
94/// Every arm states all five axes, and that is the point of the type: a
95/// new axis is a compile error in every arm's constructor, so no arm can
96/// keep a stale answer to a question that arrived after it was written.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub struct Assurances {
99    pub filesystem: Kept,
100    pub network: Kept,
101    pub process_tree: Kept,
102    pub user: Kept,
103    pub resources: Kept,
104}
105
106impl Assurances {
107    /// The whole list, in the order [`Guarantee::ALL`] declares.
108    pub fn of(self, axis: Guarantee) -> Kept {
109        match axis {
110            Guarantee::Filesystem => self.filesystem,
111            Guarantee::Network => self.network,
112            Guarantee::ProcessTree => self.process_tree,
113            Guarantee::User => self.user,
114            Guarantee::Resources => self.resources,
115        }
116    }
117}
118
119/// What a machine lacks when none of its arms can take a command at all.
120///
121/// A name, never a sentence: a page supplies the words, and a machine
122/// that lacks something else gets an arm here rather than a second
123/// string field no reader can match on.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum Missing {
126    /// A writable directory a working tree can be copied into.
127    ScratchDirectory,
128}
129
130impl Missing {
131    /// The thing itself, for a refusal's subject.
132    pub fn phrase(self) -> &'static str {
133        match self {
134            Missing::ScratchDirectory => "a writable scratch directory",
135        }
136    }
137
138    /// What a person does about it.
139    pub fn recovery(self) -> &'static str {
140        match self {
141            Missing::ScratchDirectory => {
142                "point TMPDIR (TEMP on Windows) at a directory this process can write, \
143                 and start sprawling again"
144            }
145        }
146    }
147}
148
149/// The backends, by platform, each carrying what it promises.
150///
151/// `WindowsJobObject` is the arm a Windows machine with a job-object
152/// enforcer compiled in would report. No build of this crate constructs
153/// one, because `CreateJobObject` is a foreign call the workspace
154/// forbids outside `crates/desktop/`; a Windows machine therefore reports
155/// [`Confinement::CopiedTree`], whose [`Assurances`] say what it does
156/// not hold (the network, above all) rather than implying it holds
157/// everything a job object would.
158#[derive(Debug, Clone, PartialEq, Eq)]
159pub enum Confinement {
160    /// Namespaces of its own — mount, network, process, user — made by a
161    /// wrapper program on this machine.
162    LinuxNamespaces { wrapper: PathBuf },
163    /// A Windows job object: the tree ends together, the limits hold,
164    /// and the network is not isolated.
165    WindowsJobObject,
166    /// The floor every platform has: the command runs in a copy of the
167    /// working tree, and the tree itself is not what it writes to.
168    CopiedTree,
169    /// No arm at all, and what this machine is missing.
170    Unavailable { missing: Missing },
171}
172
173impl Confinement {
174    /// The arm this machine gives a command. One sampling point: the
175    /// scratch root, the search path and this platform are asked here
176    /// and nowhere else, so a report and a placement cannot disagree.
177    pub fn detect() -> Confinement {
178        Confinement::choose(&Offerings::this_machine())
179    }
180
181    /// The arm a machine with these capabilities gives.
182    pub fn choose(offered: &Offerings) -> Confinement {
183        if offered.scratch.is_none() {
184            return Confinement::Unavailable {
185                missing: Missing::ScratchDirectory,
186            };
187        }
188        match &offered.namespace_tool {
189            Some(wrapper) => Confinement::LinuxNamespaces {
190                wrapper: wrapper.clone(),
191            },
192            None => Confinement::CopiedTree,
193        }
194    }
195
196    /// What this arm promises. A pure function of the arm, so a report
197    /// can be read without running anything.
198    pub fn assurances(&self) -> Assurances {
199        let all = Kept::Yes;
200        let none = Kept::No;
201        match self {
202            Confinement::LinuxNamespaces { .. } => Assurances {
203                filesystem: all,
204                network: all,
205                process_tree: all,
206                user: all,
207                resources: none,
208            },
209            Confinement::WindowsJobObject => Assurances {
210                filesystem: all,
211                network: none,
212                process_tree: all,
213                user: none,
214                resources: all,
215            },
216            Confinement::CopiedTree => Assurances {
217                filesystem: all,
218                network: none,
219                process_tree: none,
220                user: none,
221                resources: none,
222            },
223            Confinement::Unavailable { .. } => Assurances {
224                filesystem: none,
225                network: none,
226                process_tree: none,
227                user: none,
228                resources: none,
229            },
230        }
231    }
232
233    /// The name a report carries. Closed and spelled once, because a
234    /// page, a refusal and a test all have to mean the same arm.
235    pub fn name(&self) -> &'static str {
236        match self {
237            Confinement::LinuxNamespaces { .. } => "linux_namespaces",
238            Confinement::WindowsJobObject => "windows_job_object",
239            Confinement::CopiedTree => "copied_tree",
240            Confinement::Unavailable { .. } => "unavailable",
241        }
242    }
243
244    /// What a command under this arm can and cannot count on, in one
245    /// sentence. Derived from [`Confinement::assurances`] rather than
246    /// written beside it, so the sentence cannot drift from the type.
247    pub fn statement(&self) -> String {
248        match self {
249            Confinement::Unavailable { missing } => {
250                format!("no sandbox is available: {}", missing.phrase())
251            }
252            Confinement::LinuxNamespaces { .. }
253            | Confinement::WindowsJobObject
254            | Confinement::CopiedTree => {
255                let kept = self.assurances();
256                let holds: Vec<&str> = Guarantee::ALL
257                    .iter()
258                    .filter(|axis| kept.of(**axis) == Kept::Yes)
259                    .map(|axis| axis.phrase())
260                    .collect();
261                let misses: Vec<&str> = Guarantee::ALL
262                    .iter()
263                    .filter(|axis| kept.of(**axis) == Kept::No)
264                    .map(|axis| axis.unkept())
265                    .collect();
266                format!(
267                    "{}: it guarantees that {}; it does not guarantee: {}.",
268                    self.name(),
269                    listed(&holds),
270                    listed(&misses)
271                )
272            }
273        }
274    }
275}
276
277/// What a machine has, read once and handed to [`Confinement::choose`]
278/// so that a test states a machine instead of borrowing one.
279#[derive(Debug, Clone, PartialEq, Eq)]
280pub struct Offerings {
281    /// The program that makes this machine's own isolation, where one
282    /// exists.
283    pub namespace_tool: Option<PathBuf>,
284    /// A writable directory a working tree can be copied into.
285    pub scratch: Option<PathBuf>,
286}
287
288impl Offerings {
289    /// Reads this machine: whether the platform's wrapper program is on
290    /// the search path, and whether the scratch root exists.
291    pub fn this_machine() -> Offerings {
292        let scratch = std::env::temp_dir();
293        Offerings {
294            namespace_tool: namespace_wrapper(),
295            scratch: scratch.is_dir().then_some(scratch),
296        }
297    }
298}
299
300/// The wrapper that gives a Linux command namespaces of its own.
301///
302/// One program, looked up by its exact name, because the arm it makes
303/// exists on Linux alone: a search path walked here is not a second
304/// authority on which programs a machine has — the doctor's requirement
305/// table is that — it is the question of whether *this* arm can be
306/// given at all.
307fn namespace_wrapper() -> Option<PathBuf> {
308    if !cfg!(target_os = "linux") {
309        return None;
310    }
311    let path = std::env::var_os("PATH")?;
312    std::env::split_paths(&path)
313        .map(|dir| dir.join("bwrap"))
314        .find(|candidate| candidate.is_file())
315}
316
317/// A list in the shape a sentence uses: `a`, `a and b`, `a, b and c`.
318fn listed(parts: &[&str]) -> String {
319    match parts {
320        [] => "nothing".to_owned(),
321        [one] => (*one).to_owned(),
322        [one, two] => format!("{one} and {two}"),
323        [first @ .., last] => format!("{}, and {last}", first.join(", ")),
324    }
325}
326
327mod placing;
328
329pub use placing::{Confined, Placed, Placement, parse_placement};
330
331#[cfg(test)]
332#[allow(
333    clippy::unwrap_used,
334    clippy::expect_used,
335    clippy::panic,
336    clippy::indexing_slicing,
337    clippy::arithmetic_side_effects,
338    reason = "test code"
339)]
340mod tests;