hermit_test_workdir/
lib.rs1use std::ffi::OsStr;
17use std::io;
18use std::path::Path;
19
20pub const REQUEST_ENV: &str = "HERMIT_E2E_EMPTY_WORKDIR";
22pub const WORKDIR: &str = "/test";
24
25pub 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
37pub 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 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}