Skip to main content

hermit_test_workdir/
lib.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 * All rights reserved.
4 *
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree.
7 */
8
9//! Host-side per-physical-run filesystem isolation inside the pinned root.
10//!
11//! Callers must create their tracer runtime inside the callback and finish its
12//! cleanup before returning. A pre-existing executor could spawn the guest in
13//! its original namespace. This helper does not change the calling thread's
14//! namespace, cwd, or filesystem sharing, and leaves /tmp transport visible.
15
16use std::ffi::OsStr;
17use std::io;
18use std::path::Path;
19
20/// The pinned-root runner requests a fresh /test for each physical run.
21pub const REQUEST_ENV: &str = "HERMIT_E2E_EMPTY_WORKDIR";
22/// The pre-existing mountpoint supplied by the pinned-root container.
23pub const WORKDIR: &str = "/test";
24
25/// Refuse malformed requests instead of silently running without isolation.
26pub fn requested_workdir(value: Option<&OsStr>) -> io::Result<Option<&'static Path>> {
27    match value {
28        None => Ok(None),
29        Some(value) if value == OsStr::new(WORKDIR) => Ok(Some(Path::new(WORKDIR))),
30        Some(value) => Err(io::Error::new(
31            io::ErrorKind::InvalidInput,
32            format!("{REQUEST_ENV} must be {WORKDIR}, got {value:?}"),
33        )),
34    }
35}
36
37/// Run on a new host thread with a fresh tmpfs mounted at /test.
38///
39/// This requires CAP_SYS_ADMIN in the owning user namespace and an existing
40/// /test directory. No user-namespace fallback or shared-directory substitute
41/// is used. Setup errors return before the callback can launch a guest. The
42/// scoped thread is joined on success, error and panic; a callback panic keeps
43/// its original payload. Each invocation creates its own mount namespace.
44pub fn with_isolated_workdir<F, T>(run: F) -> io::Result<T>
45where
46    F: FnOnce() -> T + Send,
47    T: Send,
48{
49    std::thread::scope(|scope| {
50        let thread = std::thread::Builder::new()
51            .name("hermit-test-workdir".into())
52            .spawn_scoped(scope, move || {
53                enter_namespace()?;
54                Ok(run())
55            })?;
56        match thread.join() {
57            Ok(result) => result,
58            Err(panic) => std::panic::resume_unwind(panic),
59        }
60    })
61}
62
63fn syscall_result(result: libc::c_int, operation: &str) -> io::Result<()> {
64    if result == 0 {
65        Ok(())
66    } else {
67        let error = io::Error::last_os_error();
68        Err(io::Error::new(
69            error.kind(),
70            format!("{operation}: {error}"),
71        ))
72    }
73}
74
75fn enter_namespace() -> io::Result<()> {
76    // A new thread is essential: unshare also separates its fs_struct, which
77    // setns could not restore to the caller's original CLONE_FS sharing.
78    syscall_result(
79        unsafe { libc::unshare(libc::CLONE_NEWNS) },
80        "unshare mount namespace",
81    )?;
82    syscall_result(
83        unsafe {
84            libc::mount(
85                std::ptr::null(),
86                c"/".as_ptr(),
87                std::ptr::null(),
88                libc::MS_REC | libc::MS_PRIVATE,
89                std::ptr::null(),
90            )
91        },
92        "make mount propagation private",
93    )?;
94    syscall_result(
95        unsafe {
96            libc::mount(
97                c"tmpfs".as_ptr(),
98                c"/test".as_ptr(),
99                c"tmpfs".as_ptr(),
100                libc::MS_NOSUID | libc::MS_NODEV,
101                c"mode=1777".as_ptr().cast(),
102            )
103        },
104        "mount per-run /test tmpfs",
105    )
106}
107
108#[cfg(test)]
109mod tests {
110    use std::os::unix::ffi::OsStrExt;
111
112    use super::*;
113
114    #[test]
115    fn request_is_exact_and_fail_closed() {
116        assert_eq!(requested_workdir(None).unwrap(), None);
117        assert_eq!(
118            requested_workdir(Some(OsStr::new("/test"))).unwrap(),
119            Some(Path::new("/test"))
120        );
121        for value in [b"".as_slice(), b"/tmp", b"/test/", b"/test\0", b"/test\xff"] {
122            let error = requested_workdir(Some(OsStr::from_bytes(value))).unwrap_err();
123            assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
124            assert!(
125                error
126                    .to_string()
127                    .contains("HERMIT_E2E_EMPTY_WORKDIR must be /test")
128            );
129        }
130    }
131}