Skip to main content

capsule_runtime/
staged_runtime.rs

1//! `capabilities.shell.staged_runtime`: staging a pinned host runtime tree into a capsule root.
2//!
3//! ## The mechanism, and why it is the inverse of `interpreter_runtime`
4//!
5//! A path-based interpreter — CPython above all — cannot run from an allowlisted binary alone. Its
6//! stdlib lives outside the workdir, at a path the `DT_NEEDED` closure cannot discover, so
7//! *something* has to make that tree reachable. There are exactly two ways to do it:
8//!
9//!   * [`crate::sandbox`]'s `interpreter_runtime` grants widen the capsule's Landlock scope
10//!     *outwards*, so the host's `/usr/lib/python3.11` stays readable from inside. That works at
11//!     `scoped`, and it costs: the capsule is now coupled to one host's directory layout, host
12//!     paths stay reachable, and moving to a second host with a different Python build silently
13//!     changes what the capsule runs. This is why declaring one fires `W-SEC-009`.
14//!   * `staged_runtime` moves the tree *inwards*. A `sealed` capsule already builds a composed
15//!     root out of read-only binds ([`crate::sealed`]); staging adds one more bind, of an
16//!     operator-named, operator-pinned runtime tree, at the same absolute path it has on the host.
17//!     Nothing outside the root becomes reachable, and the `pin` makes "the same interpreter on
18//!     both hosts" a claim a human can check rather than assume.
19//!
20//! The second supersedes the first for any binary that uses it, which is why the manifest parser
21//! refuses both for one binary rather than merging them (see `parse_staged_runtime` in
22//! `murmur-artifact`). Staging is not an additional grant layered onto a widened scope; it is the
23//! thing that makes widening unnecessary.
24//!
25//! ## What this module contains, and how the mount reaches the launch path
26//!
27//! Two independent pieces, with very different reach:
28//!
29//!   * [`check_staged_runtime_floor`] — pure, every OS, and **live in the launch path**. It is the
30//!     gate that refuses to stage a capsule declaring `staged_runtime` below an effective `sealed`
31//!     floor, called from `runtime::stage_session` next to `check_containment_floor`.
32//!   * [`bind_mount_staged_runtimes`] — Linux-only, and the executable statement of the mount
33//!     *contract*: the re-basing rule, the two-call read-only bind, and the failure taxonomy. It
34//!     is built and proven here in isolation, against a throwaway directory tree inside a mount
35//!     namespace its own test creates.
36//!
37//! The staging mounts **are** performed on every `sealed` launch that declares a grant — but not
38//! by calling that function. `sandbox::resolve_staged_runtime_dirs` collects each grant's
39//! `source_path` into `ShellEnforcement::staged_runtime_dirs`, `build_sealed_root` passes them to
40//! [`crate::sealed::plan_composed_root`]'s `staged_runtime_read_only` parameter, and they are
41//! planned as *required* `RootOp::Bind` steps ahead of every other step — and so ahead of
42//! `pivot_root`. A grant whose source is missing fails at the real `mount(2)` with `ENOENT`,
43//! aborting the construction; that reaches the operator as
44//! `RuntimeError::SealedRootConstructionFailed` (`E-RUN-014`) and is session-fatal.
45//!
46//! The function itself stays uncalled by production code because it allocates, and the composed
47//! root executes inside the forked child's `pre_exec` window, which must not — see
48//! [`bind_mount_staged_runtimes`]'s own doc comment. It remains valuable as an independently
49//! provable statement of what the planned step must do on a real kernel, without needing a sealed
50//! capsule, a `pivot_root` or the enforcement pipeline to demonstrate it.
51
52#[cfg(target_os = "linux")]
53use std::path::{Path, PathBuf};
54
55use murmur_artifact::{ContainmentClass, StagedRuntimeGrant};
56
57use crate::errors::RuntimeError;
58
59/// Refuses a capsule that declares `capabilities.shell.staged_runtime` without an effective
60/// `sealed` containment floor.
61///
62/// Compares against the **declared** floor — the already-combined strongest of manifest,
63/// workspace config and `--containment` — and never probes the host. That is the whole point of
64/// keeping it separate from [`crate::containment::check_containment_floor`], which asks the
65/// opposite question (can this host back what was declared?) and has the opposite remedy. A
66/// machine that could deliver `sealed` still fails this check when the capsule did not ask for
67/// `sealed`, because the composed root is only built for a capsule that declared it: launching
68/// anyway would produce a capsule whose interpreter is simply not there, diagnosed as a missing
69/// binary somewhere deep in a task rather than as the policy error it is.
70///
71/// Pure, so the decision is testable on any OS and at any enforcement tier.
72pub fn check_staged_runtime_floor(
73    grants: &[StagedRuntimeGrant],
74    declared: ContainmentClass,
75) -> Result<(), RuntimeError> {
76    if grants.is_empty() || declared >= ContainmentClass::Sealed {
77        return Ok(());
78    }
79
80    Err(RuntimeError::StagedRuntimeRequiresSealed {
81        // Every offending binary, not just the first: an operator fixing this should not have to
82        // re-run to discover the second grant.
83        binaries: grants.iter().map(|grant| grant.binary.clone()).collect(),
84        declared,
85    })
86}
87
88/// Where [`bind_mount_staged_runtimes`] failed, so the error names a step rather than a bare
89/// errno.
90#[cfg(target_os = "linux")]
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum StagedRuntimeMountStage {
93    /// Creating the mount point inside the target root.
94    CreateMountPoint,
95    /// The `MS_BIND | MS_REC` mount itself.
96    Bind,
97    /// The second, `MS_REMOUNT | MS_BIND | MS_RDONLY` call that actually makes the bind read-only.
98    RemountReadOnly,
99}
100
101#[cfg(target_os = "linux")]
102impl std::fmt::Display for StagedRuntimeMountStage {
103    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104        let name = match self {
105            Self::CreateMountPoint => "create mount point",
106            Self::Bind => "bind mount",
107            Self::RemountReadOnly => "remount read-only",
108        };
109        f.write_str(name)
110    }
111}
112
113/// One staged-runtime bind mount that could not be established.
114#[cfg(target_os = "linux")]
115#[derive(Debug, Clone)]
116pub struct StagedRuntimeMountError {
117    /// The `staged_runtime` grant's binary, so the failure names the capsule's own declaration
118    /// rather than only a path.
119    pub binary: String,
120    /// The host tree that was being staged.
121    pub source_path: PathBuf,
122    /// Where it was being staged to, inside the target root.
123    pub target_path: PathBuf,
124    pub stage: StagedRuntimeMountStage,
125    /// `errno` from the failing syscall.
126    pub errno: i32,
127}
128
129#[cfg(target_os = "linux")]
130impl std::fmt::Display for StagedRuntimeMountError {
131    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132        write!(
133            f,
134            "staged runtime for '{}': {} of {} at {} failed (errno {})",
135            self.binary,
136            self.stage,
137            self.source_path.display(),
138            self.target_path.display(),
139            self.errno
140        )
141    }
142}
143
144#[cfg(target_os = "linux")]
145impl std::error::Error for StagedRuntimeMountError {}
146
147/// Re-bases an absolute host path under `root`, preserving it verbatim: `/opt/py` under `/newroot`
148/// is `/newroot/opt/py`.
149///
150/// Identity of the path inside and outside the root is the property the whole mechanism rests on —
151/// `sys.prefix`, shebang lines, `PYTHONHOME` and anything a previous turn wrote to disk all keep
152/// resolving, and the capsule never has to be told its interpreter moved. It is the same rule
153/// [`crate::sealed`] applies to the session workdir, via the same [`crate::sealed::rebase`]
154/// function — reused here rather than reimplemented, so there is exactly one re-basing rule.
155#[cfg(target_os = "linux")]
156fn target_under_root(root: &Path, source_path: &Path) -> PathBuf {
157    crate::sealed::rebase(root, source_path)
158}
159
160/// Bind-mounts every declared `staged_runtime` tree read-only into `root`, each at its own
161/// absolute host path re-based under `root`. Returns the target paths it established, in order.
162///
163/// # Where the launch path performs this, and why it is not here
164///
165/// The staging mounts are live: every `sealed` launch that declares a grant establishes them
166/// before `pivot_root`. They are just not established by calling this function, and the reason is
167/// worth stating rather than leaving for someone to rediscover.
168///
169/// [`crate::sealed`] executes its mounts inside the forked child's `pre_exec` window, where
170/// allocation can deadlock on a malloc lock another thread of the parent held at `fork()`. It
171/// avoids that by splitting the decision (`plan_composed_root`, pure, parent-side) from the
172/// execution (`construct_composed_root`, raw syscalls over `CString`s built before the fork). This
173/// function allocates — it joins paths and creates directories — so calling it from that window
174/// as-is would break the invariant that split exists to protect.
175///
176/// The wiring is therefore a *plan entry*, not a call: each grant's `source_path` is fed to
177/// [`crate::sealed::plan_composed_root`]'s `staged_runtime_read_only` parameter, which lowers to
178/// an allocation-free, **required** `RootOp::Bind { read_only: true }`, planned ahead of every
179/// other step. Note that this is a dedicated parameter and not the pre-existing `extra_read_only`:
180/// entries there are planned via `mirror`, which schedules *nothing at all* for a path the host
181/// does not have, so a missing source would have launched a capsule into a root silently lacking
182/// its runtime tree — the opposite of the guarantee below.
183///
184/// What remains here is the executable, independently provable statement of what that plan entry
185/// must *do*: same re-basing rule, same two-call read-only bind, same failure taxonomy. Its test
186/// is what pins that behaviour down on a real kernel without requiring a sealed capsule, a
187/// `pivot_root`, or the enforcement pipeline.
188///
189/// # Preconditions
190///
191/// The caller must already be inside a mount namespace it is willing to modify — this function
192/// does not create one, on purpose, so it composes with a namespace built for other reasons. Each
193/// `source_path` must exist on the host; a grant naming a missing tree fails at
194/// [`StagedRuntimeMountStage::Bind`] with `ENOENT` rather than being skipped, because a capsule
195/// that declared a pinned runtime and did not get it must not proceed as though it had.
196///
197/// # Read-only takes two calls
198///
199/// A single `mount(MS_BIND | MS_RDONLY)` does **not** produce a read-only bind — the kernel
200/// applies the flag to the new mount only on a follow-up `MS_REMOUNT | MS_BIND`. Both are issued
201/// here, and `MS_NOSUID` rides along on the remount, matching [`crate::sealed`]'s binds.
202#[cfg(target_os = "linux")]
203#[allow(unsafe_code)]
204pub fn bind_mount_staged_runtimes(
205    root: &Path,
206    grants: &[StagedRuntimeGrant],
207) -> Result<Vec<PathBuf>, StagedRuntimeMountError> {
208    use std::ffi::CString;
209    use std::os::unix::ffi::OsStrExt;
210
211    let mut staged = Vec::with_capacity(grants.len());
212
213    for grant in grants {
214        let source = PathBuf::from(&grant.source_path);
215        let target = target_under_root(root, &source);
216        let fail = |stage: StagedRuntimeMountStage, errno: i32| StagedRuntimeMountError {
217            binary: grant.binary.clone(),
218            source_path: source.clone(),
219            target_path: target.clone(),
220            stage,
221            errno,
222        };
223
224        // The mount point has to exist before anything can be bound over it. A runtime tree is a
225        // directory, so this is `mkdir -p`; `EEXIST` is success, which is what `create_dir_all`
226        // already reports.
227        std::fs::create_dir_all(&target).map_err(|error| {
228            fail(
229                StagedRuntimeMountStage::CreateMountPoint,
230                error.raw_os_error().unwrap_or(0),
231            )
232        })?;
233
234        // A NUL byte cannot reach here from a parsed manifest (serde_yaml rejects it in a scalar),
235        // but the conversion is fallible, so report it as the mount-point failure it functionally
236        // is rather than unwrapping in a function that may one day run near a fork.
237        let c_source = CString::new(source.as_os_str().as_bytes())
238            .map_err(|_| fail(StagedRuntimeMountStage::CreateMountPoint, libc::EINVAL))?;
239        let c_target = CString::new(target.as_os_str().as_bytes())
240            .map_err(|_| fail(StagedRuntimeMountStage::CreateMountPoint, libc::EINVAL))?;
241
242        // SAFETY: both pointers are NUL-terminated and outlive each call; the filesystem-type and
243        // data arguments are unused for a bind mount and are passed as NULL, as `mount(2)`
244        // specifies.
245        unsafe {
246            if libc::mount(
247                c_source.as_ptr(),
248                c_target.as_ptr(),
249                std::ptr::null(),
250                libc::MS_BIND | libc::MS_REC,
251                std::ptr::null(),
252            ) != 0
253            {
254                return Err(fail(StagedRuntimeMountStage::Bind, errno()));
255            }
256
257            // The call that actually makes it read-only. Without this the tree above is writable.
258            if libc::mount(
259                std::ptr::null(),
260                c_target.as_ptr(),
261                std::ptr::null(),
262                libc::MS_REMOUNT | libc::MS_BIND | libc::MS_RDONLY | libc::MS_NOSUID,
263                std::ptr::null(),
264            ) != 0
265            {
266                return Err(fail(StagedRuntimeMountStage::RemountReadOnly, errno()));
267            }
268        }
269
270        staged.push(target);
271    }
272
273    Ok(staged)
274}
275
276#[cfg(target_os = "linux")]
277fn errno() -> i32 {
278    std::io::Error::last_os_error().raw_os_error().unwrap_or(0)
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284
285    fn grant(binary: &str, source_path: &str) -> StagedRuntimeGrant {
286        StagedRuntimeGrant {
287            binary: binary.to_string(),
288            source_path: source_path.to_string(),
289            pin: "test-pin-1".to_string(),
290        }
291    }
292
293    #[test]
294    fn no_grants_never_requires_sealed() {
295        for declared in [
296            ContainmentClass::Advisory,
297            ContainmentClass::Scoped,
298            ContainmentClass::Sealed,
299        ] {
300            assert!(check_staged_runtime_floor(&[], declared).is_ok());
301        }
302    }
303
304    #[test]
305    fn staged_runtime_below_sealed_is_refused() {
306        for declared in [ContainmentClass::Advisory, ContainmentClass::Scoped] {
307            let error = check_staged_runtime_floor(&[grant("python3", "/opt/py")], declared)
308                .expect_err("a staged runtime below sealed must be refused");
309            match error {
310                RuntimeError::StagedRuntimeRequiresSealed {
311                    binaries,
312                    declared: reported,
313                } => {
314                    assert_eq!(binaries, vec!["python3".to_string()]);
315                    assert_eq!(reported, declared);
316                }
317                other => panic!("expected StagedRuntimeRequiresSealed, got {other:?}"),
318            }
319        }
320    }
321
322    #[test]
323    fn staged_runtime_at_sealed_is_accepted() {
324        assert!(check_staged_runtime_floor(
325            &[grant("python3", "/opt/py")],
326            ContainmentClass::Sealed
327        )
328        .is_ok());
329    }
330
331    /// Every tier, so a new variant cannot quietly escape a test that iterates "all of them".
332    /// Mirrors the same list in `containment`'s tests.
333    const ALL_TIERS: &[crate::sandbox::EnforcementTier] = &[
334        crate::sandbox::EnforcementTier::KernelSealed,
335        crate::sandbox::EnforcementTier::KernelFull,
336        crate::sandbox::EnforcementTier::KernelSeccompOnly,
337        crate::sandbox::EnforcementTier::EnvironmentOnly,
338    ];
339
340    /// The check is a function of the **declared** floor alone. This is the property that keeps it
341    /// distinct from `check_containment_floor`, so it is asserted rather than left implicit in the
342    /// signature: for every enforcement tier the host might probe as — including
343    /// `KernelSealed`, where the host genuinely could deliver a composed root — a capsule that did
344    /// not declare `sealed` is still refused, and one that did is still accepted.
345    #[test]
346    fn the_check_is_independent_of_the_achieved_tier() {
347        let grants = [grant("python3", "/opt/testbed/conda")];
348
349        for tier in ALL_TIERS {
350            // The tier is deliberately unused by the call below; binding it here is what makes
351            // the claim legible, and `achieved_class_for_tier` proves the tier is a real one that
352            // maps to a class rather than a placeholder.
353            let achieved = crate::containment::achieved_class_for_tier(*tier);
354
355            for declared in [ContainmentClass::Advisory, ContainmentClass::Scoped] {
356                assert!(
357                    check_staged_runtime_floor(&grants, declared).is_err(),
358                    "declared {declared} must be refused regardless of tier {tier:?} \
359                     (which achieves {achieved})"
360                );
361            }
362            assert!(
363                check_staged_runtime_floor(&grants, ContainmentClass::Sealed).is_ok(),
364                "a declared sealed floor must pass regardless of tier {tier:?}"
365            );
366        }
367    }
368
369    #[test]
370    fn refusal_names_every_offending_binary() {
371        let error = check_staged_runtime_floor(
372            &[grant("python3", "/opt/py"), grant("node", "/opt/node")],
373            ContainmentClass::Scoped,
374        )
375        .expect_err("must be refused");
376        let rendered = error.to_string();
377        assert!(rendered.contains("python3"), "{rendered}");
378        assert!(rendered.contains("node"), "{rendered}");
379        assert!(rendered.contains("sealed"), "{rendered}");
380    }
381
382    #[cfg(target_os = "linux")]
383    #[test]
384    fn target_is_the_source_path_rebased_under_root() {
385        assert_eq!(
386            target_under_root(Path::new("/newroot"), Path::new("/opt/testbed/conda")),
387            PathBuf::from("/newroot/opt/testbed/conda")
388        );
389        // A root with a trailing component of its own still nests the full source path.
390        assert_eq!(
391            target_under_root(Path::new("/tmp/mur-root"), Path::new("/usr/lib/python3.9")),
392            PathBuf::from("/tmp/mur-root/usr/lib/python3.9")
393        );
394    }
395
396    // ------------------------------------------------------------------ the real mount test
397    //
398    // `bind_mount_staged_runtimes` is only meaningful against a real kernel, so the test below
399    // mounts for real inside a private mount namespace it creates itself. Two constraints shape
400    // how it is run:
401    //
402    //   * `unshare(CLONE_NEWUSER)` returns `EINVAL` in a multi-threaded process, and libtest runs
403    //     each test on its own thread by default. So the work happens in a re-executed copy of
404    //     this same test binary, run with `--test-threads=1`, where libtest executes the test
405    //     body on the main thread of an otherwise single-threaded process.
406    //   * The inner run is `#[ignore]`d so a normal `cargo test` never picks it up directly — it
407    //     is reached only through the driver below, which is what supplies the env var and the
408    //     single-threaded harness.
409    //
410    // Nothing here uses `pivot_root`, the enforcement pipeline, or `crate::sealed`.
411
412    /// Env var the driver sets to tell the re-executed copy it is the inner run.
413    #[cfg(target_os = "linux")]
414    const INNER_RUN_ENV: &str = "MURMUR_STAGED_RUNTIME_MOUNT_INNER";
415
416    #[cfg(target_os = "linux")]
417    #[test]
418    fn bind_mount_staged_runtimes_mounts_read_only_in_a_private_namespace() {
419        use std::process::Command;
420
421        // The inner run needs a user namespace to get `CAP_SYS_ADMIN` for `mount(2)`. Where the
422        // host forbids that, say so loudly and name what went unproven rather than passing quietly.
423        if !unprivileged_userns_available() {
424            eprintln!(
425                "\n\
426                 ==================== SKIPPED: staged-runtime bind mount ====================\n\
427                 This host does not permit an unprivileged user namespace, so this test could\n\
428                 NOT prove any of the following on this machine:\n\
429                   - that bind_mount_staged_runtimes() establishes a real bind mount\n\
430                   - that the staged tree is READ-ONLY through the target root\n\
431                   - that the source tree's contents are readable through the target root\n\
432                 The pure re-basing and floor-check tests above still ran. Re-run this suite on\n\
433                 a Linux host that permits the unshare -- `unshare -Ur true` succeeding is the\n\
434                 whole test -- before treating the mount behaviour as verified. Where AppArmor\n\
435                 refuses it, `kernel.apparmor_restrict_unprivileged_userns` is the sysctl.\n\
436                 ============================================================================\n"
437            );
438            return;
439        }
440
441        let exe = std::env::current_exe().expect("test binary path");
442        let output = Command::new(exe)
443            .args([
444                "--exact",
445                "staged_runtime::tests::inner_bind_mount_in_private_namespace",
446                "--ignored",
447                "--test-threads=1",
448                "--nocapture",
449            ])
450            .env(INNER_RUN_ENV, "1")
451            .output()
452            .expect("re-exec the test binary for the single-threaded inner run");
453
454        let stdout = String::from_utf8_lossy(&output.stdout);
455        let stderr = String::from_utf8_lossy(&output.stderr);
456        assert!(
457            output.status.success(),
458            "inner mount run failed\n--- stdout ---\n{stdout}\n--- stderr ---\n{stderr}"
459        );
460        // Guard against the inner test silently not being selected: a filter typo would otherwise
461        // leave a passing run that asserted nothing at all.
462        assert!(
463            stdout.contains("1 passed"),
464            "inner run did not execute the mount test\n--- stdout ---\n{stdout}"
465        );
466    }
467
468    /// True when this host lets an unprivileged process create a user namespace.
469    ///
470    /// Answered by `detect_egress_namespace_blocker`, which forks and attempts the `unshare` for
471    /// real rather than reading a knob. Reading knobs gets this wrong on Ubuntu 23.10 and later:
472    /// `/proc/sys/kernel/unprivileged_userns_clone` no longer exists there, and the fallback
473    /// question -- whether `/proc/self/ns/user` exists -- is yes on every kernel built with
474    /// `CONFIG_USER_NS` regardless of whether the `unshare` is permitted. AppArmor's
475    /// `kernel.apparmor_restrict_unprivileged_userns` is what actually refuses it, so the knobs
476    /// report available on precisely the hosts where the inner run then dies at step 10.
477    ///
478    /// The probe unshares `CLONE_NEWUSER | CLONE_NEWNET` where the inner run wants
479    /// `CLONE_NEWUSER | CLONE_NEWNS`. `CLONE_NEWUSER` is the half that gets refused and is common
480    /// to both, so the probe answers the question this guard is asking.
481    #[cfg(target_os = "linux")]
482    fn unprivileged_userns_available() -> bool {
483        crate::network_namespace::detect_egress_namespace_blocker().is_none()
484    }
485
486    /// What the forked child reports back through its exit status. `Ok` is 0; every other value
487    /// names one step, so a failure in the child is diagnosable from the parent without a pipe.
488    #[cfg(target_os = "linux")]
489    fn child_exit_meaning(code: i32) -> &'static str {
490        match code {
491            0 => "success",
492            10 => "unshare(CLONE_NEWUSER|CLONE_NEWNS) failed",
493            11 => "writing /proc/self/setgroups, uid_map or gid_map failed",
494            12 => "making / MS_REC|MS_PRIVATE failed",
495            13 => "bind_mount_staged_runtimes returned Err",
496            14 => "the staged target path was not the source path re-based under the root",
497            15 => "reading the marker file through the target root failed or read wrong contents",
498            16 => "writing an existing file through the target root did NOT fail with EROFS",
499            17 => "creating a new file through the target root did NOT fail with EROFS",
500            18 => "the source tree stopped being writable on the host side",
501            _ => "unrecognised child status",
502        }
503    }
504
505    /// The inner run, driven by the test above. Creates a private mount namespace, stages a
506    /// throwaway tree into a throwaway root, and checks both directions — reads succeed through
507    /// the target, writes are refused with `EROFS`.
508    ///
509    /// The work happens in a `fork()`ed child for one specific reason: `unshare(CLONE_NEWUSER)`
510    /// returns `EINVAL` in a multi-threaded process, and libtest runs the test body on a spawned
511    /// thread even at `--test-threads=1` (the process reports `Threads: 2`). `fork` clones only
512    /// the calling thread, so the child is single-threaded and the call is permitted.
513    ///
514    /// Allocating after `fork` in a threaded parent can deadlock on a malloc lock another thread
515    /// held at fork time. That is why this runs under the driver's `--test-threads=1` re-exec: the
516    /// only other thread is libtest's main thread, parked in a join and allocating nothing, so no
517    /// lock can be held across the fork. Both halves of that arrangement are load-bearing — do not
518    /// drop the re-exec and fork from a normal parallel test run.
519    #[cfg(target_os = "linux")]
520    #[test]
521    #[ignore = "driven by bind_mount_staged_runtimes_mounts_read_only_in_a_private_namespace"]
522    #[allow(unsafe_code)]
523    fn inner_bind_mount_in_private_namespace() {
524        if std::env::var(INNER_RUN_ENV).is_err() {
525            panic!("inner run invoked without {INNER_RUN_ENV}; run the driver test instead");
526        }
527
528        // Everything the child needs, built *before* the fork. The temp dirs are owned by the
529        // parent so they are cleaned up on the host: the child's mounts live only in its own
530        // namespace and vanish when it exits, while the directories themselves are ordinary and
531        // visible to both.
532        let source_tree = tempfile::tempdir().expect("source tree");
533        let root = tempfile::tempdir().expect("target root");
534        let marker = source_tree.path().join("lib").join("marker.txt");
535        std::fs::create_dir_all(marker.parent().unwrap()).expect("create source subdir");
536        std::fs::write(&marker, "staged-runtime-contents").expect("write marker");
537
538        let grants = vec![grant(
539            "python3",
540            source_tree.path().to_str().expect("utf-8 temp path"),
541        )];
542        let expected_target = target_under_root(root.path(), source_tree.path());
543        let staged_marker = expected_target.join("lib").join("marker.txt");
544        let uid = unsafe { libc::geteuid() };
545        let gid = unsafe { libc::getegid() };
546
547        // SAFETY: see the doc comment above — the child touches only its own namespace and exits
548        // via `_exit`, never returning into libtest.
549        let pid = unsafe { libc::fork() };
550        assert!(pid >= 0, "fork failed: {}", std::io::Error::last_os_error());
551
552        if pid == 0 {
553            // ---- child: single-threaded, owns a private namespace, never returns ----
554            let mut code = 0;
555
556            // 1. A private mount namespace, via a user namespace so an unprivileged uid holds
557            //    CAP_SYS_ADMIN inside it and nowhere else.
558            if unsafe { libc::unshare(libc::CLONE_NEWUSER | libc::CLONE_NEWNS) } != 0 {
559                unsafe { libc::_exit(10) };
560            }
561
562            // 2. Map this uid/gid one-to-one, so the staged tree's ownership still reads normally.
563            //    `setgroups` must be denied before `gid_map` becomes writable at all.
564            if std::fs::write("/proc/self/setgroups", "deny").is_err()
565                || std::fs::write("/proc/self/uid_map", format!("{uid} {uid} 1")).is_err()
566                || std::fs::write("/proc/self/gid_map", format!("{gid} {gid} 1")).is_err()
567            {
568                unsafe { libc::_exit(11) };
569            }
570
571            // 3. Private propagation, so nothing below leaks back into the host mount table.
572            if unsafe {
573                libc::mount(
574                    std::ptr::null(),
575                    c"/".as_ptr(),
576                    std::ptr::null(),
577                    libc::MS_REC | libc::MS_PRIVATE,
578                    std::ptr::null(),
579                )
580            } != 0
581            {
582                unsafe { libc::_exit(12) };
583            }
584
585            // 4. The call under test. Nothing above it is `pivot_root`, the enforcement pipeline,
586            //    or `crate::sealed` — the helper takes a plain directory as its root.
587            match bind_mount_staged_runtimes(root.path(), &grants) {
588                Ok(staged) => {
589                    // The target is the source path re-based under the root, not a flattened name.
590                    if staged != vec![expected_target.clone()] {
591                        code = 14;
592                    }
593                }
594                Err(_) => code = 13,
595            }
596
597            // 5a. Reading *through the target root* sees the source tree's contents. This is what
598            //     proves a bind happened rather than an empty directory having been created.
599            if code == 0
600                && std::fs::read_to_string(&staged_marker).ok().as_deref()
601                    != Some("staged-runtime-contents")
602            {
603                code = 15;
604            }
605
606            // 5b. Writing through the target root is refused, specifically with `EROFS`. A
607            //     permission error would mean only that this uid cannot write the tree, which is a
608            //     much weaker property than the mount being read-only.
609            if code == 0
610                && std::fs::write(&staged_marker, "tampered")
611                    .err()
612                    .and_then(|e| e.raw_os_error())
613                    != Some(libc::EROFS)
614            {
615                code = 16;
616            }
617            if code == 0
618                && std::fs::write(expected_target.join("new-file"), "nope")
619                    .err()
620                    .and_then(|e| e.raw_os_error())
621                    != Some(libc::EROFS)
622            {
623                code = 17;
624            }
625
626            // 5c. The source itself stays writable: the read-only flag belongs to the new mount,
627            //     not to the underlying tree.
628            if code == 0 && std::fs::write(&marker, "still-writable-at-source").is_err() {
629                code = 18;
630            }
631
632            unsafe { libc::_exit(code) };
633        }
634
635        // ---- parent ----
636        let mut status = 0;
637        assert_eq!(
638            unsafe { libc::waitpid(pid, &mut status, 0) },
639            pid,
640            "waitpid failed: {}",
641            std::io::Error::last_os_error()
642        );
643        assert!(
644            libc::WIFEXITED(status),
645            "the mount child did not exit normally (status {status})"
646        );
647        let code = libc::WEXITSTATUS(status);
648        assert_eq!(code, 0, "mount child failed: {}", child_exit_meaning(code));
649
650        // The child's mounts were confined to its namespace, so the host still sees an ordinary
651        // empty directory here. Asserted from the parent because it is the one claim the child
652        // structurally cannot make about itself.
653        assert!(
654            !staged_marker.exists(),
655            "the staged bind mount leaked out of the child's mount namespace"
656        );
657    }
658}