forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

sandbox.rs484 lines, 16.0 KiBHistoryRawDownload
1//! Real sandbox tests. They run `forge-runner __sandbox` with a rootfs built here from the host's
2//! shell and a few utilities plus their shared libraries. Nothing is pulled from a registry, and
3//! there is no network access. The tests skip, with a message, when unprivileged user
4//! namespaces are unavailable.
5
6use std::fs;
7use std::io::Write;
8use std::path::{Path, PathBuf};
9use std::process::{Command, Output, Stdio};
10use std::time::{Duration, Instant};
11
12use std::os::unix::fs::MetadataExt;
13
14use forge_runner::config::Limits;
15use forge_runner::sandbox::SandboxRequest;
16use forge_runner::sandbox::idmap::{IdMap, UsernsMode};
17
18use crate::common::can_run;
19
20/// Utilities copied into the test rootfs. `sh` is the job shell, and the rest are used by the
21/// test scripts.
22const BINARIES: &[&str] = &[
23 "sh", "id", "cat", "grep", "touch", "sleep", "unshare", "chown", "stat", "mkdir",
24];
25
26/// The shared libraries `ldd` reports for `binary`, as absolute host paths.
27fn shared_libs(binary: &Path) -> Vec<PathBuf> {
28 let Ok(out) = Command::new("ldd").arg(binary).output() else {
29 return Vec::new();
30 };
31 String::from_utf8_lossy(&out.stdout)
32 .lines()
33 .filter_map(|line| {
34 let line = line.trim();
35 let path = match line.split_once(" => ") {
36 Some((_, rest)) => rest.split(" (").next()?,
37 None => line.split(" (").next()?,
38 };
39 path.starts_with('/').then(|| PathBuf::from(path))
40 })
41 .collect()
42}
43
44fn copy_into(root: &Path, host: &Path) {
45 let real = fs::canonicalize(host).expect("canonicalize host file");
46 let dest = root.join(host.strip_prefix("/").unwrap_or(host));
47 if let Some(parent) = dest.parent() {
48 fs::create_dir_all(parent).expect("create dest dir");
49 }
50 fs::copy(&real, &dest).expect("copy file into rootfs");
51}
52
53/// Builds a tiny rootfs in `root`: the binaries in `/bin`, their shared libraries at the same
54/// absolute paths, and the empty mount points the spec needs.
55fn build_rootfs(root: &Path) {
56 for dir in [
57 "bin",
58 "proc",
59 "dev",
60 "sys",
61 "tmp",
62 "workspace",
63 "etc",
64 "root",
65 ] {
66 fs::create_dir_all(root.join(dir)).expect("create rootfs dir");
67 }
68 for name in ["null", "zero", "full", "random", "urandom"] {
69 fs::write(root.join("dev").join(name), b"").expect("placeholder device");
70 }
71 fs::write(root.join("etc/hosts"), b"").expect("placeholder hosts");
72 fs::write(root.join("etc/hostname"), b"").expect("placeholder hostname");
73 fs::write(root.join("etc/resolv.conf"), b"").expect("placeholder resolv.conf");
74
75 let mut libs: Vec<PathBuf> = Vec::new();
76 for name in BINARIES {
77 let host = ["/usr/bin", "/bin"]
78 .iter()
79 .map(|dir| Path::new(dir).join(name))
80 .find(|p| p.exists())
81 .unwrap_or_else(|| panic!("{name} not found on this host"));
82 let real = fs::canonicalize(&host).expect("canonicalize binary");
83 fs::copy(&real, root.join("bin").join(name)).expect("copy binary");
84 libs.extend(shared_libs(&real));
85 }
86 libs.sort();
87 libs.dedup();
88 for lib in &libs {
89 copy_into(root, lib);
90 }
91}
92
93fn request(dir: &Path, rootfs: &Path, run: &str, network: bool) -> SandboxRequest {
94 let workspace = dir.join("workspace");
95 fs::create_dir_all(&workspace).expect("create workspace");
96 SandboxRequest {
97 job_id: "job_01".to_owned(),
98 rootfs: rootfs.to_owned(),
99 job_dir: dir.join("jobs/job_01"),
100 workspace,
101 image_env: Vec::new(),
102 env: vec![("FORGE_TEST".to_owned(), "yes".to_owned())],
103 run: run.to_owned(),
104 network,
105 pasta: None,
106 limits: Limits::default(),
107 idmap: IdMap::single(),
108 }
109}
110
111/// The subuid map, or `None` with a message when the host can't provide one.
112fn subuid_map() -> Option<IdMap> {
113 match IdMap::resolve(UsernsMode::Subuid) {
114 Ok(map) if map.is_subuid() => Some(map),
115 Ok(_) => None,
116 Err(e) => {
117 eprintln!("skipping: subordinate ids are not available: {e}");
118 None
119 }
120 }
121}
122
123/// Spawns the helper and writes the request to its stdin. Returns the child, not yet waited on.
124fn spawn_helper(req: &SandboxRequest) -> std::process::Child {
125 let mut child = Command::new(env!("CARGO_BIN_EXE_forge-runner"))
126 .arg("__sandbox")
127 .stdin(Stdio::piped())
128 .stdout(Stdio::piped())
129 .stderr(Stdio::piped())
130 .spawn()
131 .expect("spawn helper");
132 let json = serde_json::to_vec(req).expect("serialize request");
133 let mut stdin = child.stdin.take().expect("helper stdin");
134 stdin.write_all(&json).expect("write request");
135 drop(stdin);
136 child
137}
138
139fn run_helper(req: &SandboxRequest) -> Output {
140 spawn_helper(req).wait_with_output().expect("helper output")
141}
142
143fn stdout_of(out: &Output) -> String {
144 String::from_utf8_lossy(&out.stdout).into_owned()
145}
146
147fn stderr_of(out: &Output) -> String {
148 String::from_utf8_lossy(&out.stderr).into_owned()
149}
150
151#[test]
152fn job_runs_as_root_with_no_capabilities() {
153 if !can_run() {
154 return;
155 }
156 let dir = tempfile::tempdir().expect("tempdir");
157 let rootfs = dir.path().join("rootfs");
158 build_rootfs(&rootfs);
159 let run = "echo hi; id -u; grep -E '^(CapEff|NoNewPrivs|Seccomp):' /proc/self/status; \
160 touch /workspace/f; echo \"$CI $FORGE_CI $HOME $FORGE_TEST\"";
161 let req = request(dir.path(), &rootfs, run, false);
162 let out = run_helper(&req);
163
164 let stdout = stdout_of(&out);
165 let stderr = stderr_of(&out);
166 assert_eq!(out.status.code(), Some(0), "stderr: {stderr}");
167 assert!(stdout.lines().any(|l| l == "hi"), "stdout: {stdout}");
168 assert!(stdout.lines().any(|l| l == "0"), "uid is not 0: {stdout}");
169 assert!(
170 stdout.contains("CapEff:\t0000000000000000"),
171 "capabilities not empty: {stdout}"
172 );
173 assert!(
174 stdout.contains("NoNewPrivs:\t1"),
175 "no_new_privs off: {stdout}"
176 );
177 // Seccomp mode 2 is a filter. The profile is installed by `sandbox::exec::FilteredExecutor`.
178 assert!(
179 stdout.contains("Seccomp:\t2"),
180 "seccomp filter not active: {stdout}"
181 );
182 assert!(
183 stdout.lines().any(|l| l == "true true /root yes"),
184 "env wrong: {stdout}"
185 );
186 assert!(
187 req.workspace.join("f").exists(),
188 "workspace file missing on host"
189 );
190 assert!(!req.job_dir.join("bundle/config.json").exists());
191 assert!(!req.job_dir.exists(), "job dir was not removed");
192}
193
194#[test]
195fn exit_code_is_passed_through() {
196 if !can_run() {
197 return;
198 }
199 let dir = tempfile::tempdir().expect("tempdir");
200 let rootfs = dir.path().join("rootfs");
201 build_rootfs(&rootfs);
202 let out = run_helper(&request(dir.path(), &rootfs, "exit 7", false));
203 assert_eq!(out.status.code(), Some(7), "stderr: {}", stderr_of(&out));
204}
205
206#[test]
207fn unshare_is_denied_inside_the_job() {
208 if !can_run() {
209 return;
210 }
211 let dir = tempfile::tempdir().expect("tempdir");
212 let rootfs = dir.path().join("rootfs");
213 build_rootfs(&rootfs);
214 // Creating a user namespace works on the host. The seccomp filter makes unshare(2) fail with
215 // EPERM inside the job, so this must print "denied".
216 let run = "if unshare --user true 2>/dev/null; then echo allowed; else echo denied; fi";
217 let out = run_helper(&request(dir.path(), &rootfs, run, false));
218 let stdout = stdout_of(&out);
219 assert_eq!(out.status.code(), Some(0), "stderr: {}", stderr_of(&out));
220 assert!(stdout.lines().any(|l| l == "denied"), "stdout: {stdout}");
221 assert!(!stdout.lines().any(|l| l == "allowed"), "stdout: {stdout}");
222}
223
224#[test]
225fn network_false_has_only_loopback() {
226 if !can_run() {
227 return;
228 }
229 let dir = tempfile::tempdir().expect("tempdir");
230 let rootfs = dir.path().join("rootfs");
231 build_rootfs(&rootfs);
232 let out = run_helper(&request(dir.path(), &rootfs, "cat /proc/net/dev", false));
233 let stdout = stdout_of(&out);
234 assert_eq!(out.status.code(), Some(0), "stderr: {}", stderr_of(&out));
235 let interfaces: Vec<&str> = stdout
236 .lines()
237 .filter_map(|l| l.split_once(':').map(|(name, _)| name.trim()))
238 .collect();
239 assert_eq!(interfaces, ["lo"], "unexpected interfaces: {stdout}");
240}
241
242#[test]
243fn network_true_shares_the_host_network() {
244 if !can_run() {
245 return;
246 }
247 let dir = tempfile::tempdir().expect("tempdir");
248 let rootfs = dir.path().join("rootfs");
249 build_rootfs(&rootfs);
250 let out = run_helper(&request(dir.path(), &rootfs, "cat /proc/net/dev", true));
251 let stdout = stdout_of(&out);
252 assert_eq!(out.status.code(), Some(0), "stderr: {}", stderr_of(&out));
253 let names = |text: &str| -> Vec<String> {
254 let mut names: Vec<String> = text
255 .lines()
256 .filter_map(|l| l.split_once(':').map(|(name, _)| name.trim().to_owned()))
257 .collect();
258 names.sort();
259 names
260 };
261 let host = fs::read_to_string("/proc/net/dev").expect("host /proc/net/dev");
262 assert_eq!(
263 names(&stdout),
264 names(&host),
265 "job does not see the host network"
266 );
267}
268
269#[test]
270fn host_sysctl_is_read_only() {
271 if !can_run() {
272 return;
273 }
274 let dir = tempfile::tempdir().expect("tempdir");
275 let rootfs = dir.path().join("rootfs");
276 build_rootfs(&rootfs);
277 let run = "if echo x > /proc/sys/kernel/hostname; then echo WROTE; else echo DENIED; fi";
278 let out = run_helper(&request(dir.path(), &rootfs, run, false));
279 let stdout = stdout_of(&out);
280 assert_eq!(out.status.code(), Some(0), "stderr: {}", stderr_of(&out));
281 assert!(stdout.contains("DENIED"), "write was not denied: {stdout}");
282 assert!(!stdout.contains("WROTE"), "write was allowed: {stdout}");
283}
284
285#[test]
286fn writes_land_in_the_overlay_not_the_image_rootfs() {
287 if !can_run() {
288 return;
289 }
290 let dir = tempfile::tempdir().expect("tempdir");
291 let rootfs = dir.path().join("rootfs");
292 build_rootfs(&rootfs);
293 let out = run_helper(&request(
294 dir.path(),
295 &rootfs,
296 "touch /etc/forge-marker",
297 false,
298 ));
299 assert_eq!(out.status.code(), Some(0), "stderr: {}", stderr_of(&out));
300 assert!(
301 !rootfs.join("etc/forge-marker").exists(),
302 "the job wrote into the image rootfs"
303 );
304}
305
306#[test]
307fn sigterm_kills_the_container_and_the_helper_exits() {
308 if !can_run() {
309 return;
310 }
311 let dir = tempfile::tempdir().expect("tempdir");
312 let rootfs = dir.path().join("rootfs");
313 build_rootfs(&rootfs);
314 let req = request(dir.path(), &rootfs, "sleep 60", false);
315 let child = spawn_helper(&req);
316 // Give the container time to start, so that SIGTERM hits a running job.
317 std::thread::sleep(Duration::from_secs(2));
318 let pid = nix::unistd::Pid::from_raw(i32::try_from(child.id()).expect("pid fits i32"));
319 nix::sys::signal::kill(pid, nix::sys::signal::Signal::SIGTERM).expect("send SIGTERM");
320
321 let started = Instant::now();
322 let out = child.wait_with_output().expect("helper output");
323 assert!(
324 started.elapsed() < Duration::from_secs(20),
325 "helper did not exit after SIGTERM"
326 );
327 assert_eq!(out.status.code(), Some(137), "stderr: {}", stderr_of(&out));
328}
329
330#[test]
331fn setup_failure_exits_125_with_a_reason() {
332 let dir = tempfile::tempdir().expect("tempdir");
333 let missing = dir.path().join("no-such-rootfs");
334 let req = request(dir.path(), &missing, "echo never", false);
335 let out = run_helper(&req);
336 assert_eq!(out.status.code(), Some(125));
337 assert!(
338 stderr_of(&out).contains("forge-sandbox: "),
339 "stderr: {}",
340 stderr_of(&out)
341 );
342}
343
344#[test]
345fn rootfs_is_copied_when_the_overlay_cannot_be_mounted() {
346 if !can_run() {
347 return;
348 }
349 let dir = tempfile::tempdir().expect("tempdir");
350 // A comma in a lower dir can't be written in overlay options, so the overlay mount fails
351 // and the helper falls back to copying the rootfs.
352 let rootfs = dir.path().join("rootfs,copy");
353 build_rootfs(&rootfs);
354 let out = run_helper(&request(
355 dir.path(),
356 &rootfs,
357 "echo copied; touch /etc/forge-marker",
358 false,
359 ));
360 let stdout = stdout_of(&out);
361 let stderr = stderr_of(&out);
362 assert_eq!(out.status.code(), Some(0), "stderr: {stderr}");
363 assert!(stdout.lines().any(|l| l == "copied"), "stdout: {stdout}");
364 assert!(
365 stderr.contains("overlay mount failed"),
366 "no fallback warning: {stderr}"
367 );
368 assert!(!rootfs.join("etc/forge-marker").exists());
369}
370
371/// A request that runs under `map` (subuid mode when `map` has a range).
372fn subuid_request(dir: &Path, rootfs: &Path, run: &str, map: &IdMap) -> SandboxRequest {
373 let mut req = request(dir, rootfs, run, false);
374 req.idmap = map.clone();
375 req
376}
377
378#[test]
379fn subuid_job_can_chown_to_a_subordinate_id() {
380 let Some(map) = subuid_map() else { return };
381 if !can_run() {
382 return;
383 }
384 let dir = tempfile::tempdir().expect("tempdir");
385 let rootfs = dir.path().join("rootfs");
386 build_rootfs(&rootfs);
387 let out = run_helper(&subuid_request(
388 dir.path(),
389 &rootfs,
390 "touch /tmp/f && chown 1000:1000 /tmp/f && stat -c '%u %g' /tmp/f",
391 &map,
392 ));
393 assert_eq!(out.status.code(), Some(0), "stderr: {}", stderr_of(&out));
394 assert_eq!(stdout_of(&out).trim(), "1000 1000");
395}
396
397#[test]
398fn subuid_uid_and_gid_maps_have_one_plus_the_range() {
399 let Some(map) = subuid_map() else { return };
400 if !can_run() {
401 return;
402 }
403 let dir = tempfile::tempdir().expect("tempdir");
404 let rootfs = dir.path().join("rootfs");
405 build_rootfs(&rootfs);
406 let out = run_helper(&subuid_request(
407 dir.path(),
408 &rootfs,
409 "cat /proc/self/uid_map; cat /proc/self/gid_map",
410 &map,
411 ));
412 let stdout = stdout_of(&out);
413 assert_eq!(out.status.code(), Some(0), "stderr: {}", stderr_of(&out));
414 // Each line is `inside outside count`. The job's root plus the subordinate range make the
415 // map's size, which is `1 + n`, in one or two lines. Sum the counts for each map.
416 let sizes: Vec<u32> = stdout
417 .lines()
418 .filter_map(|l| l.split_whitespace().nth(2)?.parse().ok())
419 .collect();
420 assert_eq!(sizes.len(), 4, "stdout: {stdout}");
421 let (uid_sizes, gid_sizes) = sizes.split_at(2);
422 assert_eq!(
423 uid_sizes.iter().sum::<u32>(),
424 map.size(),
425 "stdout: {stdout}"
426 );
427 assert_eq!(
428 gid_sizes.iter().sum::<u32>(),
429 map.size(),
430 "stdout: {stdout}"
431 );
432 assert!(map.size() > 1, "the range is empty");
433}
434
435#[test]
436fn subuid_job_files_are_owned_by_the_runner_afterwards() {
437 let Some(map) = subuid_map() else { return };
438 if !can_run() {
439 return;
440 }
441 let dir = tempfile::tempdir().expect("tempdir");
442 let rootfs = dir.path().join("rootfs");
443 build_rootfs(&rootfs);
444 let req = subuid_request(
445 dir.path(),
446 &rootfs,
447 "touch /workspace/a && chown 1000:1000 /workspace/a \
448 && mkdir /workspace/d && chown 1000:1000 /workspace/d \
449 && touch /workspace/d/x && chown 1000:1000 /workspace/d/x",
450 &map,
451 );
452 let out = run_helper(&req);
453 assert_eq!(out.status.code(), Some(0), "stderr: {}", stderr_of(&out));
454 for path in ["a", "d", "d/x"] {
455 let path = req.workspace.join(path);
456 let meta = fs::symlink_metadata(&path).expect("stat workspace entry");
457 assert_eq!(
458 (meta.uid(), meta.gid()),
459 (map.uid, map.gid),
460 "{} is not owned by the runner",
461 path.display()
462 );
463 }
464}
465
466#[test]
467fn subuid_job_dir_is_removed_afterwards() {
468 let Some(map) = subuid_map() else { return };
469 if !can_run() {
470 return;
471 }
472 let dir = tempfile::tempdir().expect("tempdir");
473 let rootfs = dir.path().join("rootfs");
474 build_rootfs(&rootfs);
475 let req = subuid_request(
476 dir.path(),
477 &rootfs,
478 "touch /workspace/a && chown 1000:1000 /workspace/a",
479 &map,
480 );
481 let out = run_helper(&req);
482 assert_eq!(out.status.code(), Some(0), "stderr: {}", stderr_of(&out));
483 assert!(!req.job_dir.exists(), "the job dir was left behind");
484}