forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

builtin.rs360 lines, 13.0 KiBHistoryRawDownload
1//! The builtin executor through the real sandbox helper. The image source is a stub that returns
2//! a rootfs built from host binaries, so no registry is needed. The tests skip, with a message,
3//! when unprivileged user namespaces are unavailable.
4
5use std::collections::BTreeMap;
6use std::fs;
7use std::future::Future;
8use std::path::{Path, PathBuf};
9use std::time::{Duration, Instant};
10
11use forge_ci::proto::{JobAssignment, Outcome};
12use forge_runner::check::build_rootfs;
13use forge_runner::config::Limits;
14use forge_runner::executor::{BuiltinExecutor, ExecRequest, ExecResult, Executor, ImageSource};
15use forge_runner::oci::{ImageError, PreparedImage, RegistryAuth};
16use forge_runner::sandbox::job_cgroup_path;
17use nix::sys::signal::{Signal, kill};
18use nix::unistd::Pid;
19use tokio::sync::mpsc;
20use tokio_util::sync::CancellationToken;
21
22use crate::common::can_run;
23
24/// Hands out a fixed rootfs for every image, with an env that the job can observe.
25struct LocalRootfs(PathBuf);
26
27impl ImageSource for LocalRootfs {
28 fn prepare<'a>(
29 &'a self,
30 _image: &'a str,
31 _auth: Option<&'a RegistryAuth>,
32 _log: &'a mpsc::Sender<Vec<u8>>,
33 ) -> impl Future<Output = Result<PreparedImage, ImageError>> + Send + 'a {
34 std::future::ready(Ok(PreparedImage {
35 rootfs: self.0.clone(),
36 digest: format!("sha256:{}", "0".repeat(64)),
37 env: vec![
38 "PATH=/usr/local/bin:/usr/bin:/bin".to_owned(),
39 "FROM_IMAGE=yes".to_owned(),
40 ],
41 working_dir: None,
42 user: None,
43 }))
44 }
45}
46
47fn job(run: &str) -> JobAssignment {
48 JobAssignment {
49 job_id: "job_01".to_owned(),
50 job_token: "tok_01_secret_token".to_owned(),
51 repo: "owner/name".to_owned(),
52 clone_url: "https://forge.example/owner/name.git".to_owned(),
53 commit: "a".repeat(40),
54 git_ref: "refs/heads/main".to_owned(),
55 job_name: "build".to_owned(),
56 image: "docker.io/library/alpine:3".to_owned(),
57 run: run.to_owned(),
58 env: BTreeMap::from([("PLAIN".to_owned(), "visible".to_owned())]),
59 secrets: BTreeMap::from([("MY_TOKEN".to_owned(), "hunter2-secret".to_owned())]),
60 artifacts: Vec::new(),
61 timeout_minutes: 5,
62 network: false,
63 cache: Vec::new(),
64 cache_key: String::new(),
65 cache_restore_keys: Vec::new(),
66 memory_bytes: None,
67 }
68}
69
70/// An executor over a rootfs in `dir`, and a fresh workspace under `dir`.
71fn executor(dir: &Path) -> (BuiltinExecutor<LocalRootfs>, PathBuf) {
72 let rootfs = dir.join("rootfs");
73 build_rootfs(&rootfs, &["sh", "sleep", "id", "touch"]).expect("build rootfs");
74 let workspace = dir.join("workspace");
75 fs::create_dir_all(&workspace).expect("create workspace");
76 let helper = PathBuf::from(env!("CARGO_BIN_EXE_forge-runner"));
77 let exec = BuiltinExecutor::new(
78 LocalRootfs(rootfs),
79 Limits::default(),
80 helper,
81 dir.join("jobs"),
82 );
83 (exec, workspace)
84}
85
86/// Runs `job` and returns the result with everything it logged.
87async fn run_job(
88 exec: &BuiltinExecutor<LocalRootfs>,
89 job: &JobAssignment,
90 workspace: &Path,
91 cancel: CancellationToken,
92) -> (ExecResult, String) {
93 let (tx, mut rx) = mpsc::channel::<Vec<u8>>(256);
94 let collector = tokio::spawn(async move {
95 let mut all = Vec::new();
96 while let Some(chunk) = rx.recv().await {
97 all.extend_from_slice(&chunk);
98 }
99 all
100 });
101 let result = exec
102 .run(ExecRequest {
103 job,
104 workspace,
105 logs: tx,
106 cancel,
107 oom: forge_runner::oom::OomSink::default(),
108 memory_budget: None,
109 memory_swap: 0,
110 })
111 .await;
112 let logs = collector.await.expect("log collector");
113 (result, String::from_utf8_lossy(&logs).into_owned())
114}
115
116#[tokio::test]
117async fn job_runs_in_the_sandbox_and_its_output_comes_back() {
118 let _serial = serial().await;
119 if !can_run() {
120 return;
121 }
122 let dir = tempfile::tempdir().expect("tempdir");
123 let (exec, workspace) = executor(dir.path());
124 let run = "echo hi-from-builtin; echo \"env=$FROM_IMAGE,$PLAIN,$CI\"; \
125 echo \"secret=$MY_TOKEN\"; id -u; touch /workspace/out.txt";
126 let (result, logs) = run_job(&exec, &job(run), &workspace, CancellationToken::new()).await;
127
128 assert_eq!(result.outcome, Outcome::Success, "{result:?}\n{logs}");
129 assert_eq!(result.exit_code, Some(0));
130 assert!(logs.contains("hi-from-builtin"), "{logs}");
131 assert!(logs.contains("env=yes,visible,true"), "{logs}");
132 assert!(logs.contains("secret=hunter2-secret"), "{logs}");
133 assert!(
134 logs.lines().any(|l| l == "0"),
135 "not root in the job: {logs}"
136 );
137 assert!(logs.contains("image sha256:"), "{logs}");
138 assert!(
139 workspace.join("out.txt").exists(),
140 "workspace write missing"
141 );
142 assert!(!dir.path().join("jobs/job_01").exists(), "job dir was kept");
143}
144
145#[tokio::test]
146async fn nonzero_exit_is_a_failure_with_its_code() {
147 let _serial = serial().await;
148 if !can_run() {
149 return;
150 }
151 let dir = tempfile::tempdir().expect("tempdir");
152 let (exec, workspace) = executor(dir.path());
153 let (result, logs) = run_job(&exec, &job("exit 3"), &workspace, CancellationToken::new()).await;
154 assert_eq!(result.outcome, Outcome::Failure, "{logs}");
155 assert_eq!(result.exit_code, Some(3));
156}
157
158#[tokio::test]
159async fn cancel_stops_the_container() {
160 let _serial = serial().await;
161 if !can_run() {
162 return;
163 }
164 let dir = tempfile::tempdir().expect("tempdir");
165 let (exec, workspace) = executor(dir.path());
166 let cancel = CancellationToken::new();
167 let stop = cancel.clone();
168 tokio::spawn(async move {
169 tokio::time::sleep(Duration::from_millis(1500)).await;
170 stop.cancel();
171 });
172 let started = Instant::now();
173 let (result, logs) = run_job(&exec, &job("sleep 120"), &workspace, cancel).await;
174 assert_eq!(result.outcome, Outcome::Cancelled, "{logs}");
175 // SIGTERM makes the helper kill its container, so this does not wait out the grace period.
176 assert!(
177 started.elapsed() < Duration::from_secs(25),
178 "{:?}",
179 started.elapsed()
180 );
181}
182
183#[tokio::test]
184async fn sandbox_setup_failure_is_an_error_with_the_reason() {
185 let _serial = serial().await;
186 if !can_run() {
187 return;
188 }
189 let dir = tempfile::tempdir().expect("tempdir");
190 let (exec, _workspace) = executor(dir.path());
191 let missing = dir.path().join("no-such-workspace");
192 let (result, logs) = run_job(&exec, &job("true"), &missing, CancellationToken::new()).await;
193 assert_eq!(result.outcome, Outcome::Error, "{logs}");
194 assert_eq!(result.exit_code, Some(125));
195 let message = result.message.unwrap_or_default();
196 assert!(
197 message.contains("workspace is not a directory"),
198 "{message}"
199 );
200}
201
202/// The builtin tests run in one process. Each takes this lock, so their jobs do not run at once.
203/// The helper-finding test below matches its own job cgroup, not any helper child of the process.
204static SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
205
206async fn serial() -> tokio::sync::MutexGuard<'static, ()> {
207 SERIAL.lock().await
208}
209
210/// The pids of this process's children that are sandbox helpers.
211fn helper_children() -> Vec<u32> {
212 let me = std::process::id();
213 let Ok(entries) = fs::read_dir("/proc") else {
214 return Vec::new();
215 };
216 entries
217 .filter_map(|e| e.ok()?.file_name().to_str()?.parse::<u32>().ok())
218 .filter(|&pid| {
219 let stat = fs::read_to_string(format!("/proc/{pid}/stat")).unwrap_or_default();
220 // The fields after the command name in parentheses start with the state, then ppid.
221 let ppid = stat
222 .rsplit_once(')')
223 .and_then(|(_, rest)| rest.split_whitespace().nth(1))
224 .and_then(|p| p.parse::<u32>().ok());
225 let cmdline = fs::read(format!("/proc/{pid}/cmdline")).unwrap_or_default();
226 ppid == Some(me) && cmdline.windows(9).any(|w| w == b"__sandbox".as_slice())
227 })
228 .collect()
229}
230
231/// The job cgroup directory of the helper with pid `helper`, for job `job_id`.
232fn job_cgroup_dir(job_id: &str, helper: u32) -> PathBuf {
233 let rel = job_cgroup_path(job_id, helper).expect("job cgroup path");
234 Path::new("/sys/fs/cgroup").join(rel.strip_prefix("/").unwrap_or(&rel))
235}
236
237/// The pids listed in a cgroup's `cgroup.procs`.
238fn procs_in(dir: &Path) -> Vec<u32> {
239 fs::read_to_string(dir.join("cgroup.procs"))
240 .unwrap_or_default()
241 .lines()
242 .filter_map(|l| l.trim().parse().ok())
243 .collect()
244}
245
246/// Whether `pid` has exited. A zombie has exited too, it only waits to be reaped.
247fn process_gone(pid: u32) -> bool {
248 match fs::read_to_string(format!("/proc/{pid}/stat")) {
249 Err(_) => true,
250 Ok(stat) => {
251 stat.rsplit_once(')')
252 .and_then(|(_, rest)| rest.split_whitespace().next())
253 == Some("Z")
254 }
255 }
256}
257
258/// Waits up to five seconds for `pid` to exit. A SIGKILLed process leaves its cgroup before it
259/// finishes exiting, so a single check right after the cgroup is gone can still see it running.
260async fn wait_gone(pid: u32) -> bool {
261 let deadline = Instant::now() + Duration::from_secs(5);
262 while !process_gone(pid) {
263 if Instant::now() >= deadline {
264 return false;
265 }
266 tokio::time::sleep(Duration::from_millis(20)).await;
267 }
268 true
269}
270
271/// The helper is SIGKILLed while its job is still running, so it cannot tear the container down.
272/// The executor must then kill the job's processes, remove its cgroup, and remove its job dir.
273#[tokio::test]
274async fn sigkilled_helper_leaves_no_process_behind() {
275 let _serial = serial().await;
276 if !can_run() {
277 return;
278 }
279 let dir = tempfile::tempdir().expect("tempdir");
280 let (exec, workspace) = executor(dir.path());
281 // `trap '' TERM` makes the job ignore SIGTERM. Only the helper's SIGKILL path can stop it.
282 let run = "trap '' TERM; sleep 300";
283 // A job id of its own. `helper_children` also finds the helpers of the other tests in this
284 // process, and only this job's cgroup name identifies this test's helper.
285 let job_id = "job_sigkill";
286 let mut job_spec = job(run);
287 job_spec.job_id = job_id.to_owned();
288
289 let killer = async {
290 let deadline = Instant::now() + Duration::from_secs(30);
291 let (helper, cgroup, procs) = loop {
292 assert!(Instant::now() < deadline, "the job never started");
293 let found = helper_children().into_iter().find_map(|pid| {
294 let cgroup = job_cgroup_dir(job_id, pid);
295 let procs = procs_in(&cgroup);
296 (!procs.is_empty()).then_some((pid, cgroup, procs))
297 });
298 if let Some(found) = found {
299 break found;
300 }
301 tokio::time::sleep(Duration::from_millis(50)).await;
302 };
303 kill(Pid::from_raw(helper as i32), Signal::SIGKILL).expect("kill the helper");
304 (cgroup, procs)
305 };
306
307 let (run_result, (cgroup, procs)) = tokio::join!(
308 run_job(&exec, &job_spec, &workspace, CancellationToken::new()),
309 killer
310 );
311 let (result, logs) = run_result;
312
313 assert_ne!(result.outcome, Outcome::Success, "{logs}");
314 assert!(
315 !cgroup.exists(),
316 "job cgroup {} is still there",
317 cgroup.display()
318 );
319 for pid in &procs {
320 assert!(
321 wait_gone(*pid).await,
322 "job process {pid} survived the helper"
323 );
324 }
325 assert!(
326 !dir.path().join("jobs").join(job_id).exists(),
327 "job dir was kept"
328 );
329}
330
331#[tokio::test]
332async fn network_job_gets_its_own_network_without_private_ranges() {
333 let _serial = serial().await;
334 if !can_run() || forge_runner::sandbox::net::find_pasta().is_none() {
335 eprintln!("skipping: needs user namespaces and pasta");
336 return;
337 }
338 let dir = tempfile::tempdir().expect("tempdir");
339 let (exec, workspace) = executor(dir.path());
340 let mut job = job("read -r l < /etc/resolv.conf; echo \"dns=$l\"; \
341 if (echo > /dev/tcp/169.254.169.254/80) 2>/dev/null; then echo meta=open; \
342 else echo meta=blocked; fi");
343 job.network = true;
344 let (result, logs) = run_job(&exec, &job, &workspace, CancellationToken::new()).await;
345
346 assert_eq!(result.outcome, Outcome::Success, "{result:?}\n{logs}");
347 assert!(logs.contains("dns=nameserver 192.0.2.3"), "{logs}");
348 assert!(logs.contains("meta=blocked"), "{logs}");
349 assert!(!logs.contains("pasta is not installed"), "{logs}");
350 let pid_file = dir.path().join("jobs/job_01/pasta.pid");
351 let leftover = fs::read_dir("/proc")
352 .expect("read /proc")
353 .flatten()
354 .any(|entry| {
355 fs::read(entry.path().join("cmdline")).is_ok_and(|cmd| {
356 String::from_utf8_lossy(&cmd).contains(&*pid_file.to_string_lossy())
357 })
358 });
359 assert!(!leftover, "pasta outlived the job");
360}