zuka
zuka/src/ci/runner.rs

worklyn / zukapublic

Agent-first git hosting. One Rust binary: git over HTTP and SSH, a REST API, MCP, CI, and multi-tenant isolation.

Get a copy: git clone https://zuka.worklyn.com/worklyn/zuka.git
zuka/src/ci/runner.rs
RSrunner.rs14.2 KBDownload
1// Executing a run.
2//
3// What this actually provides, stated plainly because the gap between claimed and
4// real isolation is where people get hurt:
5//
6// * a scrubbed environment — the child inherits nothing but an allowlist, so the
7// service's credentials are not readable from `/proc/self/environ`;
8// * rlimits on CPU, address space, file size and open files (process count is
9// opt-in: `RLIMIT_NPROC` is per-UID and means nothing without a runner uid);
10// * a wall-clock timeout that kills the whole process GROUP, because a step's
11// children are grandchildren of ours and killing the shell orphans them;
12// * a bounded log, so output cannot fill the disk;
13// * a workspace that is deleted afterwards.
14//
15// What it does NOT provide, in standalone mode: a container, a network namespace, or
16// a separate uid unless the operator configured one. **Standalone CI is not a
17// security boundary** — anyone who can push can run code as the service user. It is
18// off by default and the README says this in the same words.
19//
20// A step allowlist was considered and rejected: `sh -c` defeats it in one character.
21// Enforcement is at the OS or it is not enforcement.
22
23use crate::brand;
24use crate::ci::run::{Run, RunStore, Status};
25use crate::ci::spec::Spec;
26use crate::config::Config;
27use crate::git::validate::Name;
28use std::path::Path;
29use std::process::Stdio;
30use std::time::Duration;
31use tokio::io::AsyncReadExt;
32use tokio::process::Command;
33
34/// Environment variables the child is allowed to see, beyond the ones we set.
35const INHERITED: &[&str] = &["PATH", "HOME", "LANG", "TZ"];
36
37/// Everything a step needs that does not change between steps.
38struct Context<'a> {
39 config: &'a Config,
40 runs: &'a RunStore,
41 account: &'a Name,
42 repo: &'a Name,
43 run: &'a Run,
44 workspace: &'a Path,
45}
46
47impl Context<'_> {
48 fn log(&self, text: &str) {
49 let _ = self.runs.append_log(
50 self.account,
51 self.repo,
52 &self.run.id,
53 text.as_bytes(),
54 self.config.ci_log_bytes,
55 );
56 }
57}
58
59pub struct Outcome {
60 pub status: Status,
61 pub exit_code: Option<i32>,
62 pub detail: Option<String>,
63}
64
65/// Check out a revision and run its steps.
66pub async fn execute(
67 config: &Config,
68 runs: &RunStore,
69 account: &Name,
70 repo: &Name,
71 run: &Run,
72 git_dir: &Path,
73) -> Outcome {
74 let workspace = config
75 .data_dir
76 .join("tmp")
77 .join("work")
78 .join(format!("{}-{}", run.id, run.created_at));
79
80 let outcome = execute_in(config, runs, account, repo, run, git_dir, &workspace).await;
81
82 // The workspace is scratch and may contain anything the run wrote.
83 if let Err(e) = std::fs::remove_dir_all(&workspace) {
84 if e.kind() != std::io::ErrorKind::NotFound {
85 eprintln!("[ci] could not clean {}: {e}", workspace.display());
86 }
87 }
88 outcome
89}
90
91async fn execute_in(
92 config: &Config,
93 runs: &RunStore,
94 account: &Name,
95 repo: &Name,
96 run: &Run,
97 git_dir: &Path,
98 workspace: &Path,
99) -> Outcome {
100 let ctx = Context {
101 config,
102 runs,
103 account,
104 repo,
105 run,
106 workspace,
107 };
108
109 if let Err(e) = std::fs::create_dir_all(workspace) {
110 return internal(format!("could not create a workspace: {e}"));
111 }
112
113 // Check out into the workspace without a clone: the object database is right
114 // there, and `--no-checkout` plus `checkout-index` avoids a second copy of it.
115 ctx.log(&format!("$ checkout {}\n", run.sha));
116 if let Err(e) = checkout(git_dir, &run.sha, workspace).await {
117 ctx.log(&format!("{e}\n"));
118 return Outcome {
119 status: Status::Failed,
120 exit_code: None,
121 detail: Some("checkout failed".into()),
122 };
123 }
124
125 let spec_path = workspace.join(brand::ci_filename());
126 let source = match std::fs::read_to_string(&spec_path) {
127 Ok(source) => source,
128 Err(_) => {
129 ctx.log(&format!(
130 "no {} in this revision; nothing to run\n",
131 brand::ci_filename()
132 ));
133 return Outcome {
134 status: Status::Succeeded,
135 exit_code: Some(0),
136 detail: Some("no spec".into()),
137 };
138 }
139 };
140
141 let spec = match Spec::parse(&source) {
142 Ok(spec) => spec,
143 Err(e) => {
144 ctx.log(&format!("{}\n", e.detail_for_user()));
145 return Outcome {
146 status: Status::Failed,
147 exit_code: None,
148 detail: Some("invalid spec".into()),
149 };
150 }
151 };
152
153 if !spec.runs_for(&run.git_ref) {
154 ctx.log(&format!(
155 "{} is not in run.branches; skipped\n",
156 run.git_ref
157 ));
158 return Outcome {
159 status: Status::Succeeded,
160 exit_code: Some(0),
161 detail: Some("skipped".into()),
162 };
163 }
164
165 let deadline = spec.timeout(config.ci_timeout);
166 let started = std::time::Instant::now();
167
168 for step in &spec.run.steps {
169 let remaining = deadline.saturating_sub(started.elapsed());
170 if remaining.is_zero() {
171 return timed_out(&ctx, deadline);
172 }
173
174 ctx.log(&format!("$ {step}\n"));
175 match run_step(&ctx, step, remaining).await {
176 StepResult::Ok => {}
177 StepResult::Failed(code) => {
178 ctx.log(&format!("step failed with exit code {code}\n"));
179 return Outcome {
180 status: Status::Failed,
181 exit_code: Some(code),
182 detail: Some(format!("step failed: {step}")),
183 };
184 }
185 StepResult::TimedOut => return timed_out(&ctx, deadline),
186 StepResult::Internal(detail) => {
187 ctx.log(&format!("{detail}\n"));
188 return internal(detail);
189 }
190 }
191 }
192
193 ctx.log("all steps succeeded\n");
194 Outcome {
195 status: Status::Succeeded,
196 exit_code: Some(0),
197 detail: None,
198 }
199}
200
201enum StepResult {
202 Ok,
203 Failed(i32),
204 TimedOut,
205 Internal(String),
206}
207
208async fn run_step(ctx: &Context<'_>, step: &str, remaining: Duration) -> StepResult {
209 let (config, runs, run) = (ctx.config, ctx.runs, ctx.run);
210 let (account, repo) = (ctx.account, ctx.repo);
211
212 let mut command = Command::new("/bin/sh");
213 command
214 .arg("-c")
215 .arg(step)
216 .current_dir(ctx.workspace)
217 .env_clear()
218 .env("CI", "1")
219 .env(brand::env_name("CI"), "1")
220 .env(brand::env_name("RUN_ID"), &run.id)
221 .env(brand::env_name("SHA"), &run.sha)
222 .env(brand::env_name("REF"), &run.git_ref)
223 .stdin(Stdio::null())
224 .stdout(Stdio::piped())
225 .stderr(Stdio::piped())
226 .kill_on_drop(true);
227
228 for key in INHERITED {
229 if let Ok(value) = std::env::var(key) {
230 command.env(key, value);
231 }
232 }
233
234 #[cfg(unix)]
235 {
236 command.process_group(0);
237 apply_limits(&mut command, config);
238 }
239
240 let mut child = match command.spawn() {
241 Ok(child) => child,
242 Err(e) => return StepResult::Internal(format!("could not start the step: {e}")),
243 };
244 let pid = child.id();
245
246 let mut stdout = child.stdout.take().expect("stdout is piped");
247 let mut stderr = child.stderr.take().expect("stderr is piped");
248 let cap = config.ci_log_bytes;
249
250 // Both pipes drain concurrently. A step that fills stderr while we read only
251 // stdout blocks forever on a 64 KiB pipe.
252 let pump = async {
253 let mut out = [0u8; 8192];
254 let mut err = [0u8; 8192];
255 loop {
256 tokio::select! {
257 read = stdout.read(&mut out) => match read {
258 Ok(0) | Err(_) => break,
259 Ok(n) => { let _ = runs.append_log(account, repo, &run.id, &out[..n], cap); }
260 },
261 read = stderr.read(&mut err) => match read {
262 Ok(0) | Err(_) => break,
263 Ok(n) => { let _ = runs.append_log(account, repo, &run.id, &err[..n], cap); }
264 },
265 }
266 }
267 // Whichever pipe closed first, drain the other.
268 let mut rest = Vec::new();
269 let _ = stdout.read_to_end(&mut rest).await;
270 let _ = runs.append_log(account, repo, &run.id, &rest, cap);
271 rest.clear();
272 let _ = stderr.read_to_end(&mut rest).await;
273 let _ = runs.append_log(account, repo, &run.id, &rest, cap);
274 };
275
276 let waited = tokio::time::timeout(remaining, async {
277 pump.await;
278 child.wait().await
279 })
280 .await;
281
282 match waited {
283 Err(_) => {
284 kill_group(pid);
285 StepResult::TimedOut
286 }
287 Ok(Err(e)) => StepResult::Internal(format!("could not wait for the step: {e}")),
288 Ok(Ok(status)) if status.success() => StepResult::Ok,
289 Ok(Ok(status)) => StepResult::Failed(status.code().unwrap_or(-1)),
290 }
291}
292
293/// Apply resource limits in the child, between fork and exec.
294#[cfg(unix)]
295fn apply_limits(command: &mut Command, config: &Config) {
296 let cpu = config.ci_timeout.as_secs().max(1);
297 let memory = config.ci_memory_bytes;
298 let file_size = config.ci_log_bytes.saturating_mul(4).max(memory);
299 let processes = config.ci_max_processes;
300
301 // SAFETY: only async-signal-safe calls between fork and exec. `setrlimit` is.
302 unsafe {
303 command.pre_exec(move || {
304 set_limit(libc::RLIMIT_CPU, cpu);
305 set_limit(libc::RLIMIT_FSIZE, file_size);
306 set_limit(libc::RLIMIT_NOFILE, 1024);
307 if memory > 0 {
308 set_limit(libc::RLIMIT_AS, memory);
309 }
310 // Off unless the operator asked for it. RLIMIT_NPROC is per-UID: with
311 // the runner sharing a uid with the service it counts processes we do
312 // not control, so a useful-looking value makes `fork` fail on the first
313 // step. It becomes meaningful — and the fork-bomb protection it looks
314 // like — only alongside a dedicated runner uid.
315 if processes > 0 {
316 set_limit(libc::RLIMIT_NPROC, processes);
317 }
318 Ok(())
319 });
320 }
321}
322
323/// Type of the `resource` argument to `setrlimit`.
324///
325/// glibc declares it `__rlimit_resource_t` (u32); musl and the BSDs use `c_int`.
326/// The discriminator is the C library, not the OS — keying on `target_os` compiles
327/// on linux-gnu and fails on linux-musl, which is the target that produces the
328/// static binary this service ships as.
329#[cfg(all(unix, target_os = "linux", target_env = "gnu"))]
330type RlimitResource = u32;
331#[cfg(all(unix, not(all(target_os = "linux", target_env = "gnu"))))]
332type RlimitResource = libc::c_int;
333
334#[cfg(unix)]
335fn set_limit(resource: RlimitResource, value: u64) {
336 let limit = libc::rlimit {
337 rlim_cur: value as libc::rlim_t,
338 rlim_max: value as libc::rlim_t,
339 };
340 // SAFETY: `limit` is a valid, fully initialised rlimit for `resource`.
341 unsafe {
342 libc::setrlimit(resource, &limit);
343 }
344}
345
346fn kill_group(pid: Option<u32>) {
347 #[cfg(unix)]
348 if let Some(pid) = pid {
349 // SAFETY: spawned with `process_group(0)`, so the pgid is the child's own
350 // pid and no unrelated process shares it.
351 unsafe {
352 libc::killpg(pid as libc::pid_t, libc::SIGKILL);
353 }
354 }
355 let _ = pid;
356}
357
358/// Materialise a revision into a workspace.
359///
360/// A temporary index plus `checkout-index`, not a clone and not `archive | tar`:
361/// the object database is already on this disk, so cloning would copy all of it to
362/// read one tree, and piping through `tar` would add an external dependency and a
363/// second process to supervise. This is pure git and writes only under
364/// `GIT_WORK_TREE`.
365async fn checkout(git_dir: &Path, sha: &str, workspace: &Path) -> std::result::Result<(), String> {
366 let index = workspace.with_extension("index");
367
368 let run = |args: Vec<String>| {
369 let index = index.clone();
370 async move {
371 let output = Command::new("git")
372 .env_clear()
373 .env(
374 "PATH",
375 std::env::var("PATH").unwrap_or_else(|_| "/usr/bin:/bin".into()),
376 )
377 .env("GIT_CONFIG_NOSYSTEM", "1")
378 .env("GIT_DIR", git_dir)
379 .env("GIT_WORK_TREE", workspace)
380 .env("GIT_INDEX_FILE", &index)
381 .args(&args)
382 .output()
383 .await
384 .map_err(|e| format!("spawn git: {e}"))?;
385
386 if output.status.success() {
387 Ok(())
388 } else {
389 Err(format!(
390 "git {} failed: {}",
391 args.first().cloned().unwrap_or_default(),
392 String::from_utf8_lossy(&output.stderr).trim()
393 ))
394 }
395 }
396 };
397
398 let outcome = async {
399 run(vec!["read-tree".into(), sha.to_string()]).await?;
400 run(vec![
401 "checkout-index".into(),
402 "--all".into(),
403 "--force".into(),
404 ])
405 .await
406 }
407 .await;
408
409 // The index is scratch and must not outlive the checkout.
410 let _ = std::fs::remove_file(&index);
411 outcome
412}
413
414fn timed_out(ctx: &Context<'_>, deadline: Duration) -> Outcome {
415 ctx.log(&format!("run exceeded its {deadline:?} timeout\n"));
416 Outcome {
417 status: Status::TimedOut,
418 exit_code: None,
419 detail: Some(format!("timed out after {deadline:?}")),
420 }
421}
422
423fn internal(detail: String) -> Outcome {
424 Outcome {
425 status: Status::Failed,
426 exit_code: None,
427 detail: Some(detail),
428 }
429}
430
431#[cfg(test)]
432mod tests {
433 use super::*;
434
435 #[test]
436 fn the_inherited_environment_is_an_allowlist_not_a_passthrough() {
437 // The service's own secrets must not be readable from a step.
438 for dangerous in [
439 "KV_URL",
440 "DENO_KV_ACCESS_TOKEN",
441 "AWS_SECRET_ACCESS_KEY",
442 "LD_PRELOAD",
443 "GIT_CONFIG_GLOBAL",
444 ] {
445 assert!(
446 !INHERITED.contains(&dangerous),
447 "{dangerous} must not be inherited by a CI step"
448 );
449 }
450 assert!(
451 INHERITED.contains(&"PATH"),
452 "a step needs to find its tools"
453 );
454 }
455}